api.go 19 KB

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