deploy.go 17 KB

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