api.go 19 KB

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