api.go 12 KB

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