api.go 13 KB

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