api.go 11 KB

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