api.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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. // Compatibility let compose run with best backward compatibility
  146. Compatibility bool
  147. }
  148. // Apply mutates project according to build options
  149. func (o BuildOptions) Apply(project *types.Project) error {
  150. platform := project.Environment["DOCKER_DEFAULT_PLATFORM"]
  151. for name, service := range project.Services {
  152. if service.Image == "" && service.Build == nil {
  153. return fmt.Errorf("invalid service %q. Must specify either image or build", name)
  154. }
  155. if service.Build == nil {
  156. continue
  157. }
  158. if platform != "" {
  159. if len(service.Build.Platforms) > 0 && !utils.StringContains(service.Build.Platforms, platform) {
  160. return fmt.Errorf("service %q build.platforms does not support value set by DOCKER_DEFAULT_PLATFORM: %s", name, platform)
  161. }
  162. service.Platform = platform
  163. }
  164. if service.Platform != "" {
  165. if len(service.Build.Platforms) > 0 && !utils.StringContains(service.Build.Platforms, service.Platform) {
  166. return fmt.Errorf("service %q build configuration does not support platform: %s", name, service.Platform)
  167. }
  168. }
  169. service.Build.Pull = service.Build.Pull || o.Pull
  170. service.Build.NoCache = service.Build.NoCache || o.NoCache
  171. project.Services[name] = service
  172. }
  173. return nil
  174. }
  175. // CreateOptions group options of the Create API
  176. type CreateOptions struct {
  177. Build *BuildOptions
  178. // Services defines the services user interacts with
  179. Services []string
  180. // Remove legacy containers for services that are not defined in the project
  181. RemoveOrphans bool
  182. // Ignore legacy containers for services that are not defined in the project
  183. IgnoreOrphans bool
  184. // Recreate define the strategy to apply on existing containers
  185. Recreate string
  186. // RecreateDependencies define the strategy to apply on dependencies services
  187. RecreateDependencies string
  188. // Inherit reuse anonymous volumes from previous container
  189. Inherit bool
  190. // Timeout set delay to wait for container to gracefully stop before sending SIGKILL
  191. Timeout *time.Duration
  192. // QuietPull makes the pulling process quiet
  193. QuietPull bool
  194. // AssumeYes assume "yes" as answer to all prompts and run non-interactively
  195. AssumeYes bool
  196. }
  197. // StartOptions group options of the Start API
  198. type StartOptions struct {
  199. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  200. Project *types.Project
  201. // Attach to container and forward logs if not nil
  202. Attach LogConsumer
  203. // AttachTo set the services to attach to
  204. AttachTo []string
  205. // OnExit defines behavior when a container stops
  206. OnExit Cascade
  207. // ExitCodeFrom return exit code from specified service
  208. ExitCodeFrom string
  209. // Wait won't return until containers reached the running|healthy state
  210. Wait bool
  211. WaitTimeout time.Duration
  212. // Services passed in the command line to be started
  213. Services []string
  214. Watch bool
  215. NavigationMenu bool
  216. }
  217. type Cascade int
  218. const (
  219. CascadeIgnore Cascade = iota
  220. CascadeStop Cascade = iota
  221. CascadeFail Cascade = iota
  222. )
  223. // RestartOptions group options of the Restart API
  224. type RestartOptions struct {
  225. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  226. Project *types.Project
  227. // Timeout override container restart timeout
  228. Timeout *time.Duration
  229. // Services passed in the command line to be restarted
  230. Services []string
  231. // NoDeps ignores services dependencies
  232. NoDeps bool
  233. }
  234. // StopOptions group options of the Stop API
  235. type StopOptions struct {
  236. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  237. Project *types.Project
  238. // Timeout override container stop timeout
  239. Timeout *time.Duration
  240. // Services passed in the command line to be stopped
  241. Services []string
  242. }
  243. // UpOptions group options of the Up API
  244. type UpOptions struct {
  245. Create CreateOptions
  246. Start StartOptions
  247. }
  248. // DownOptions group options of the Down API
  249. type DownOptions struct {
  250. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  251. RemoveOrphans bool
  252. // Project is the compose project used to define this app. Might be nil if user ran `down` just with project name
  253. Project *types.Project
  254. // Timeout override container stop timeout
  255. Timeout *time.Duration
  256. // Images remove image used by services. 'all': Remove all images. 'local': Remove only images that don't have a tag
  257. Images string
  258. // Volumes remove volumes, both declared in the `volumes` section and anonymous ones
  259. Volumes bool
  260. // Services passed in the command line to be stopped
  261. Services []string
  262. }
  263. // ConfigOptions group options of the Config API
  264. type ConfigOptions struct {
  265. // Format define the output format used to dump converted application model (json|yaml)
  266. Format string
  267. // Output defines the path to save the application model
  268. Output string
  269. // Resolve image reference to digests
  270. ResolveImageDigests bool
  271. }
  272. // PushOptions group options of the Push API
  273. type PushOptions struct {
  274. Quiet bool
  275. IgnoreFailures bool
  276. ImageMandatory bool
  277. }
  278. // PullOptions group options of the Pull API
  279. type PullOptions struct {
  280. Quiet bool
  281. IgnoreFailures bool
  282. IgnoreBuildable bool
  283. }
  284. // ImagesOptions group options of the Images API
  285. type ImagesOptions struct {
  286. Services []string
  287. }
  288. // KillOptions group options of the Kill API
  289. type KillOptions struct {
  290. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  291. RemoveOrphans bool
  292. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  293. Project *types.Project
  294. // Services passed in the command line to be killed
  295. Services []string
  296. // Signal to send to containers
  297. Signal string
  298. // All can be set to true to try to kill all found containers, independently of their state
  299. All bool
  300. }
  301. // RemoveOptions group options of the Remove API
  302. type RemoveOptions struct {
  303. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  304. Project *types.Project
  305. // Stop option passed in the command line
  306. Stop bool
  307. // Volumes remove anonymous volumes
  308. Volumes bool
  309. // Force don't ask to confirm removal
  310. Force bool
  311. // Services passed in the command line to be removed
  312. Services []string
  313. }
  314. // RunOptions group options of the Run API
  315. type RunOptions struct {
  316. Build *BuildOptions
  317. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  318. Project *types.Project
  319. Name string
  320. Service string
  321. Command []string
  322. Entrypoint []string
  323. Detach bool
  324. AutoRemove bool
  325. Tty bool
  326. Interactive bool
  327. WorkingDir string
  328. User string
  329. Environment []string
  330. CapAdd []string
  331. CapDrop []string
  332. Labels types.Labels
  333. Privileged bool
  334. UseNetworkAliases bool
  335. NoDeps bool
  336. // QuietPull makes the pulling process quiet
  337. QuietPull bool
  338. // used by exec
  339. Index int
  340. }
  341. // AttachOptions group options of the Attach API
  342. type AttachOptions struct {
  343. Project *types.Project
  344. Service string
  345. Index int
  346. DetachKeys string
  347. NoStdin bool
  348. Proxy bool
  349. }
  350. // EventsOptions group options of the Events API
  351. type EventsOptions struct {
  352. Services []string
  353. Consumer func(event Event) error
  354. }
  355. // Event is a container runtime event served by Events API
  356. type Event struct {
  357. Timestamp time.Time
  358. Service string
  359. Container string
  360. Status string
  361. Attributes map[string]string
  362. }
  363. // PortOptions group options of the Port API
  364. type PortOptions struct {
  365. Protocol string
  366. Index int
  367. }
  368. // OCIVersion controls manifest generation to ensure compatibility
  369. // with different registries.
  370. //
  371. // Currently, this is not exposed as an option to the user – Compose uses
  372. // OCI 1.0 mode automatically for ECR registries based on domain and OCI 1.1
  373. // for all other registries.
  374. //
  375. // There are likely other popular registries that do not support the OCI 1.1
  376. // format, so it might make sense to expose this as a CLI flag or see if
  377. // there's a way to generically probe the registry for support level.
  378. type OCIVersion string
  379. const (
  380. OCIVersion1_0 OCIVersion = "1.0"
  381. OCIVersion1_1 OCIVersion = "1.1"
  382. )
  383. // PublishOptions group options of the Publish API
  384. type PublishOptions struct {
  385. ResolveImageDigests bool
  386. OCIVersion OCIVersion
  387. }
  388. func (e Event) String() string {
  389. t := e.Timestamp.Format("2006-01-02 15:04:05.000000")
  390. var attr []string
  391. for k, v := range e.Attributes {
  392. attr = append(attr, fmt.Sprintf("%s=%s", k, v))
  393. }
  394. return fmt.Sprintf("%s container %s %s (%s)\n", t, e.Status, e.Container, strings.Join(attr, ", "))
  395. }
  396. // ListOptions group options of the ls API
  397. type ListOptions struct {
  398. All bool
  399. }
  400. // PsOptions group options of the Ps API
  401. type PsOptions struct {
  402. Project *types.Project
  403. All bool
  404. Services []string
  405. }
  406. // CopyOptions group options of the cp API
  407. type CopyOptions struct {
  408. Source string
  409. Destination string
  410. All bool
  411. Index int
  412. FollowLink bool
  413. CopyUIDGID bool
  414. }
  415. // PortPublisher hold status about published port
  416. type PortPublisher struct {
  417. URL string
  418. TargetPort int
  419. PublishedPort int
  420. Protocol string
  421. }
  422. // ContainerSummary hold high-level description of a container
  423. type ContainerSummary struct {
  424. ID string
  425. Name string
  426. Names []string
  427. Image string
  428. Command string
  429. Project string
  430. Service string
  431. Created int64
  432. State string
  433. Status string
  434. Health string
  435. ExitCode int
  436. Publishers PortPublishers
  437. Labels map[string]string
  438. SizeRw int64 `json:",omitempty"`
  439. SizeRootFs int64 `json:",omitempty"`
  440. Mounts []string
  441. Networks []string
  442. LocalVolumes int
  443. }
  444. // PortPublishers is a slice of PortPublisher
  445. type PortPublishers []PortPublisher
  446. // Len implements sort.Interface
  447. func (p PortPublishers) Len() int {
  448. return len(p)
  449. }
  450. // Less implements sort.Interface
  451. func (p PortPublishers) Less(i, j int) bool {
  452. left := p[i]
  453. right := p[j]
  454. if left.URL != right.URL {
  455. return left.URL < right.URL
  456. }
  457. if left.TargetPort != right.TargetPort {
  458. return left.TargetPort < right.TargetPort
  459. }
  460. if left.PublishedPort != right.PublishedPort {
  461. return left.PublishedPort < right.PublishedPort
  462. }
  463. return left.Protocol < right.Protocol
  464. }
  465. // Swap implements sort.Interface
  466. func (p PortPublishers) Swap(i, j int) {
  467. p[i], p[j] = p[j], p[i]
  468. }
  469. // ContainerProcSummary holds container processes top data
  470. type ContainerProcSummary struct {
  471. ID string
  472. Name string
  473. Processes [][]string
  474. Titles []string
  475. }
  476. // ImageSummary holds container image description
  477. type ImageSummary struct {
  478. ID string
  479. ContainerName string
  480. Repository string
  481. Tag string
  482. Size int64
  483. }
  484. // ServiceStatus hold status about a service
  485. type ServiceStatus struct {
  486. ID string
  487. Name string
  488. Replicas int
  489. Desired int
  490. Ports []string
  491. Publishers []PortPublisher
  492. }
  493. // LogOptions defines optional parameters for the `Log` API
  494. type LogOptions struct {
  495. Project *types.Project
  496. Index int
  497. Services []string
  498. Tail string
  499. Since string
  500. Until string
  501. Follow bool
  502. Timestamps bool
  503. }
  504. // PauseOptions group options of the Pause API
  505. type PauseOptions struct {
  506. // Services passed in the command line to be started
  507. Services []string
  508. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  509. Project *types.Project
  510. }
  511. // ExportOptions group options of the Export API
  512. type ExportOptions struct {
  513. Service string
  514. Index int
  515. Output string
  516. }
  517. // CommitOptions group options of the Commit API
  518. type CommitOptions struct {
  519. Service string
  520. Reference string
  521. Pause bool
  522. Comment string
  523. Author string
  524. Changes opts.ListOpts
  525. Index int
  526. }
  527. type GenerateOptions struct {
  528. // ProjectName to set in the Compose file
  529. ProjectName string
  530. // Containers passed in the command line to be used as reference for service definition
  531. Containers []string
  532. }
  533. const (
  534. // STARTING indicates that stack is being deployed
  535. STARTING string = "Starting"
  536. // RUNNING indicates that stack is deployed and services are running
  537. RUNNING string = "Running"
  538. // UPDATING indicates that some stack resources are being recreated
  539. UPDATING string = "Updating"
  540. // REMOVING indicates that stack is being deleted
  541. REMOVING string = "Removing"
  542. // UNKNOWN indicates unknown stack state
  543. UNKNOWN string = "Unknown"
  544. // FAILED indicates that stack deployment failed
  545. FAILED string = "Failed"
  546. )
  547. const (
  548. // RecreateDiverged to recreate services which configuration diverges from compose model
  549. RecreateDiverged = "diverged"
  550. // RecreateForce to force service container being recreated
  551. RecreateForce = "force"
  552. // RecreateNever to never recreate existing service containers
  553. RecreateNever = "never"
  554. )
  555. // Stack holds the name and state of a compose application/stack
  556. type Stack struct {
  557. ID string
  558. Name string
  559. Status string
  560. ConfigFiles string
  561. Reason string
  562. }
  563. // LogConsumer is a callback to process log messages from services
  564. type LogConsumer interface {
  565. Log(containerName, message string)
  566. Err(containerName, message string)
  567. Status(container, msg string)
  568. Register(container string)
  569. }
  570. // ContainerEventListener is a callback to process ContainerEvent from services
  571. type ContainerEventListener func(event ContainerEvent)
  572. // ContainerEvent notify an event has been collected on source container implementing Service
  573. type ContainerEvent struct {
  574. Type int
  575. // Container is the name of the container _without the project prefix_.
  576. //
  577. // This is only suitable for display purposes within Compose, as it's
  578. // not guaranteed to be unique across services.
  579. Container string
  580. ID string
  581. Service string
  582. Line string
  583. // ContainerEventExit only
  584. ExitCode int
  585. Restarting bool
  586. }
  587. const (
  588. // ContainerEventLog is a ContainerEvent of type log on stdout. Line is set
  589. ContainerEventLog = iota
  590. // ContainerEventErr is a ContainerEvent of type log on stderr. Line is set
  591. ContainerEventErr
  592. // ContainerEventAttach is a ContainerEvent of type attach. First event sent about a container
  593. ContainerEventAttach
  594. // ContainerEventStopped is a ContainerEvent of type stopped.
  595. ContainerEventStopped
  596. // ContainerEventRecreated let consumer know container stopped but his being replaced
  597. ContainerEventRecreated
  598. // ContainerEventExit is a ContainerEvent of type exit. ExitCode is set
  599. ContainerEventExit
  600. // UserCancel user cancelled compose up, we are stopping containers
  601. UserCancel
  602. // HookEventLog is a ContainerEvent of type log on stdout by service hook
  603. HookEventLog
  604. )
  605. // Separator is used for naming components
  606. var Separator = "-"
  607. // GetImageNameOrDefault computes the default image name for a service, used to tag built images
  608. func GetImageNameOrDefault(service types.ServiceConfig, projectName string) string {
  609. imageName := service.Image
  610. if imageName == "" {
  611. imageName = projectName + Separator + service.Name
  612. }
  613. return imageName
  614. }