api.go 21 KB

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