api.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. )
  21. // Service manages a compose project
  22. type Service interface {
  23. // Build executes the equivalent to a `compose build`
  24. Build(ctx context.Context, project *types.Project, options BuildOptions) error
  25. // Push executes the equivalent to a `compose push`
  26. Push(ctx context.Context, project *types.Project, options PushOptions) error
  27. // Pull executes the equivalent of a `compose pull`
  28. Pull(ctx context.Context, project *types.Project, options PullOptions) error
  29. // Create executes the equivalent to a `compose create`
  30. Create(ctx context.Context, project *types.Project, options CreateOptions) error
  31. // Start executes the equivalent to a `compose start`
  32. Start(ctx context.Context, projectName string, options StartOptions) error
  33. // Restart restarts containers
  34. Restart(ctx context.Context, projectName string, options RestartOptions) error
  35. // Stop executes the equivalent to a `compose stop`
  36. Stop(ctx context.Context, projectName string, options StopOptions) error
  37. // Up executes the equivalent to a `compose up`
  38. Up(ctx context.Context, project *types.Project, options UpOptions) error
  39. // Down executes the equivalent to a `compose down`
  40. Down(ctx context.Context, projectName string, options DownOptions) error
  41. // Logs executes the equivalent to a `compose logs`
  42. Logs(ctx context.Context, projectName string, consumer LogConsumer, options LogOptions) error
  43. // Ps executes the equivalent to a `compose ps`
  44. Ps(ctx context.Context, projectName string, options PsOptions) ([]ContainerSummary, error)
  45. // List executes the equivalent to a `docker stack ls`
  46. List(ctx context.Context, options ListOptions) ([]Stack, error)
  47. // Convert translate compose model into backend's native format
  48. Convert(ctx context.Context, project *types.Project, options ConvertOptions) ([]byte, error)
  49. // Kill executes the equivalent to a `compose kill`
  50. Kill(ctx context.Context, projectName string, options KillOptions) error
  51. // RunOneOffContainer creates a service oneoff container and starts its dependencies
  52. RunOneOffContainer(ctx context.Context, project *types.Project, opts RunOptions) (int, error)
  53. // Remove executes the equivalent to a `compose rm`
  54. Remove(ctx context.Context, projectName string, options RemoveOptions) error
  55. // Exec executes a command in a running service container
  56. Exec(ctx context.Context, projectName string, options RunOptions) (int, error)
  57. // Copy copies a file/folder between a service container and the local filesystem
  58. Copy(ctx context.Context, projectName string, options CopyOptions) error
  59. // Pause executes the equivalent to a `compose pause`
  60. Pause(ctx context.Context, projectName string, options PauseOptions) error
  61. // UnPause executes the equivalent to a `compose unpause`
  62. UnPause(ctx context.Context, projectName string, options PauseOptions) error
  63. // Top executes the equivalent to a `compose top`
  64. Top(ctx context.Context, projectName string, services []string) ([]ContainerProcSummary, error)
  65. // Events executes the equivalent to a `compose events`
  66. Events(ctx context.Context, projectName string, options EventsOptions) error
  67. // Port executes the equivalent to a `compose port`
  68. Port(ctx context.Context, projectName string, service string, port uint16, options PortOptions) (string, int, error)
  69. // Images executes the equivalent of a `compose images`
  70. Images(ctx context.Context, projectName string, options ImagesOptions) ([]ImageSummary, error)
  71. // MaxConcurrency defines upper limit for concurrent operations against engine API
  72. MaxConcurrency(parallel int)
  73. }
  74. // BuildOptions group options of the Build API
  75. type BuildOptions struct {
  76. // Pull always attempt to pull a newer version of the image
  77. Pull bool
  78. // Progress set type of progress output ("auto", "plain", "tty")
  79. Progress string
  80. // Args set build-time args
  81. Args types.MappingWithEquals
  82. // NoCache disables cache use
  83. NoCache bool
  84. // Quiet make the build process not output to the console
  85. Quiet bool
  86. // Services passed in the command line to be built
  87. Services []string
  88. // Ssh authentications passed in the command line
  89. SSHs []types.SSHKey
  90. }
  91. // CreateOptions group options of the Create API
  92. type CreateOptions struct {
  93. // Services defines the services user interacts with
  94. Services []string
  95. // Remove legacy containers for services that are not defined in the project
  96. RemoveOrphans bool
  97. // Ignore legacy containers for services that are not defined in the project
  98. IgnoreOrphans bool
  99. // Recreate define the strategy to apply on existing containers
  100. Recreate string
  101. // RecreateDependencies define the strategy to apply on dependencies services
  102. RecreateDependencies string
  103. // Inherit reuse anonymous volumes from previous container
  104. Inherit bool
  105. // Timeout set delay to wait for container to gracelfuly stop before sending SIGKILL
  106. Timeout *time.Duration
  107. // QuietPull makes the pulling process quiet
  108. QuietPull bool
  109. }
  110. // StartOptions group options of the Start API
  111. type StartOptions struct {
  112. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  113. Project *types.Project
  114. // Attach to container and forward logs if not nil
  115. Attach LogConsumer
  116. // AttachTo set the services to attach to
  117. AttachTo []string
  118. // CascadeStop stops the application when a container stops
  119. CascadeStop bool
  120. // ExitCodeFrom return exit code from specified service
  121. ExitCodeFrom string
  122. // Wait won't return until containers reached the running|healthy state
  123. Wait bool
  124. // Services passed in the command line to be started
  125. Services []string
  126. }
  127. // RestartOptions group options of the Restart API
  128. type RestartOptions struct {
  129. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  130. Project *types.Project
  131. // Timeout override container restart timeout
  132. Timeout *time.Duration
  133. // Services passed in the command line to be restarted
  134. Services []string
  135. }
  136. // StopOptions group options of the Stop API
  137. type StopOptions struct {
  138. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  139. Project *types.Project
  140. // Timeout override container stop timeout
  141. Timeout *time.Duration
  142. // Services passed in the command line to be stopped
  143. Services []string
  144. }
  145. // UpOptions group options of the Up API
  146. type UpOptions struct {
  147. Create CreateOptions
  148. Start StartOptions
  149. }
  150. // DownOptions group options of the Down API
  151. type DownOptions struct {
  152. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  153. RemoveOrphans bool
  154. // Project is the compose project used to define this app. Might be nil if user ran `down` just with project name
  155. Project *types.Project
  156. // Timeout override container stop timeout
  157. Timeout *time.Duration
  158. // Images remove image used by services. 'all': Remove all images. 'local': Remove only images that don't have a tag
  159. Images string
  160. // Volumes remove volumes, both declared in the `volumes` section and anonymous ones
  161. Volumes bool
  162. }
  163. // ConvertOptions group options of the Convert API
  164. type ConvertOptions struct {
  165. // Format define the output format used to dump converted application model (json|yaml)
  166. Format string
  167. // Output defines the path to save the application model
  168. Output string
  169. // Resolve image reference to digests
  170. ResolveImageDigests bool
  171. }
  172. // PushOptions group options of the Push API
  173. type PushOptions struct {
  174. Quiet bool
  175. IgnoreFailures bool
  176. }
  177. // PullOptions group options of the Pull API
  178. type PullOptions struct {
  179. Quiet bool
  180. IgnoreFailures bool
  181. IgnoreBuildable bool
  182. }
  183. // ImagesOptions group options of the Images API
  184. type ImagesOptions struct {
  185. Services []string
  186. }
  187. // KillOptions group options of the Kill API
  188. type KillOptions struct {
  189. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  190. RemoveOrphans bool
  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. // Services passed in the command line to be killed
  194. Services []string
  195. // Signal to send to containers
  196. Signal string
  197. }
  198. // RemoveOptions group options of the Remove API
  199. type RemoveOptions struct {
  200. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  201. Project *types.Project
  202. // DryRun just list removable resources
  203. DryRun bool
  204. // Volumes remove anonymous volumes
  205. Volumes bool
  206. // Force don't ask to confirm removal
  207. Force bool
  208. // Services passed in the command line to be removed
  209. Services []string
  210. }
  211. // RunOptions group options of the Run API
  212. type RunOptions struct {
  213. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  214. Project *types.Project
  215. Name string
  216. Service string
  217. Command []string
  218. Entrypoint []string
  219. Detach bool
  220. AutoRemove bool
  221. Tty bool
  222. Interactive bool
  223. WorkingDir string
  224. User string
  225. Environment []string
  226. Labels types.Labels
  227. Privileged bool
  228. UseNetworkAliases bool
  229. NoDeps bool
  230. // QuietPull makes the pulling process quiet
  231. QuietPull bool
  232. // used by exec
  233. Index int
  234. }
  235. // EventsOptions group options of the Events API
  236. type EventsOptions struct {
  237. Services []string
  238. Consumer func(event Event) error
  239. }
  240. // Event is a container runtime event served by Events API
  241. type Event struct {
  242. Timestamp time.Time
  243. Service string
  244. Container string
  245. Status string
  246. Attributes map[string]string
  247. }
  248. // PortOptions group options of the Port API
  249. type PortOptions struct {
  250. Protocol string
  251. Index int
  252. }
  253. func (e Event) String() string {
  254. t := e.Timestamp.Format("2006-01-02 15:04:05.000000")
  255. var attr []string
  256. for k, v := range e.Attributes {
  257. attr = append(attr, fmt.Sprintf("%s=%s", k, v))
  258. }
  259. return fmt.Sprintf("%s container %s %s (%s)\n", t, e.Status, e.Container, strings.Join(attr, ", "))
  260. }
  261. // ListOptions group options of the ls API
  262. type ListOptions struct {
  263. All bool
  264. }
  265. // PsOptions group options of the Ps API
  266. type PsOptions struct {
  267. Project *types.Project
  268. All bool
  269. Services []string
  270. }
  271. // CopyOptions group options of the cp API
  272. type CopyOptions struct {
  273. Source string
  274. Destination string
  275. All bool
  276. Index int
  277. FollowLink bool
  278. CopyUIDGID bool
  279. }
  280. // PortPublisher hold status about published port
  281. type PortPublisher struct {
  282. URL string
  283. TargetPort int
  284. PublishedPort int
  285. Protocol string
  286. }
  287. // ContainerSummary hold high-level description of a container
  288. type ContainerSummary struct {
  289. ID string
  290. Name string
  291. Image any
  292. Command string
  293. Project string
  294. Service string
  295. Created int64
  296. State string
  297. Status string
  298. Health string
  299. ExitCode int
  300. Publishers PortPublishers
  301. }
  302. // PortPublishers is a slice of PortPublisher
  303. type PortPublishers []PortPublisher
  304. // Len implements sort.Interface
  305. func (p PortPublishers) Len() int {
  306. return len(p)
  307. }
  308. // Less implements sort.Interface
  309. func (p PortPublishers) Less(i, j int) bool {
  310. left := p[i]
  311. right := p[j]
  312. if left.URL != right.URL {
  313. return left.URL < right.URL
  314. }
  315. if left.TargetPort != right.TargetPort {
  316. return left.TargetPort < right.TargetPort
  317. }
  318. if left.PublishedPort != right.PublishedPort {
  319. return left.PublishedPort < right.PublishedPort
  320. }
  321. return left.Protocol < right.Protocol
  322. }
  323. // Swap implements sort.Interface
  324. func (p PortPublishers) Swap(i, j int) {
  325. p[i], p[j] = p[j], p[i]
  326. }
  327. // ContainerProcSummary holds container processes top data
  328. type ContainerProcSummary struct {
  329. ID string
  330. Name string
  331. Processes [][]string
  332. Titles []string
  333. }
  334. // ImageSummary holds container image description
  335. type ImageSummary struct {
  336. ID string
  337. ContainerName string
  338. Repository string
  339. Tag string
  340. Size int64
  341. }
  342. // ServiceStatus hold status about a service
  343. type ServiceStatus struct {
  344. ID string
  345. Name string
  346. Replicas int
  347. Desired int
  348. Ports []string
  349. Publishers []PortPublisher
  350. }
  351. // LogOptions defines optional parameters for the `Log` API
  352. type LogOptions struct {
  353. Project *types.Project
  354. Services []string
  355. Tail string
  356. Since string
  357. Until string
  358. Follow bool
  359. Timestamps bool
  360. }
  361. // PauseOptions group options of the Pause API
  362. type PauseOptions struct {
  363. // Services passed in the command line to be started
  364. Services []string
  365. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  366. Project *types.Project
  367. }
  368. const (
  369. // STARTING indicates that stack is being deployed
  370. STARTING string = "Starting"
  371. // RUNNING indicates that stack is deployed and services are running
  372. RUNNING string = "Running"
  373. // UPDATING indicates that some stack resources are being recreated
  374. UPDATING string = "Updating"
  375. // REMOVING indicates that stack is being deleted
  376. REMOVING string = "Removing"
  377. // UNKNOWN indicates unknown stack state
  378. UNKNOWN string = "Unknown"
  379. // FAILED indicates that stack deployment failed
  380. FAILED string = "Failed"
  381. )
  382. const (
  383. // RecreateDiverged to recreate services which configuration diverges from compose model
  384. RecreateDiverged = "diverged"
  385. // RecreateForce to force service container being recreated
  386. RecreateForce = "force"
  387. // RecreateNever to never recreate existing service containers
  388. RecreateNever = "never"
  389. )
  390. // Stack holds the name and state of a compose application/stack
  391. type Stack struct {
  392. ID string
  393. Name string
  394. Status string
  395. ConfigFiles string
  396. Reason string
  397. }
  398. // LogConsumer is a callback to process log messages from services
  399. type LogConsumer interface {
  400. Log(containerName, message string)
  401. Err(containerName, message string)
  402. Status(container, msg string)
  403. Register(container string)
  404. }
  405. // ContainerEventListener is a callback to process ContainerEvent from services
  406. type ContainerEventListener func(event ContainerEvent)
  407. // ContainerEvent notify an event has been collected on source container implementing Service
  408. type ContainerEvent struct {
  409. Type int
  410. // Container is the name of the container _without the project prefix_.
  411. //
  412. // This is only suitable for display purposes within Compose, as it's
  413. // not guaranteed to be unique across services.
  414. Container string
  415. Service string
  416. Line string
  417. // ContainerEventExit only
  418. ExitCode int
  419. Restarting bool
  420. }
  421. const (
  422. // ContainerEventLog is a ContainerEvent of type log on stdout. Line is set
  423. ContainerEventLog = iota
  424. // ContainerEventErr is a ContainerEvent of type log on stderr. Line is set
  425. ContainerEventErr
  426. // ContainerEventAttach is a ContainerEvent of type attach. First event sent about a container
  427. ContainerEventAttach
  428. // ContainerEventStopped is a ContainerEvent of type stopped.
  429. ContainerEventStopped
  430. // ContainerEventExit is a ContainerEvent of type exit. ExitCode is set
  431. ContainerEventExit
  432. // UserCancel user cancelled compose up, we are stopping containers
  433. UserCancel
  434. )
  435. // Separator is used for naming components
  436. var Separator = "-"
  437. // GetImageNameOrDefault computes the default image name for a service, used to tag built images
  438. func GetImageNameOrDefault(service types.ServiceConfig, projectName string) string {
  439. imageName := service.Image
  440. if imageName == "" {
  441. imageName = projectName + Separator + service.Name
  442. }
  443. return imageName
  444. }