api.go 13 KB

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