api.go 20 KB

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