api.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 compose
  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) 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. // Stop executes the equivalent to a `compose stop`
  35. Stop(ctx context.Context, project *types.Project, options StopOptions) error
  36. // Up executes the equivalent to a `compose up`
  37. Up(ctx context.Context, project *types.Project, options UpOptions) error
  38. // Down executes the equivalent to a `compose down`
  39. Down(ctx context.Context, projectName string, options DownOptions) error
  40. // Logs executes the equivalent to a `compose logs`
  41. Logs(ctx context.Context, projectName string, consumer LogConsumer, options LogOptions) error
  42. // Ps executes the equivalent to a `compose ps`
  43. Ps(ctx context.Context, projectName string, options PsOptions) ([]ContainerSummary, error)
  44. // List executes the equivalent to a `docker stack ls`
  45. List(ctx context.Context, options ListOptions) ([]Stack, error)
  46. // Convert translate compose model into backend's native format
  47. Convert(ctx context.Context, project *types.Project, options ConvertOptions) ([]byte, error)
  48. // Kill executes the equivalent to a `compose kill`
  49. Kill(ctx context.Context, project *types.Project, options KillOptions) error
  50. // RunOneOffContainer creates a service oneoff container and starts its dependencies
  51. RunOneOffContainer(ctx context.Context, project *types.Project, opts RunOptions) (int, error)
  52. // Remove executes the equivalent to a `compose rm`
  53. Remove(ctx context.Context, project *types.Project, options RemoveOptions) ([]string, error)
  54. // Exec executes a command in a running service container
  55. Exec(ctx context.Context, project *types.Project, opts RunOptions) error
  56. // Pause executes the equivalent to a `compose pause`
  57. Pause(ctx context.Context, project *types.Project) error
  58. // UnPause executes the equivalent to a `compose unpause`
  59. UnPause(ctx context.Context, project *types.Project) error
  60. // Top executes the equivalent to a `compose top`
  61. Top(ctx context.Context, projectName string, services []string) ([]ContainerProcSummary, error)
  62. // Events executes the equivalent to a `compose events`
  63. Events(ctx context.Context, project string, options EventsOptions) error
  64. }
  65. // BuildOptions group options of the Build API
  66. type BuildOptions struct {
  67. // Pull always attempt to pull a newer version of the image
  68. Pull bool
  69. // Progress set type of progress output ("auto", "plain", "tty")
  70. Progress string
  71. // Args set build-time args
  72. Args types.Mapping
  73. }
  74. // CreateOptions group options of the Create API
  75. type CreateOptions struct {
  76. // Services defines the services user interacts with
  77. Services []string
  78. // Remove legacy containers for services that are not defined in the project
  79. RemoveOrphans bool
  80. // Recreate define the strategy to apply on existing containers
  81. Recreate string
  82. // RecreateDependencies define the strategy to apply on dependencies services
  83. RecreateDependencies string
  84. // Inherit reuse anonymous volumes from previous container
  85. Inherit bool
  86. // Timeout set delay to wait for container to gracelfuly stop before sending SIGKILL
  87. Timeout *time.Duration
  88. }
  89. // StartOptions group options of the Start API
  90. type StartOptions struct {
  91. // Attach will attach to service containers and send container logs and events
  92. Attach ContainerEventListener
  93. // Services passed in the command line to be started
  94. Services []string
  95. }
  96. // StopOptions group options of the Stop API
  97. type StopOptions struct {
  98. // Timeout override container stop timeout
  99. Timeout *time.Duration
  100. }
  101. // UpOptions group options of the Up API
  102. type UpOptions struct {
  103. // Detach will create services and return immediately
  104. Detach bool
  105. }
  106. // DownOptions group options of the Down API
  107. type DownOptions struct {
  108. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  109. RemoveOrphans bool
  110. // Project is the compose project used to define this app. Might be nil if user ran `down` just with project name
  111. Project *types.Project
  112. // Timeout override container stop timeout
  113. Timeout *time.Duration
  114. // Images remove image used by services. 'all': Remove all images. 'local': Remove only images that don't have a tag
  115. Images string
  116. // Volumes remove volumes, both declared in the `volumes` section and anonymous ones
  117. Volumes bool
  118. }
  119. // ConvertOptions group options of the Convert API
  120. type ConvertOptions struct {
  121. // Format define the output format used to dump converted application model (json|yaml)
  122. Format string
  123. // Output defines the path to save the application model
  124. Output string
  125. }
  126. // PushOptions group options of the Push API
  127. type PushOptions struct {
  128. IgnoreFailures bool
  129. }
  130. // KillOptions group options of the Kill API
  131. type KillOptions struct {
  132. // Signal to send to containers
  133. Signal string
  134. }
  135. // RemoveOptions group options of the Remove API
  136. type RemoveOptions struct {
  137. // DryRun just list removable resources
  138. DryRun bool
  139. // Volumes remove anonymous volumes
  140. Volumes bool
  141. // Force don't ask to confirm removal
  142. Force bool
  143. }
  144. // RunOptions group options of the Run API
  145. type RunOptions struct {
  146. Name string
  147. Service string
  148. Command []string
  149. Entrypoint []string
  150. Detach bool
  151. AutoRemove bool
  152. Writer io.Writer
  153. Reader io.Reader
  154. Tty bool
  155. WorkingDir string
  156. User string
  157. Environment []string
  158. Labels types.Labels
  159. Privileged bool
  160. UseNetworkAliases bool
  161. // used by exec
  162. Index int
  163. }
  164. // EventsOptions group options of the Events API
  165. type EventsOptions struct {
  166. Services []string
  167. Consumer func(event Event) error
  168. }
  169. // Event is a container runtime event served by Events API
  170. type Event struct {
  171. Timestamp time.Time
  172. Service string
  173. Container string
  174. Status string
  175. Attributes map[string]string
  176. }
  177. func (e Event) String() string {
  178. t := e.Timestamp.Format("2006-01-02 15:04:05.000000")
  179. var attr []string
  180. for k, v := range e.Attributes {
  181. attr = append(attr, fmt.Sprintf("%s=%s", k, v))
  182. }
  183. return fmt.Sprintf("%s container %s %s (%s)\n", t, e.Status, e.Container, strings.Join(attr, ", "))
  184. }
  185. // EnvironmentMap return RunOptions.Environment as a MappingWithEquals
  186. func (opts *RunOptions) EnvironmentMap() types.MappingWithEquals {
  187. environment := types.MappingWithEquals{}
  188. for _, s := range opts.Environment {
  189. parts := strings.SplitN(s, "=", 2)
  190. key := parts[0]
  191. switch {
  192. case len(parts) == 1:
  193. environment[key] = nil
  194. default:
  195. environment[key] = &parts[1]
  196. }
  197. }
  198. return environment
  199. }
  200. // ListOptions group options of the ls API
  201. type ListOptions struct {
  202. All bool
  203. }
  204. // PsOptions group options of the Ps API
  205. type PsOptions struct {
  206. All bool
  207. }
  208. // PortPublisher hold status about published port
  209. type PortPublisher struct {
  210. URL string
  211. TargetPort int
  212. PublishedPort int
  213. Protocol string
  214. }
  215. // ContainerSummary hold high-level description of a container
  216. type ContainerSummary struct {
  217. ID string
  218. Name string
  219. Project string
  220. Service string
  221. State string
  222. Health string
  223. Publishers []PortPublisher
  224. }
  225. // ContainerProcSummary holds container processes top data
  226. type ContainerProcSummary struct {
  227. ID string
  228. Name string
  229. Processes [][]string
  230. Titles []string
  231. }
  232. // ServiceStatus hold status about a service
  233. type ServiceStatus struct {
  234. ID string
  235. Name string
  236. Replicas int
  237. Desired int
  238. Ports []string
  239. Publishers []PortPublisher
  240. }
  241. // LogOptions defines optional parameters for the `Log` API
  242. type LogOptions struct {
  243. Services []string
  244. Tail string
  245. Follow bool
  246. Timestamps bool
  247. }
  248. const (
  249. // STARTING indicates that stack is being deployed
  250. STARTING string = "Starting"
  251. // RUNNING indicates that stack is deployed and services are running
  252. RUNNING string = "Running"
  253. // UPDATING indicates that some stack resources are being recreated
  254. UPDATING string = "Updating"
  255. // REMOVING indicates that stack is being deleted
  256. REMOVING string = "Removing"
  257. // UNKNOWN indicates unknown stack state
  258. UNKNOWN string = "Unknown"
  259. // FAILED indicates that stack deployment failed
  260. FAILED string = "Failed"
  261. )
  262. const (
  263. // RecreateDiverged to recreate services which configuration diverges from compose model
  264. RecreateDiverged = "diverged"
  265. // RecreateForce to force service container being recreated
  266. RecreateForce = "force"
  267. // RecreateNever to never recreate existing service containers
  268. RecreateNever = "never"
  269. )
  270. // Stack holds the name and state of a compose application/stack
  271. type Stack struct {
  272. ID string
  273. Name string
  274. Status string
  275. Reason string
  276. }
  277. // LogConsumer is a callback to process log messages from services
  278. type LogConsumer interface {
  279. Log(name, service, container, message string)
  280. Status(name, container, msg string)
  281. Register(name string, source string)
  282. }
  283. // ContainerEventListener is a callback to process ContainerEvent from services
  284. type ContainerEventListener func(event ContainerEvent)
  285. // ContainerEvent notify an event has been collected on Source container implementing Service
  286. type ContainerEvent struct {
  287. Type int
  288. Source string
  289. Service string
  290. Name string
  291. Line string
  292. ExitCode int
  293. }
  294. const (
  295. // ContainerEventLog is a ContainerEvent of type log. Line is set
  296. ContainerEventLog = iota
  297. // ContainerEventAttach is a ContainerEvent of type attach. First event sent about a container
  298. ContainerEventAttach
  299. // ContainerEventExit is a ContainerEvent of type exit. ExitCode is set
  300. ContainerEventExit
  301. // UserCancel user cancelled compose up, we are stopping containers
  302. UserCancel
  303. )