deploy.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. package stack
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "sort"
  7. "strings"
  8. "github.com/spf13/cobra"
  9. "golang.org/x/net/context"
  10. "github.com/aanand/compose-file/loader"
  11. composetypes "github.com/aanand/compose-file/types"
  12. "github.com/docker/docker/api/types"
  13. "github.com/docker/docker/api/types/mount"
  14. networktypes "github.com/docker/docker/api/types/network"
  15. "github.com/docker/docker/api/types/swarm"
  16. "github.com/docker/docker/cli"
  17. "github.com/docker/docker/cli/command"
  18. servicecmd "github.com/docker/docker/cli/command/service"
  19. "github.com/docker/docker/opts"
  20. runconfigopts "github.com/docker/docker/runconfig/opts"
  21. "github.com/docker/go-connections/nat"
  22. )
  23. const (
  24. defaultNetworkDriver = "overlay"
  25. )
  26. type deployOptions struct {
  27. bundlefile string
  28. composefile string
  29. namespace string
  30. sendRegistryAuth bool
  31. }
  32. func newDeployCommand(dockerCli *command.DockerCli) *cobra.Command {
  33. var opts deployOptions
  34. cmd := &cobra.Command{
  35. Use: "deploy [OPTIONS] STACK",
  36. Aliases: []string{"up"},
  37. Short: "Deploy a new stack or update an existing stack",
  38. Args: cli.ExactArgs(1),
  39. RunE: func(cmd *cobra.Command, args []string) error {
  40. opts.namespace = args[0]
  41. return runDeploy(dockerCli, opts)
  42. },
  43. Tags: map[string]string{"experimental": "", "version": "1.25"},
  44. }
  45. flags := cmd.Flags()
  46. addBundlefileFlag(&opts.bundlefile, flags)
  47. addComposefileFlag(&opts.composefile, flags)
  48. addRegistryAuthFlag(&opts.sendRegistryAuth, flags)
  49. return cmd
  50. }
  51. func runDeploy(dockerCli *command.DockerCli, opts deployOptions) error {
  52. switch {
  53. case opts.bundlefile == "" && opts.composefile == "":
  54. return fmt.Errorf("Please specify either a bundle file (with --bundle-file) or a Compose file (with --compose-file).")
  55. case opts.bundlefile != "" && opts.composefile != "":
  56. return fmt.Errorf("You cannot specify both a bundle file and a Compose file.")
  57. case opts.bundlefile != "":
  58. return deployBundle(dockerCli, opts)
  59. default:
  60. return deployCompose(dockerCli, opts)
  61. }
  62. }
  63. func deployCompose(dockerCli *command.DockerCli, opts deployOptions) error {
  64. configDetails, err := getConfigDetails(opts)
  65. if err != nil {
  66. return err
  67. }
  68. config, err := loader.Load(configDetails)
  69. if err != nil {
  70. if fpe, ok := err.(*loader.ForbiddenPropertiesError); ok {
  71. return fmt.Errorf("Compose file contains unsupported options:\n\n%s\n",
  72. propertyWarnings(fpe.Properties))
  73. }
  74. return err
  75. }
  76. unsupportedProperties := loader.GetUnsupportedProperties(configDetails)
  77. if len(unsupportedProperties) > 0 {
  78. fmt.Fprintf(dockerCli.Err(), "Ignoring unsupported options: %s\n\n",
  79. strings.Join(unsupportedProperties, ", "))
  80. }
  81. deprecatedProperties := loader.GetDeprecatedProperties(configDetails)
  82. if len(deprecatedProperties) > 0 {
  83. fmt.Fprintf(dockerCli.Err(), "Ignoring deprecated options:\n\n%s\n\n",
  84. propertyWarnings(deprecatedProperties))
  85. }
  86. ctx := context.Background()
  87. namespace := namespace{name: opts.namespace}
  88. networks := convertNetworks(namespace, config.Networks)
  89. if err := createNetworks(ctx, dockerCli, namespace, networks); err != nil {
  90. return err
  91. }
  92. services, err := convertServices(namespace, config)
  93. if err != nil {
  94. return err
  95. }
  96. return deployServices(ctx, dockerCli, services, namespace, opts.sendRegistryAuth)
  97. }
  98. func propertyWarnings(properties map[string]string) string {
  99. var msgs []string
  100. for name, description := range properties {
  101. msgs = append(msgs, fmt.Sprintf("%s: %s", name, description))
  102. }
  103. sort.Strings(msgs)
  104. return strings.Join(msgs, "\n\n")
  105. }
  106. func getConfigDetails(opts deployOptions) (composetypes.ConfigDetails, error) {
  107. var details composetypes.ConfigDetails
  108. var err error
  109. details.WorkingDir, err = os.Getwd()
  110. if err != nil {
  111. return details, err
  112. }
  113. configFile, err := getConfigFile(opts.composefile)
  114. if err != nil {
  115. return details, err
  116. }
  117. // TODO: support multiple files
  118. details.ConfigFiles = []composetypes.ConfigFile{*configFile}
  119. return details, nil
  120. }
  121. func getConfigFile(filename string) (*composetypes.ConfigFile, error) {
  122. bytes, err := ioutil.ReadFile(filename)
  123. if err != nil {
  124. return nil, err
  125. }
  126. config, err := loader.ParseYAML(bytes)
  127. if err != nil {
  128. return nil, err
  129. }
  130. return &composetypes.ConfigFile{
  131. Filename: filename,
  132. Config: config,
  133. }, nil
  134. }
  135. func convertNetworks(
  136. namespace namespace,
  137. networks map[string]composetypes.NetworkConfig,
  138. ) map[string]types.NetworkCreate {
  139. if networks == nil {
  140. networks = make(map[string]composetypes.NetworkConfig)
  141. }
  142. // TODO: only add default network if it's used
  143. networks["default"] = composetypes.NetworkConfig{}
  144. result := make(map[string]types.NetworkCreate)
  145. for internalName, network := range networks {
  146. if network.External.Name != "" {
  147. continue
  148. }
  149. createOpts := types.NetworkCreate{
  150. Labels: getStackLabels(namespace.name, network.Labels),
  151. Driver: network.Driver,
  152. Options: network.DriverOpts,
  153. }
  154. if network.Ipam.Driver != "" || len(network.Ipam.Config) > 0 {
  155. createOpts.IPAM = &networktypes.IPAM{}
  156. }
  157. if network.Ipam.Driver != "" {
  158. createOpts.IPAM.Driver = network.Ipam.Driver
  159. }
  160. for _, ipamConfig := range network.Ipam.Config {
  161. config := networktypes.IPAMConfig{
  162. Subnet: ipamConfig.Subnet,
  163. }
  164. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  165. }
  166. result[internalName] = createOpts
  167. }
  168. return result
  169. }
  170. func createNetworks(
  171. ctx context.Context,
  172. dockerCli *command.DockerCli,
  173. namespace namespace,
  174. networks map[string]types.NetworkCreate,
  175. ) error {
  176. client := dockerCli.Client()
  177. existingNetworks, err := getNetworks(ctx, client, namespace.name)
  178. if err != nil {
  179. return err
  180. }
  181. existingNetworkMap := make(map[string]types.NetworkResource)
  182. for _, network := range existingNetworks {
  183. existingNetworkMap[network.Name] = network
  184. }
  185. for internalName, createOpts := range networks {
  186. name := namespace.scope(internalName)
  187. if _, exists := existingNetworkMap[name]; exists {
  188. continue
  189. }
  190. if createOpts.Driver == "" {
  191. createOpts.Driver = defaultNetworkDriver
  192. }
  193. fmt.Fprintf(dockerCli.Out(), "Creating network %s\n", name)
  194. if _, err := client.NetworkCreate(ctx, name, createOpts); err != nil {
  195. return err
  196. }
  197. }
  198. return nil
  199. }
  200. func convertServiceNetworks(
  201. networks map[string]*composetypes.ServiceNetworkConfig,
  202. namespace namespace,
  203. name string,
  204. ) []swarm.NetworkAttachmentConfig {
  205. if len(networks) == 0 {
  206. return []swarm.NetworkAttachmentConfig{
  207. {
  208. Target: namespace.scope("default"),
  209. Aliases: []string{name},
  210. },
  211. }
  212. }
  213. nets := []swarm.NetworkAttachmentConfig{}
  214. for networkName, network := range networks {
  215. nets = append(nets, swarm.NetworkAttachmentConfig{
  216. Target: namespace.scope(networkName),
  217. Aliases: append(network.Aliases, name),
  218. })
  219. }
  220. return nets
  221. }
  222. func convertVolumes(
  223. serviceVolumes []string,
  224. stackVolumes map[string]composetypes.VolumeConfig,
  225. namespace namespace,
  226. ) ([]mount.Mount, error) {
  227. var mounts []mount.Mount
  228. for _, volumeSpec := range serviceVolumes {
  229. mount, err := convertVolumeToMount(volumeSpec, stackVolumes, namespace)
  230. if err != nil {
  231. return nil, err
  232. }
  233. mounts = append(mounts, mount)
  234. }
  235. return mounts, nil
  236. }
  237. func convertVolumeToMount(
  238. volumeSpec string,
  239. stackVolumes map[string]composetypes.VolumeConfig,
  240. namespace namespace,
  241. ) (mount.Mount, error) {
  242. var source, target string
  243. var mode []string
  244. // TODO: split Windows path mappings properly
  245. parts := strings.SplitN(volumeSpec, ":", 3)
  246. switch len(parts) {
  247. case 3:
  248. source = parts[0]
  249. target = parts[1]
  250. mode = strings.Split(parts[2], ",")
  251. case 2:
  252. source = parts[0]
  253. target = parts[1]
  254. case 1:
  255. target = parts[0]
  256. default:
  257. return mount.Mount{}, fmt.Errorf("invald volume: %s", volumeSpec)
  258. }
  259. // TODO: catch Windows paths here
  260. if strings.HasPrefix(source, "/") {
  261. return mount.Mount{
  262. Type: mount.TypeBind,
  263. Source: source,
  264. Target: target,
  265. ReadOnly: isReadOnly(mode),
  266. BindOptions: getBindOptions(mode),
  267. }, nil
  268. }
  269. stackVolume, exists := stackVolumes[source]
  270. if !exists {
  271. return mount.Mount{}, fmt.Errorf("undefined volume: %s", source)
  272. }
  273. var volumeOptions *mount.VolumeOptions
  274. if stackVolume.External.Name != "" {
  275. source = stackVolume.External.Name
  276. } else {
  277. volumeOptions = &mount.VolumeOptions{
  278. Labels: stackVolume.Labels,
  279. NoCopy: isNoCopy(mode),
  280. }
  281. if stackVolume.Driver != "" {
  282. volumeOptions.DriverConfig = &mount.Driver{
  283. Name: stackVolume.Driver,
  284. Options: stackVolume.DriverOpts,
  285. }
  286. }
  287. source = namespace.scope(source)
  288. }
  289. return mount.Mount{
  290. Type: mount.TypeVolume,
  291. Source: source,
  292. Target: target,
  293. ReadOnly: isReadOnly(mode),
  294. VolumeOptions: volumeOptions,
  295. }, nil
  296. }
  297. func modeHas(mode []string, field string) bool {
  298. for _, item := range mode {
  299. if item == field {
  300. return true
  301. }
  302. }
  303. return false
  304. }
  305. func isReadOnly(mode []string) bool {
  306. return modeHas(mode, "ro")
  307. }
  308. func isNoCopy(mode []string) bool {
  309. return modeHas(mode, "nocopy")
  310. }
  311. func getBindOptions(mode []string) *mount.BindOptions {
  312. for _, item := range mode {
  313. if strings.Contains(item, "private") || strings.Contains(item, "shared") || strings.Contains(item, "slave") {
  314. return &mount.BindOptions{Propagation: mount.Propagation(item)}
  315. }
  316. }
  317. return nil
  318. }
  319. func deployServices(
  320. ctx context.Context,
  321. dockerCli *command.DockerCli,
  322. services map[string]swarm.ServiceSpec,
  323. namespace namespace,
  324. sendAuth bool,
  325. ) error {
  326. apiClient := dockerCli.Client()
  327. out := dockerCli.Out()
  328. existingServices, err := getServices(ctx, apiClient, namespace.name)
  329. if err != nil {
  330. return err
  331. }
  332. existingServiceMap := make(map[string]swarm.Service)
  333. for _, service := range existingServices {
  334. existingServiceMap[service.Spec.Name] = service
  335. }
  336. for internalName, serviceSpec := range services {
  337. name := namespace.scope(internalName)
  338. encodedAuth := ""
  339. if sendAuth {
  340. // Retrieve encoded auth token from the image reference
  341. image := serviceSpec.TaskTemplate.ContainerSpec.Image
  342. encodedAuth, err = command.RetrieveAuthTokenFromImage(ctx, dockerCli, image)
  343. if err != nil {
  344. return err
  345. }
  346. }
  347. if service, exists := existingServiceMap[name]; exists {
  348. fmt.Fprintf(out, "Updating service %s (id: %s)\n", name, service.ID)
  349. updateOpts := types.ServiceUpdateOptions{}
  350. if sendAuth {
  351. updateOpts.EncodedRegistryAuth = encodedAuth
  352. }
  353. response, err := apiClient.ServiceUpdate(
  354. ctx,
  355. service.ID,
  356. service.Version,
  357. serviceSpec,
  358. updateOpts,
  359. )
  360. if err != nil {
  361. return err
  362. }
  363. for _, warning := range response.Warnings {
  364. fmt.Fprintln(dockerCli.Err(), warning)
  365. }
  366. } else {
  367. fmt.Fprintf(out, "Creating service %s\n", name)
  368. createOpts := types.ServiceCreateOptions{}
  369. if sendAuth {
  370. createOpts.EncodedRegistryAuth = encodedAuth
  371. }
  372. if _, err := apiClient.ServiceCreate(ctx, serviceSpec, createOpts); err != nil {
  373. return err
  374. }
  375. }
  376. }
  377. return nil
  378. }
  379. func convertServices(
  380. namespace namespace,
  381. config *composetypes.Config,
  382. ) (map[string]swarm.ServiceSpec, error) {
  383. result := make(map[string]swarm.ServiceSpec)
  384. services := config.Services
  385. volumes := config.Volumes
  386. for _, service := range services {
  387. serviceSpec, err := convertService(namespace, service, volumes)
  388. if err != nil {
  389. return nil, err
  390. }
  391. result[service.Name] = serviceSpec
  392. }
  393. return result, nil
  394. }
  395. func convertService(
  396. namespace namespace,
  397. service composetypes.ServiceConfig,
  398. volumes map[string]composetypes.VolumeConfig,
  399. ) (swarm.ServiceSpec, error) {
  400. name := namespace.scope(service.Name)
  401. endpoint, err := convertEndpointSpec(service.Ports)
  402. if err != nil {
  403. return swarm.ServiceSpec{}, err
  404. }
  405. mode, err := convertDeployMode(service.Deploy.Mode, service.Deploy.Replicas)
  406. if err != nil {
  407. return swarm.ServiceSpec{}, err
  408. }
  409. mounts, err := convertVolumes(service.Volumes, volumes, namespace)
  410. if err != nil {
  411. // TODO: better error message (include service name)
  412. return swarm.ServiceSpec{}, err
  413. }
  414. resources, err := convertResources(service.Deploy.Resources)
  415. if err != nil {
  416. return swarm.ServiceSpec{}, err
  417. }
  418. restartPolicy, err := convertRestartPolicy(
  419. service.Restart, service.Deploy.RestartPolicy)
  420. if err != nil {
  421. return swarm.ServiceSpec{}, err
  422. }
  423. serviceSpec := swarm.ServiceSpec{
  424. Annotations: swarm.Annotations{
  425. Name: name,
  426. Labels: getStackLabels(namespace.name, service.Deploy.Labels),
  427. },
  428. TaskTemplate: swarm.TaskSpec{
  429. ContainerSpec: swarm.ContainerSpec{
  430. Image: service.Image,
  431. Command: service.Entrypoint,
  432. Args: service.Command,
  433. Hostname: service.Hostname,
  434. Hosts: convertExtraHosts(service.ExtraHosts),
  435. Env: convertEnvironment(service.Environment),
  436. Labels: getStackLabels(namespace.name, service.Labels),
  437. Dir: service.WorkingDir,
  438. User: service.User,
  439. Mounts: mounts,
  440. StopGracePeriod: service.StopGracePeriod,
  441. TTY: service.Tty,
  442. OpenStdin: service.StdinOpen,
  443. },
  444. Resources: resources,
  445. RestartPolicy: restartPolicy,
  446. Placement: &swarm.Placement{
  447. Constraints: service.Deploy.Placement.Constraints,
  448. },
  449. },
  450. EndpointSpec: endpoint,
  451. Mode: mode,
  452. Networks: convertServiceNetworks(service.Networks, namespace, service.Name),
  453. UpdateConfig: convertUpdateConfig(service.Deploy.UpdateConfig),
  454. }
  455. return serviceSpec, nil
  456. }
  457. func convertExtraHosts(extraHosts map[string]string) []string {
  458. hosts := []string{}
  459. for host, ip := range extraHosts {
  460. hosts = append(hosts, fmt.Sprintf("%s %s", host, ip))
  461. }
  462. return hosts
  463. }
  464. func convertRestartPolicy(restart string, source *composetypes.RestartPolicy) (*swarm.RestartPolicy, error) {
  465. // TODO: log if restart is being ignored
  466. if source == nil {
  467. policy, err := runconfigopts.ParseRestartPolicy(restart)
  468. if err != nil {
  469. return nil, err
  470. }
  471. // TODO: is this an accurate convertion?
  472. switch {
  473. case policy.IsNone():
  474. return nil, nil
  475. case policy.IsAlways(), policy.IsUnlessStopped():
  476. return &swarm.RestartPolicy{
  477. Condition: swarm.RestartPolicyConditionAny,
  478. }, nil
  479. case policy.IsOnFailure():
  480. attempts := uint64(policy.MaximumRetryCount)
  481. return &swarm.RestartPolicy{
  482. Condition: swarm.RestartPolicyConditionOnFailure,
  483. MaxAttempts: &attempts,
  484. }, nil
  485. }
  486. }
  487. return &swarm.RestartPolicy{
  488. Condition: swarm.RestartPolicyCondition(source.Condition),
  489. Delay: source.Delay,
  490. MaxAttempts: source.MaxAttempts,
  491. Window: source.Window,
  492. }, nil
  493. }
  494. func convertUpdateConfig(source *composetypes.UpdateConfig) *swarm.UpdateConfig {
  495. if source == nil {
  496. return nil
  497. }
  498. return &swarm.UpdateConfig{
  499. Parallelism: source.Parallelism,
  500. Delay: source.Delay,
  501. FailureAction: source.FailureAction,
  502. Monitor: source.Monitor,
  503. MaxFailureRatio: source.MaxFailureRatio,
  504. }
  505. }
  506. func convertResources(source composetypes.Resources) (*swarm.ResourceRequirements, error) {
  507. resources := &swarm.ResourceRequirements{}
  508. if source.Limits != nil {
  509. cpus, err := opts.ParseCPUs(source.Limits.NanoCPUs)
  510. if err != nil {
  511. return nil, err
  512. }
  513. resources.Limits = &swarm.Resources{
  514. NanoCPUs: cpus,
  515. MemoryBytes: int64(source.Limits.MemoryBytes),
  516. }
  517. }
  518. if source.Reservations != nil {
  519. cpus, err := opts.ParseCPUs(source.Reservations.NanoCPUs)
  520. if err != nil {
  521. return nil, err
  522. }
  523. resources.Reservations = &swarm.Resources{
  524. NanoCPUs: cpus,
  525. MemoryBytes: int64(source.Reservations.MemoryBytes),
  526. }
  527. }
  528. return resources, nil
  529. }
  530. func convertEndpointSpec(source []string) (*swarm.EndpointSpec, error) {
  531. portConfigs := []swarm.PortConfig{}
  532. ports, portBindings, err := nat.ParsePortSpecs(source)
  533. if err != nil {
  534. return nil, err
  535. }
  536. for port := range ports {
  537. portConfigs = append(
  538. portConfigs,
  539. servicecmd.ConvertPortToPortConfig(port, portBindings)...)
  540. }
  541. return &swarm.EndpointSpec{Ports: portConfigs}, nil
  542. }
  543. func convertEnvironment(source map[string]string) []string {
  544. var output []string
  545. for name, value := range source {
  546. output = append(output, fmt.Sprintf("%s=%s", name, value))
  547. }
  548. return output
  549. }
  550. func convertDeployMode(mode string, replicas *uint64) (swarm.ServiceMode, error) {
  551. serviceMode := swarm.ServiceMode{}
  552. switch mode {
  553. case "global":
  554. if replicas != nil {
  555. return serviceMode, fmt.Errorf("replicas can only be used with replicated mode")
  556. }
  557. serviceMode.Global = &swarm.GlobalService{}
  558. case "replicated", "":
  559. serviceMode.Replicated = &swarm.ReplicatedService{Replicas: replicas}
  560. default:
  561. return serviceMode, fmt.Errorf("Unknown mode: %s", mode)
  562. }
  563. return serviceMode, nil
  564. }