api.go 19 KB

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