api.go 21 KB

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