api.go 21 KB

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