api.go 11 KB

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