api.go 13 KB

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