api.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. // Port executes the equivalent to a `compose port`
  65. Port(ctx context.Context, project string, service string, port int, options PortOptions) (string, int, 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. // StopOptions group options of the Stop API
  101. type StopOptions struct {
  102. // Timeout override container stop timeout
  103. Timeout *time.Duration
  104. }
  105. // UpOptions group options of the Up API
  106. type UpOptions struct {
  107. // Detach will create services and return immediately
  108. Detach bool
  109. // QuietPull makes the pulling process quiet
  110. QuietPull bool
  111. }
  112. // DownOptions group options of the Down API
  113. type DownOptions struct {
  114. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  115. RemoveOrphans bool
  116. // Project is the compose project used to define this app. Might be nil if user ran `down` just with project name
  117. Project *types.Project
  118. // Timeout override container stop timeout
  119. Timeout *time.Duration
  120. // Images remove image used by services. 'all': Remove all images. 'local': Remove only images that don't have a tag
  121. Images string
  122. // Volumes remove volumes, both declared in the `volumes` section and anonymous ones
  123. Volumes bool
  124. }
  125. // ConvertOptions group options of the Convert API
  126. type ConvertOptions struct {
  127. // Format define the output format used to dump converted application model (json|yaml)
  128. Format string
  129. // Output defines the path to save the application model
  130. Output string
  131. }
  132. // PushOptions group options of the Push API
  133. type PushOptions struct {
  134. IgnoreFailures bool
  135. }
  136. // KillOptions group options of the Kill API
  137. type KillOptions struct {
  138. // Signal to send to containers
  139. Signal string
  140. }
  141. // RemoveOptions group options of the Remove API
  142. type RemoveOptions struct {
  143. // DryRun just list removable resources
  144. DryRun bool
  145. // Volumes remove anonymous volumes
  146. Volumes bool
  147. // Force don't ask to confirm removal
  148. Force bool
  149. }
  150. // RunOptions group options of the Run API
  151. type RunOptions struct {
  152. Name string
  153. Service string
  154. Command []string
  155. Entrypoint []string
  156. Detach bool
  157. AutoRemove bool
  158. Writer io.Writer
  159. Reader io.Reader
  160. Tty bool
  161. WorkingDir string
  162. User string
  163. Environment []string
  164. Labels types.Labels
  165. Privileged bool
  166. UseNetworkAliases bool
  167. // used by exec
  168. Index int
  169. }
  170. // EventsOptions group options of the Events API
  171. type EventsOptions struct {
  172. Services []string
  173. Consumer func(event Event) error
  174. }
  175. // Event is a container runtime event served by Events API
  176. type Event struct {
  177. Timestamp time.Time
  178. Service string
  179. Container string
  180. Status string
  181. Attributes map[string]string
  182. }
  183. // PortOptions group options of the Port API
  184. type PortOptions struct {
  185. Protocol string
  186. Index int
  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(service, container, message string)
  291. Status(container, msg string)
  292. Register(container 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. Container string
  300. Service string
  301. Line string
  302. ExitCode int
  303. }
  304. const (
  305. // ContainerEventLog is a ContainerEvent of type log. Line is set
  306. ContainerEventLog = iota
  307. // ContainerEventAttach is a ContainerEvent of type attach. First event sent about a container
  308. ContainerEventAttach
  309. // ContainerEventExit is a ContainerEvent of type exit. ExitCode is set
  310. ContainerEventExit
  311. // UserCancel user cancelled compose up, we are stopping containers
  312. UserCancel
  313. )