1
0

api.go 22 KB

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