api.go 14 KB

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