api.go 22 KB

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