deploy.go 20 KB

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