api.go 20 KB

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