1
0

api.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package api
  14. import (
  15. "context"
  16. "fmt"
  17. "strings"
  18. "time"
  19. "github.com/compose-spec/compose-go/v2/types"
  20. "github.com/docker/compose/v2/pkg/utils"
  21. )
  22. // Service manages a compose project
  23. type Service interface {
  24. // Build executes the equivalent to a `compose build`
  25. Build(ctx context.Context, project *types.Project, options BuildOptions) error
  26. // Push executes the equivalent to a `compose push`
  27. Push(ctx context.Context, project *types.Project, options PushOptions) error
  28. // Pull executes the equivalent of a `compose pull`
  29. Pull(ctx context.Context, project *types.Project, options PullOptions) error
  30. // Create executes the equivalent to a `compose create`
  31. Create(ctx context.Context, project *types.Project, options CreateOptions) error
  32. // Start executes the equivalent to a `compose start`
  33. Start(ctx context.Context, projectName string, options StartOptions) error
  34. // Restart restarts containers
  35. Restart(ctx context.Context, projectName string, options RestartOptions) error
  36. // Stop executes the equivalent to a `compose stop`
  37. Stop(ctx context.Context, projectName string, options StopOptions) error
  38. // Up executes the equivalent to a `compose up`
  39. Up(ctx context.Context, project *types.Project, options UpOptions) error
  40. // Down executes the equivalent to a `compose down`
  41. Down(ctx context.Context, projectName string, options DownOptions) error
  42. // Logs executes the equivalent to a `compose logs`
  43. Logs(ctx context.Context, projectName string, consumer LogConsumer, options LogOptions) error
  44. // Ps executes the equivalent to a `compose ps`
  45. Ps(ctx context.Context, projectName string, options PsOptions) ([]ContainerSummary, error)
  46. // List executes the equivalent to a `docker stack ls`
  47. List(ctx context.Context, options ListOptions) ([]Stack, error)
  48. // Kill executes the equivalent to a `compose kill`
  49. Kill(ctx context.Context, projectName string, options KillOptions) error
  50. // RunOneOffContainer creates a service oneoff container and starts its dependencies
  51. RunOneOffContainer(ctx context.Context, project *types.Project, opts RunOptions) (int, error)
  52. // Remove executes the equivalent to a `compose rm`
  53. Remove(ctx context.Context, projectName string, options RemoveOptions) error
  54. // Exec executes a command in a running service container
  55. Exec(ctx context.Context, projectName string, options RunOptions) (int, error)
  56. // Attach STDIN,STDOUT,STDERR to a running service container
  57. Attach(ctx context.Context, projectName string, options AttachOptions) error
  58. // Copy copies a file/folder between a service container and the local filesystem
  59. Copy(ctx context.Context, projectName string, options CopyOptions) error
  60. // Pause executes the equivalent to a `compose pause`
  61. Pause(ctx context.Context, projectName string, options PauseOptions) error
  62. // UnPause executes the equivalent to a `compose unpause`
  63. UnPause(ctx context.Context, projectName string, options PauseOptions) error
  64. // Top executes the equivalent to a `compose top`
  65. Top(ctx context.Context, projectName string, services []string) ([]ContainerProcSummary, error)
  66. // Events executes the equivalent to a `compose events`
  67. Events(ctx context.Context, projectName string, options EventsOptions) error
  68. // Port executes the equivalent to a `compose port`
  69. Port(ctx context.Context, projectName string, service string, port uint16, options PortOptions) (string, int, error)
  70. // Publish executes the equivalent to a `compose publish`
  71. Publish(ctx context.Context, project *types.Project, repository string, options PublishOptions) error
  72. // Images executes the equivalent of a `compose images`
  73. Images(ctx context.Context, projectName string, options ImagesOptions) ([]ImageSummary, error)
  74. // MaxConcurrency defines upper limit for concurrent operations against engine API
  75. MaxConcurrency(parallel int)
  76. // DryRunMode defines if dry run applies to the command
  77. DryRunMode(ctx context.Context, dryRun bool) (context.Context, error)
  78. // Watch services' development context and sync/notify/rebuild/restart on changes
  79. Watch(ctx context.Context, project *types.Project, services []string, options WatchOptions) error
  80. // Viz generates a graphviz graph of the project services
  81. Viz(ctx context.Context, project *types.Project, options VizOptions) (string, error)
  82. // Wait blocks until at least one of the services' container exits
  83. Wait(ctx context.Context, projectName string, options WaitOptions) (int64, error)
  84. // Scale manages numbers of container instances running per service
  85. Scale(ctx context.Context, project *types.Project, options ScaleOptions) error
  86. // Export a service container's filesystem as a tar archive
  87. Export(ctx context.Context, projectName string, options ExportOptions) error
  88. }
  89. type ScaleOptions struct {
  90. Services []string
  91. }
  92. type WaitOptions struct {
  93. // Services passed in the command line to be waited
  94. Services []string
  95. // Executes a down when a container exits
  96. DownProjectOnContainerExit bool
  97. }
  98. type VizOptions struct {
  99. // IncludeNetworks if true, network names a container is attached to should appear in the graph node
  100. IncludeNetworks bool
  101. // IncludePorts if true, ports a container exposes should appear in the graph node
  102. IncludePorts bool
  103. // IncludeImageName if true, name of the image used to create a container should appear in the graph node
  104. IncludeImageName bool
  105. // Indentation string to be used to indent graphviz code, e.g. "\t", " "
  106. Indentation string
  107. }
  108. // WatchLogger is a reserved name to log watch events
  109. const WatchLogger = "#watch"
  110. // WatchOptions group options of the Watch API
  111. type WatchOptions struct {
  112. Build *BuildOptions
  113. LogTo LogConsumer
  114. Prune bool
  115. }
  116. // BuildOptions group options of the Build API
  117. type BuildOptions struct {
  118. // Pull always attempt to pull a newer version of the image
  119. Pull bool
  120. // Push pushes service images
  121. Push bool
  122. // Progress set type of progress output ("auto", "plain", "tty")
  123. Progress string
  124. // Args set build-time args
  125. Args types.MappingWithEquals
  126. // NoCache disables cache use
  127. NoCache bool
  128. // Quiet make the build process not output to the console
  129. Quiet bool
  130. // Services passed in the command line to be built
  131. Services []string
  132. // Deps also build selected services dependencies
  133. Deps bool
  134. // Ssh authentications passed in the command line
  135. SSHs []types.SSHKey
  136. // Memory limit for the build container
  137. Memory int64
  138. // Builder name passed in the command line
  139. Builder string
  140. }
  141. // Apply mutates project according to build options
  142. func (o BuildOptions) Apply(project *types.Project) error {
  143. platform := project.Environment["DOCKER_DEFAULT_PLATFORM"]
  144. for name, service := range project.Services {
  145. if service.Image == "" && service.Build == nil {
  146. return fmt.Errorf("invalid service %q. Must specify either image or build", name)
  147. }
  148. if service.Build == nil {
  149. continue
  150. }
  151. if platform != "" {
  152. if len(service.Build.Platforms) > 0 && !utils.StringContains(service.Build.Platforms, platform) {
  153. return fmt.Errorf("service %q build.platforms does not support value set by DOCKER_DEFAULT_PLATFORM: %s", name, platform)
  154. }
  155. service.Platform = platform
  156. }
  157. if service.Platform != "" {
  158. if len(service.Build.Platforms) > 0 && !utils.StringContains(service.Build.Platforms, service.Platform) {
  159. return fmt.Errorf("service %q build configuration does not support platform: %s", name, service.Platform)
  160. }
  161. }
  162. service.Build.Pull = service.Build.Pull || o.Pull
  163. service.Build.NoCache = service.Build.NoCache || o.NoCache
  164. project.Services[name] = service
  165. }
  166. return nil
  167. }
  168. // CreateOptions group options of the Create API
  169. type CreateOptions struct {
  170. Build *BuildOptions
  171. // Services defines the services user interacts with
  172. Services []string
  173. // Remove legacy containers for services that are not defined in the project
  174. RemoveOrphans bool
  175. // Ignore legacy containers for services that are not defined in the project
  176. IgnoreOrphans bool
  177. // Recreate define the strategy to apply on existing containers
  178. Recreate string
  179. // RecreateDependencies define the strategy to apply on dependencies services
  180. RecreateDependencies string
  181. // Inherit reuse anonymous volumes from previous container
  182. Inherit bool
  183. // Timeout set delay to wait for container to gracefully stop before sending SIGKILL
  184. Timeout *time.Duration
  185. // QuietPull makes the pulling process quiet
  186. QuietPull bool
  187. }
  188. // StartOptions group options of the Start API
  189. type StartOptions struct {
  190. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  191. Project *types.Project
  192. // Attach to container and forward logs if not nil
  193. Attach LogConsumer
  194. // AttachTo set the services to attach to
  195. AttachTo []string
  196. // OnExit defines behavior when a container stops
  197. OnExit Cascade
  198. // ExitCodeFrom return exit code from specified service
  199. ExitCodeFrom string
  200. // Wait won't return until containers reached the running|healthy state
  201. Wait bool
  202. WaitTimeout time.Duration
  203. // Services passed in the command line to be started
  204. Services []string
  205. Watch bool
  206. NavigationMenu bool
  207. }
  208. type Cascade int
  209. const (
  210. CascadeIgnore Cascade = iota
  211. CascadeStop Cascade = iota
  212. CascadeFail Cascade = iota
  213. )
  214. // RestartOptions group options of the Restart API
  215. type RestartOptions struct {
  216. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  217. Project *types.Project
  218. // Timeout override container restart timeout
  219. Timeout *time.Duration
  220. // Services passed in the command line to be restarted
  221. Services []string
  222. // NoDeps ignores services dependencies
  223. NoDeps bool
  224. }
  225. // StopOptions group options of the Stop API
  226. type StopOptions struct {
  227. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  228. Project *types.Project
  229. // Timeout override container stop timeout
  230. Timeout *time.Duration
  231. // Services passed in the command line to be stopped
  232. Services []string
  233. }
  234. // UpOptions group options of the Up API
  235. type UpOptions struct {
  236. Create CreateOptions
  237. Start StartOptions
  238. }
  239. // DownOptions group options of the Down API
  240. type DownOptions struct {
  241. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  242. RemoveOrphans bool
  243. // Project is the compose project used to define this app. Might be nil if user ran `down` just with project name
  244. Project *types.Project
  245. // Timeout override container stop timeout
  246. Timeout *time.Duration
  247. // Images remove image used by services. 'all': Remove all images. 'local': Remove only images that don't have a tag
  248. Images string
  249. // Volumes remove volumes, both declared in the `volumes` section and anonymous ones
  250. Volumes bool
  251. // Services passed in the command line to be stopped
  252. Services []string
  253. }
  254. // ConfigOptions group options of the Config API
  255. type ConfigOptions struct {
  256. // Format define the output format used to dump converted application model (json|yaml)
  257. Format string
  258. // Output defines the path to save the application model
  259. Output string
  260. // Resolve image reference to digests
  261. ResolveImageDigests bool
  262. }
  263. // PushOptions group options of the Push API
  264. type PushOptions struct {
  265. Quiet bool
  266. IgnoreFailures bool
  267. ImageMandatory bool
  268. }
  269. // PullOptions group options of the Pull API
  270. type PullOptions struct {
  271. Quiet bool
  272. IgnoreFailures bool
  273. IgnoreBuildable bool
  274. }
  275. // ImagesOptions group options of the Images API
  276. type ImagesOptions struct {
  277. Services []string
  278. }
  279. // KillOptions group options of the Kill API
  280. type KillOptions struct {
  281. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  282. RemoveOrphans bool
  283. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  284. Project *types.Project
  285. // Services passed in the command line to be killed
  286. Services []string
  287. // Signal to send to containers
  288. Signal string
  289. // All can be set to true to try to kill all found containers, independently of their state
  290. All bool
  291. }
  292. // RemoveOptions group options of the Remove API
  293. type RemoveOptions struct {
  294. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  295. Project *types.Project
  296. // Stop option passed in the command line
  297. Stop bool
  298. // Volumes remove anonymous volumes
  299. Volumes bool
  300. // Force don't ask to confirm removal
  301. Force bool
  302. // Services passed in the command line to be removed
  303. Services []string
  304. }
  305. // RunOptions group options of the Run API
  306. type RunOptions struct {
  307. Build *BuildOptions
  308. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  309. Project *types.Project
  310. Name string
  311. Service string
  312. Command []string
  313. Entrypoint []string
  314. Detach bool
  315. AutoRemove bool
  316. Tty bool
  317. Interactive bool
  318. WorkingDir string
  319. User string
  320. Environment []string
  321. CapAdd []string
  322. CapDrop []string
  323. Labels types.Labels
  324. Privileged bool
  325. UseNetworkAliases bool
  326. NoDeps bool
  327. // QuietPull makes the pulling process quiet
  328. QuietPull bool
  329. // used by exec
  330. Index int
  331. }
  332. // AttachOptions group options of the Attach API
  333. type AttachOptions struct {
  334. Project *types.Project
  335. Service string
  336. Index int
  337. DetachKeys string
  338. NoStdin bool
  339. Proxy bool
  340. }
  341. // EventsOptions group options of the Events API
  342. type EventsOptions struct {
  343. Services []string
  344. Consumer func(event Event) error
  345. }
  346. // Event is a container runtime event served by Events API
  347. type Event struct {
  348. Timestamp time.Time
  349. Service string
  350. Container string
  351. Status string
  352. Attributes map[string]string
  353. }
  354. // PortOptions group options of the Port API
  355. type PortOptions struct {
  356. Protocol string
  357. Index int
  358. }
  359. // OCIVersion controls manifest generation to ensure compatibility
  360. // with different registries.
  361. //
  362. // Currently, this is not exposed as an option to the user – Compose uses
  363. // OCI 1.0 mode automatically for ECR registries based on domain and OCI 1.1
  364. // for all other registries.
  365. //
  366. // There are likely other popular registries that do not support the OCI 1.1
  367. // format, so it might make sense to expose this as a CLI flag or see if
  368. // there's a way to generically probe the registry for support level.
  369. type OCIVersion string
  370. const (
  371. OCIVersion1_0 OCIVersion = "1.0"
  372. OCIVersion1_1 OCIVersion = "1.1"
  373. )
  374. // PublishOptions group options of the Publish API
  375. type PublishOptions struct {
  376. ResolveImageDigests bool
  377. OCIVersion OCIVersion
  378. }
  379. func (e Event) String() string {
  380. t := e.Timestamp.Format("2006-01-02 15:04:05.000000")
  381. var attr []string
  382. for k, v := range e.Attributes {
  383. attr = append(attr, fmt.Sprintf("%s=%s", k, v))
  384. }
  385. return fmt.Sprintf("%s container %s %s (%s)\n", t, e.Status, e.Container, strings.Join(attr, ", "))
  386. }
  387. // ListOptions group options of the ls API
  388. type ListOptions struct {
  389. All bool
  390. }
  391. // PsOptions group options of the Ps API
  392. type PsOptions struct {
  393. Project *types.Project
  394. All bool
  395. Services []string
  396. }
  397. // CopyOptions group options of the cp API
  398. type CopyOptions struct {
  399. Source string
  400. Destination string
  401. All bool
  402. Index int
  403. FollowLink bool
  404. CopyUIDGID bool
  405. }
  406. // PortPublisher hold status about published port
  407. type PortPublisher struct {
  408. URL string
  409. TargetPort int
  410. PublishedPort int
  411. Protocol string
  412. }
  413. // ContainerSummary hold high-level description of a container
  414. type ContainerSummary struct {
  415. ID string
  416. Name string
  417. Names []string
  418. Image string
  419. Command string
  420. Project string
  421. Service string
  422. Created int64
  423. State string
  424. Status string
  425. Health string
  426. ExitCode int
  427. Publishers PortPublishers
  428. Labels map[string]string
  429. SizeRw int64 `json:",omitempty"`
  430. SizeRootFs int64 `json:",omitempty"`
  431. Mounts []string
  432. Networks []string
  433. LocalVolumes int
  434. }
  435. // PortPublishers is a slice of PortPublisher
  436. type PortPublishers []PortPublisher
  437. // Len implements sort.Interface
  438. func (p PortPublishers) Len() int {
  439. return len(p)
  440. }
  441. // Less implements sort.Interface
  442. func (p PortPublishers) Less(i, j int) bool {
  443. left := p[i]
  444. right := p[j]
  445. if left.URL != right.URL {
  446. return left.URL < right.URL
  447. }
  448. if left.TargetPort != right.TargetPort {
  449. return left.TargetPort < right.TargetPort
  450. }
  451. if left.PublishedPort != right.PublishedPort {
  452. return left.PublishedPort < right.PublishedPort
  453. }
  454. return left.Protocol < right.Protocol
  455. }
  456. // Swap implements sort.Interface
  457. func (p PortPublishers) Swap(i, j int) {
  458. p[i], p[j] = p[j], p[i]
  459. }
  460. // ContainerProcSummary holds container processes top data
  461. type ContainerProcSummary struct {
  462. ID string
  463. Name string
  464. Processes [][]string
  465. Titles []string
  466. }
  467. // ImageSummary holds container image description
  468. type ImageSummary struct {
  469. ID string
  470. ContainerName string
  471. Repository string
  472. Tag string
  473. Size int64
  474. }
  475. // ServiceStatus hold status about a service
  476. type ServiceStatus struct {
  477. ID string
  478. Name string
  479. Replicas int
  480. Desired int
  481. Ports []string
  482. Publishers []PortPublisher
  483. }
  484. // LogOptions defines optional parameters for the `Log` API
  485. type LogOptions struct {
  486. Project *types.Project
  487. Index int
  488. Services []string
  489. Tail string
  490. Since string
  491. Until string
  492. Follow bool
  493. Timestamps bool
  494. }
  495. // PauseOptions group options of the Pause API
  496. type PauseOptions struct {
  497. // Services passed in the command line to be started
  498. Services []string
  499. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  500. Project *types.Project
  501. }
  502. // ExportOptions group options of the Export API
  503. type ExportOptions struct {
  504. Service string
  505. Index int
  506. Output string
  507. }
  508. const (
  509. // STARTING indicates that stack is being deployed
  510. STARTING string = "Starting"
  511. // RUNNING indicates that stack is deployed and services are running
  512. RUNNING string = "Running"
  513. // UPDATING indicates that some stack resources are being recreated
  514. UPDATING string = "Updating"
  515. // REMOVING indicates that stack is being deleted
  516. REMOVING string = "Removing"
  517. // UNKNOWN indicates unknown stack state
  518. UNKNOWN string = "Unknown"
  519. // FAILED indicates that stack deployment failed
  520. FAILED string = "Failed"
  521. )
  522. const (
  523. // RecreateDiverged to recreate services which configuration diverges from compose model
  524. RecreateDiverged = "diverged"
  525. // RecreateForce to force service container being recreated
  526. RecreateForce = "force"
  527. // RecreateNever to never recreate existing service containers
  528. RecreateNever = "never"
  529. )
  530. // Stack holds the name and state of a compose application/stack
  531. type Stack struct {
  532. ID string
  533. Name string
  534. Status string
  535. ConfigFiles string
  536. Reason string
  537. }
  538. // LogConsumer is a callback to process log messages from services
  539. type LogConsumer interface {
  540. Log(containerName, message string)
  541. Err(containerName, message string)
  542. Status(container, msg string)
  543. Register(container string)
  544. }
  545. // ContainerEventListener is a callback to process ContainerEvent from services
  546. type ContainerEventListener func(event ContainerEvent)
  547. // ContainerEvent notify an event has been collected on source container implementing Service
  548. type ContainerEvent struct {
  549. Type int
  550. // Container is the name of the container _without the project prefix_.
  551. //
  552. // This is only suitable for display purposes within Compose, as it's
  553. // not guaranteed to be unique across services.
  554. Container string
  555. ID string
  556. Service string
  557. Line string
  558. // ContainerEventExit only
  559. ExitCode int
  560. Restarting bool
  561. }
  562. const (
  563. // ContainerEventLog is a ContainerEvent of type log on stdout. Line is set
  564. ContainerEventLog = iota
  565. // ContainerEventErr is a ContainerEvent of type log on stderr. Line is set
  566. ContainerEventErr
  567. // ContainerEventAttach is a ContainerEvent of type attach. First event sent about a container
  568. ContainerEventAttach
  569. // ContainerEventStopped is a ContainerEvent of type stopped.
  570. ContainerEventStopped
  571. // ContainerEventRecreated let consumer know container stopped but his being replaced
  572. ContainerEventRecreated
  573. // ContainerEventExit is a ContainerEvent of type exit. ExitCode is set
  574. ContainerEventExit
  575. // UserCancel user cancelled compose up, we are stopping containers
  576. UserCancel
  577. // HookEventLog is a ContainerEvent of type log on stdout by service hook
  578. HookEventLog
  579. )
  580. // Separator is used for naming components
  581. var Separator = "-"
  582. // GetImageNameOrDefault computes the default image name for a service, used to tag built images
  583. func GetImageNameOrDefault(service types.ServiceConfig, projectName string) string {
  584. imageName := service.Image
  585. if imageName == "" {
  586. imageName = projectName + Separator + service.Name
  587. }
  588. return imageName
  589. }