api.go 18 KB

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