api.go 21 KB

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