deploy.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. package stack
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "strings"
  7. "github.com/spf13/cobra"
  8. "golang.org/x/net/context"
  9. "github.com/aanand/compose-file/loader"
  10. composetypes "github.com/aanand/compose-file/types"
  11. "github.com/docker/docker/api/types"
  12. "github.com/docker/docker/api/types/mount"
  13. networktypes "github.com/docker/docker/api/types/network"
  14. "github.com/docker/docker/api/types/swarm"
  15. "github.com/docker/docker/cli"
  16. "github.com/docker/docker/cli/command"
  17. servicecmd "github.com/docker/docker/cli/command/service"
  18. runconfigopts "github.com/docker/docker/runconfig/opts"
  19. "github.com/docker/docker/opts"
  20. "github.com/docker/go-connections/nat"
  21. )
  22. const (
  23. defaultNetworkDriver = "overlay"
  24. )
  25. type deployOptions struct {
  26. composefile string
  27. namespace string
  28. sendRegistryAuth bool
  29. }
  30. func newDeployCommand(dockerCli *command.DockerCli) *cobra.Command {
  31. var opts deployOptions
  32. cmd := &cobra.Command{
  33. Use: "deploy [OPTIONS] STACK",
  34. Aliases: []string{"up"},
  35. Short: "Deploy a new stack or update an existing stack",
  36. Args: cli.ExactArgs(1),
  37. RunE: func(cmd *cobra.Command, args []string) error {
  38. opts.namespace = args[0]
  39. return runDeploy(dockerCli, opts)
  40. },
  41. Tags: map[string]string{"experimental": "", "version": "1.25"},
  42. }
  43. flags := cmd.Flags()
  44. addComposefileFlag(&opts.composefile, flags)
  45. addRegistryAuthFlag(&opts.sendRegistryAuth, flags)
  46. return cmd
  47. }
  48. func runDeploy(dockerCli *command.DockerCli, opts deployOptions) error {
  49. configDetails, err := getConfigDetails(opts)
  50. if err != nil {
  51. return err
  52. }
  53. config, err := loader.Load(configDetails)
  54. if err != nil {
  55. return err
  56. }
  57. ctx := context.Background()
  58. if err := createNetworks(ctx, dockerCli, config.Networks, opts.namespace); err != nil {
  59. return err
  60. }
  61. return deployServices(ctx, dockerCli, config, opts.namespace, opts.sendRegistryAuth)
  62. }
  63. func getConfigDetails(opts deployOptions) (composetypes.ConfigDetails, error) {
  64. var details composetypes.ConfigDetails
  65. var err error
  66. details.WorkingDir, err = os.Getwd()
  67. if err != nil {
  68. return details, err
  69. }
  70. configFile, err := getConfigFile(opts.composefile)
  71. if err != nil {
  72. return details, err
  73. }
  74. // TODO: support multiple files
  75. details.ConfigFiles = []composetypes.ConfigFile{*configFile}
  76. return details, nil
  77. }
  78. func getConfigFile(filename string) (*composetypes.ConfigFile, error) {
  79. bytes, err := ioutil.ReadFile(filename)
  80. if err != nil {
  81. return nil, err
  82. }
  83. config, err := loader.ParseYAML(bytes)
  84. if err != nil {
  85. return nil, err
  86. }
  87. return &composetypes.ConfigFile{
  88. Filename: filename,
  89. Config: config,
  90. }, nil
  91. }
  92. func createNetworks(
  93. ctx context.Context,
  94. dockerCli *command.DockerCli,
  95. networks map[string]composetypes.NetworkConfig,
  96. namespace string,
  97. ) error {
  98. client := dockerCli.Client()
  99. existingNetworks, err := getNetworks(ctx, client, namespace)
  100. if err != nil {
  101. return err
  102. }
  103. existingNetworkMap := make(map[string]types.NetworkResource)
  104. for _, network := range existingNetworks {
  105. existingNetworkMap[network.Name] = network
  106. }
  107. for internalName, network := range networks {
  108. if network.External.Name != "" {
  109. continue
  110. }
  111. name := fmt.Sprintf("%s_%s", namespace, internalName)
  112. if _, exists := existingNetworkMap[name]; exists {
  113. continue
  114. }
  115. createOpts := types.NetworkCreate{
  116. // TODO: support network labels from compose file
  117. Labels: getStackLabels(namespace, nil),
  118. Driver: network.Driver,
  119. Options: network.DriverOpts,
  120. }
  121. if network.Ipam.Driver != "" {
  122. createOpts.IPAM = &networktypes.IPAM{
  123. Driver: network.Ipam.Driver,
  124. }
  125. }
  126. // TODO: IPAMConfig.Config
  127. if createOpts.Driver == "" {
  128. createOpts.Driver = defaultNetworkDriver
  129. }
  130. fmt.Fprintf(dockerCli.Out(), "Creating network %s\n", name)
  131. if _, err := client.NetworkCreate(ctx, name, createOpts); err != nil {
  132. return err
  133. }
  134. }
  135. return nil
  136. }
  137. func convertNetworks(
  138. networks map[string]*composetypes.ServiceNetworkConfig,
  139. namespace string,
  140. name string,
  141. ) []swarm.NetworkAttachmentConfig {
  142. nets := []swarm.NetworkAttachmentConfig{}
  143. for networkName, network := range networks {
  144. nets = append(nets, swarm.NetworkAttachmentConfig{
  145. // TODO: only do this name mangling in one function
  146. Target: namespace + "_" + networkName,
  147. Aliases: append(network.Aliases, name),
  148. })
  149. }
  150. return nets
  151. }
  152. func convertVolumes(
  153. serviceVolumes []string,
  154. stackVolumes map[string]composetypes.VolumeConfig,
  155. namespace string,
  156. ) ([]mount.Mount, error) {
  157. var mounts []mount.Mount
  158. for _, volumeString := range serviceVolumes {
  159. var (
  160. source, target string
  161. mountType mount.Type
  162. readOnly bool
  163. volumeOptions *mount.VolumeOptions
  164. )
  165. // TODO: split Windows path mappings properly
  166. parts := strings.SplitN(volumeString, ":", 3)
  167. if len(parts) == 3 {
  168. source = parts[0]
  169. target = parts[1]
  170. if parts[2] == "ro" {
  171. readOnly = true
  172. }
  173. } else if len(parts) == 2 {
  174. source = parts[0]
  175. target = parts[1]
  176. } else if len(parts) == 1 {
  177. target = parts[0]
  178. }
  179. // TODO: catch Windows paths here
  180. if strings.HasPrefix(source, "/") {
  181. mountType = mount.TypeBind
  182. } else {
  183. mountType = mount.TypeVolume
  184. stackVolume, exists := stackVolumes[source]
  185. if !exists {
  186. // TODO: better error message (include service name)
  187. return nil, fmt.Errorf("Undefined volume: %s", source)
  188. }
  189. if stackVolume.External.Name != "" {
  190. source = stackVolume.External.Name
  191. } else {
  192. volumeOptions = &mount.VolumeOptions{
  193. Labels: stackVolume.Labels,
  194. }
  195. if stackVolume.Driver != "" {
  196. volumeOptions.DriverConfig = &mount.Driver{
  197. Name: stackVolume.Driver,
  198. Options: stackVolume.DriverOpts,
  199. }
  200. }
  201. // TODO: remove this duplication
  202. source = fmt.Sprintf("%s_%s", namespace, source)
  203. }
  204. }
  205. mounts = append(mounts, mount.Mount{
  206. Type: mountType,
  207. Source: source,
  208. Target: target,
  209. ReadOnly: readOnly,
  210. VolumeOptions: volumeOptions,
  211. })
  212. }
  213. return mounts, nil
  214. }
  215. func deployServices(
  216. ctx context.Context,
  217. dockerCli *command.DockerCli,
  218. config *composetypes.Config,
  219. namespace string,
  220. sendAuth bool,
  221. ) error {
  222. apiClient := dockerCli.Client()
  223. out := dockerCli.Out()
  224. services := config.Services
  225. volumes := config.Volumes
  226. existingServices, err := getServices(ctx, apiClient, namespace)
  227. if err != nil {
  228. return err
  229. }
  230. existingServiceMap := make(map[string]swarm.Service)
  231. for _, service := range existingServices {
  232. existingServiceMap[service.Spec.Name] = service
  233. }
  234. for _, service := range services {
  235. name := fmt.Sprintf("%s_%s", namespace, service.Name)
  236. serviceSpec, err := convertService(namespace, service, volumes)
  237. if err != nil {
  238. return err
  239. }
  240. encodedAuth := ""
  241. if sendAuth {
  242. // Retrieve encoded auth token from the image reference
  243. image := serviceSpec.TaskTemplate.ContainerSpec.Image
  244. encodedAuth, err = command.RetrieveAuthTokenFromImage(ctx, dockerCli, image)
  245. if err != nil {
  246. return err
  247. }
  248. }
  249. if service, exists := existingServiceMap[name]; exists {
  250. fmt.Fprintf(out, "Updating service %s (id: %s)\n", name, service.ID)
  251. updateOpts := types.ServiceUpdateOptions{}
  252. if sendAuth {
  253. updateOpts.EncodedRegistryAuth = encodedAuth
  254. }
  255. if err := apiClient.ServiceUpdate(
  256. ctx,
  257. service.ID,
  258. service.Version,
  259. serviceSpec,
  260. updateOpts,
  261. ); err != nil {
  262. return err
  263. }
  264. } else {
  265. fmt.Fprintf(out, "Creating service %s\n", name)
  266. createOpts := types.ServiceCreateOptions{}
  267. if sendAuth {
  268. createOpts.EncodedRegistryAuth = encodedAuth
  269. }
  270. if _, err := apiClient.ServiceCreate(ctx, serviceSpec, createOpts); err != nil {
  271. return err
  272. }
  273. }
  274. }
  275. return nil
  276. }
  277. func convertService(
  278. namespace string,
  279. service composetypes.ServiceConfig,
  280. volumes map[string]composetypes.VolumeConfig,
  281. ) (swarm.ServiceSpec, error) {
  282. // TODO: remove this duplication
  283. name := fmt.Sprintf("%s_%s", namespace, service.Name)
  284. endpoint, err := convertEndpointSpec(service.Ports)
  285. if err != nil {
  286. return swarm.ServiceSpec{}, err
  287. }
  288. mode, err := convertDeployMode(service.Deploy.Mode, service.Deploy.Replicas)
  289. if err != nil {
  290. return swarm.ServiceSpec{}, err
  291. }
  292. mounts, err := convertVolumes(service.Volumes, volumes, namespace)
  293. if err != nil {
  294. return swarm.ServiceSpec{}, err
  295. }
  296. resources, err := convertResources(service.Deploy.Resources)
  297. if err != nil {
  298. return swarm.ServiceSpec{}, err
  299. }
  300. restartPolicy, err := convertRestartPolicy(
  301. service.Restart, service.Deploy.RestartPolicy)
  302. if err != nil {
  303. return swarm.ServiceSpec{}, err
  304. }
  305. serviceSpec := swarm.ServiceSpec{
  306. Annotations: swarm.Annotations{
  307. Name: name,
  308. Labels: getStackLabels(namespace, service.Deploy.Labels),
  309. },
  310. TaskTemplate: swarm.TaskSpec{
  311. ContainerSpec: swarm.ContainerSpec{
  312. Image: service.Image,
  313. Command: service.Entrypoint,
  314. Args: service.Command,
  315. Hostname: service.Hostname,
  316. Env: convertEnvironment(service.Environment),
  317. Labels: getStackLabels(namespace, service.Labels),
  318. Dir: service.WorkingDir,
  319. User: service.User,
  320. Mounts: mounts,
  321. StopGracePeriod: service.StopGracePeriod,
  322. },
  323. Resources: resources,
  324. RestartPolicy: restartPolicy,
  325. Placement: &swarm.Placement{
  326. Constraints: service.Deploy.Placement.Constraints,
  327. },
  328. },
  329. EndpointSpec: endpoint,
  330. Mode: mode,
  331. Networks: convertNetworks(service.Networks, namespace, service.Name),
  332. UpdateConfig: convertUpdateConfig(service.Deploy.UpdateConfig),
  333. }
  334. return serviceSpec, nil
  335. }
  336. func convertRestartPolicy(restart string, source *composetypes.RestartPolicy) (*swarm.RestartPolicy, error) {
  337. // TODO: log if restart is being ignored
  338. if source == nil {
  339. policy, err := runconfigopts.ParseRestartPolicy(restart)
  340. if err != nil {
  341. return nil, err
  342. }
  343. // TODO: is this an accurate convertion?
  344. switch {
  345. case policy.IsNone(), policy.IsAlways(), policy.IsUnlessStopped():
  346. return nil, nil
  347. case policy.IsOnFailure():
  348. attempts := uint64(policy.MaximumRetryCount)
  349. return &swarm.RestartPolicy{
  350. Condition: swarm.RestartPolicyConditionOnFailure,
  351. MaxAttempts: &attempts,
  352. }, nil
  353. }
  354. }
  355. return &swarm.RestartPolicy{
  356. Condition: swarm.RestartPolicyCondition(source.Condition),
  357. Delay: source.Delay,
  358. MaxAttempts: source.MaxAttempts,
  359. Window: source.Window,
  360. }, nil
  361. }
  362. func convertUpdateConfig(source *composetypes.UpdateConfig) *swarm.UpdateConfig {
  363. if source == nil {
  364. return nil
  365. }
  366. return &swarm.UpdateConfig{
  367. Parallelism: source.Parallelism,
  368. Delay: source.Delay,
  369. FailureAction: source.FailureAction,
  370. Monitor: source.Monitor,
  371. MaxFailureRatio: source.MaxFailureRatio,
  372. }
  373. }
  374. func convertResources(source composetypes.Resources) (*swarm.ResourceRequirements, error) {
  375. resources := &swarm.ResourceRequirements{}
  376. if source.Limits != nil {
  377. cpus, err := opts.ParseCPUs(source.Limits.NanoCPUs)
  378. if err != nil {
  379. return nil, err
  380. }
  381. resources.Limits = &swarm.Resources{
  382. NanoCPUs: cpus,
  383. MemoryBytes: int64(source.Limits.MemoryBytes),
  384. }
  385. }
  386. if source.Reservations != nil {
  387. cpus, err := opts.ParseCPUs(source.Reservations.NanoCPUs)
  388. if err != nil {
  389. return nil, err
  390. }
  391. resources.Reservations = &swarm.Resources{
  392. NanoCPUs: cpus,
  393. MemoryBytes: int64(source.Reservations.MemoryBytes),
  394. }
  395. }
  396. return resources, nil
  397. }
  398. func convertEndpointSpec(source []string) (*swarm.EndpointSpec, error) {
  399. portConfigs := []swarm.PortConfig{}
  400. ports, portBindings, err := nat.ParsePortSpecs(source)
  401. if err != nil {
  402. return nil, err
  403. }
  404. for port := range ports {
  405. portConfigs = append(
  406. portConfigs,
  407. servicecmd.ConvertPortToPortConfig(port, portBindings)...)
  408. }
  409. return &swarm.EndpointSpec{Ports: portConfigs}, nil
  410. }
  411. func convertEnvironment(source map[string]string) []string {
  412. var output []string
  413. for name, value := range source {
  414. output = append(output, fmt.Sprintf("%s=%s", name, value))
  415. }
  416. return output
  417. }
  418. func convertDeployMode(mode string, replicas *uint64) (swarm.ServiceMode, error) {
  419. serviceMode := swarm.ServiceMode{}
  420. switch mode {
  421. case "global":
  422. if replicas != nil {
  423. return serviceMode, fmt.Errorf("replicas can only be used with replicated mode")
  424. }
  425. serviceMode.Global = &swarm.GlobalService{}
  426. case "replicated":
  427. serviceMode.Replicated = &swarm.ReplicatedService{Replicas: replicas}
  428. default:
  429. return serviceMode, fmt.Errorf("Unknown mode: %s", mode)
  430. }
  431. return serviceMode, nil
  432. }