api.go 20 KB

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