api.go 20 KB

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