api.go 19 KB

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