api.go 19 KB

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