deploy.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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. for _, part := range parts {
  303. if strings.TrimSpace(part) == "" {
  304. return mount.Mount{}, fmt.Errorf("invalid volume: %s", volumeSpec)
  305. }
  306. }
  307. switch len(parts) {
  308. case 3:
  309. source = parts[0]
  310. target = parts[1]
  311. mode = strings.Split(parts[2], ",")
  312. case 2:
  313. source = parts[0]
  314. target = parts[1]
  315. case 1:
  316. target = parts[0]
  317. }
  318. if source == "" {
  319. // Anonymous volume
  320. return mount.Mount{
  321. Type: mount.TypeVolume,
  322. Target: target,
  323. }, nil
  324. }
  325. // TODO: catch Windows paths here
  326. if strings.HasPrefix(source, "/") {
  327. return mount.Mount{
  328. Type: mount.TypeBind,
  329. Source: source,
  330. Target: target,
  331. ReadOnly: isReadOnly(mode),
  332. BindOptions: getBindOptions(mode),
  333. }, nil
  334. }
  335. stackVolume, exists := stackVolumes[source]
  336. if !exists {
  337. return mount.Mount{}, fmt.Errorf("undefined volume: %s", source)
  338. }
  339. var volumeOptions *mount.VolumeOptions
  340. if stackVolume.External.Name != "" {
  341. source = stackVolume.External.Name
  342. } else {
  343. volumeOptions = &mount.VolumeOptions{
  344. Labels: getStackLabels(namespace.name, stackVolume.Labels),
  345. NoCopy: isNoCopy(mode),
  346. }
  347. if stackVolume.Driver != "" {
  348. volumeOptions.DriverConfig = &mount.Driver{
  349. Name: stackVolume.Driver,
  350. Options: stackVolume.DriverOpts,
  351. }
  352. }
  353. source = namespace.scope(source)
  354. }
  355. return mount.Mount{
  356. Type: mount.TypeVolume,
  357. Source: source,
  358. Target: target,
  359. ReadOnly: isReadOnly(mode),
  360. VolumeOptions: volumeOptions,
  361. }, nil
  362. }
  363. func modeHas(mode []string, field string) bool {
  364. for _, item := range mode {
  365. if item == field {
  366. return true
  367. }
  368. }
  369. return false
  370. }
  371. func isReadOnly(mode []string) bool {
  372. return modeHas(mode, "ro")
  373. }
  374. func isNoCopy(mode []string) bool {
  375. return modeHas(mode, "nocopy")
  376. }
  377. func getBindOptions(mode []string) *mount.BindOptions {
  378. for _, item := range mode {
  379. if strings.Contains(item, "private") || strings.Contains(item, "shared") || strings.Contains(item, "slave") {
  380. return &mount.BindOptions{Propagation: mount.Propagation(item)}
  381. }
  382. }
  383. return nil
  384. }
  385. func deployServices(
  386. ctx context.Context,
  387. dockerCli *command.DockerCli,
  388. services map[string]swarm.ServiceSpec,
  389. namespace namespace,
  390. sendAuth bool,
  391. ) error {
  392. apiClient := dockerCli.Client()
  393. out := dockerCli.Out()
  394. existingServices, err := getServices(ctx, apiClient, namespace.name)
  395. if err != nil {
  396. return err
  397. }
  398. existingServiceMap := make(map[string]swarm.Service)
  399. for _, service := range existingServices {
  400. existingServiceMap[service.Spec.Name] = service
  401. }
  402. for internalName, serviceSpec := range services {
  403. name := namespace.scope(internalName)
  404. encodedAuth := ""
  405. if sendAuth {
  406. // Retrieve encoded auth token from the image reference
  407. image := serviceSpec.TaskTemplate.ContainerSpec.Image
  408. encodedAuth, err = command.RetrieveAuthTokenFromImage(ctx, dockerCli, image)
  409. if err != nil {
  410. return err
  411. }
  412. }
  413. if service, exists := existingServiceMap[name]; exists {
  414. fmt.Fprintf(out, "Updating service %s (id: %s)\n", name, service.ID)
  415. updateOpts := types.ServiceUpdateOptions{}
  416. if sendAuth {
  417. updateOpts.EncodedRegistryAuth = encodedAuth
  418. }
  419. response, err := apiClient.ServiceUpdate(
  420. ctx,
  421. service.ID,
  422. service.Version,
  423. serviceSpec,
  424. updateOpts,
  425. )
  426. if err != nil {
  427. return err
  428. }
  429. for _, warning := range response.Warnings {
  430. fmt.Fprintln(dockerCli.Err(), warning)
  431. }
  432. } else {
  433. fmt.Fprintf(out, "Creating service %s\n", name)
  434. createOpts := types.ServiceCreateOptions{}
  435. if sendAuth {
  436. createOpts.EncodedRegistryAuth = encodedAuth
  437. }
  438. if _, err := apiClient.ServiceCreate(ctx, serviceSpec, createOpts); err != nil {
  439. return err
  440. }
  441. }
  442. }
  443. return nil
  444. }
  445. func convertServices(
  446. namespace namespace,
  447. config *composetypes.Config,
  448. ) (map[string]swarm.ServiceSpec, error) {
  449. result := make(map[string]swarm.ServiceSpec)
  450. services := config.Services
  451. volumes := config.Volumes
  452. networks := config.Networks
  453. for _, service := range services {
  454. serviceSpec, err := convertService(namespace, service, networks, volumes)
  455. if err != nil {
  456. return nil, err
  457. }
  458. result[service.Name] = serviceSpec
  459. }
  460. return result, nil
  461. }
  462. func convertService(
  463. namespace namespace,
  464. service composetypes.ServiceConfig,
  465. networkConfigs map[string]composetypes.NetworkConfig,
  466. volumes map[string]composetypes.VolumeConfig,
  467. ) (swarm.ServiceSpec, error) {
  468. name := namespace.scope(service.Name)
  469. endpoint, err := convertEndpointSpec(service.Ports)
  470. if err != nil {
  471. return swarm.ServiceSpec{}, err
  472. }
  473. mode, err := convertDeployMode(service.Deploy.Mode, service.Deploy.Replicas)
  474. if err != nil {
  475. return swarm.ServiceSpec{}, err
  476. }
  477. mounts, err := convertVolumes(service.Volumes, volumes, namespace)
  478. if err != nil {
  479. // TODO: better error message (include service name)
  480. return swarm.ServiceSpec{}, err
  481. }
  482. resources, err := convertResources(service.Deploy.Resources)
  483. if err != nil {
  484. return swarm.ServiceSpec{}, err
  485. }
  486. restartPolicy, err := convertRestartPolicy(
  487. service.Restart, service.Deploy.RestartPolicy)
  488. if err != nil {
  489. return swarm.ServiceSpec{}, err
  490. }
  491. healthcheck, err := convertHealthcheck(service.HealthCheck)
  492. if err != nil {
  493. return swarm.ServiceSpec{}, err
  494. }
  495. networks, err := convertServiceNetworks(service.Networks, networkConfigs, namespace, service.Name)
  496. if err != nil {
  497. return swarm.ServiceSpec{}, err
  498. }
  499. var logDriver *swarm.Driver
  500. if service.Logging != nil {
  501. logDriver = &swarm.Driver{
  502. Name: service.Logging.Driver,
  503. Options: service.Logging.Options,
  504. }
  505. }
  506. serviceSpec := swarm.ServiceSpec{
  507. Annotations: swarm.Annotations{
  508. Name: name,
  509. Labels: getStackLabels(namespace.name, service.Deploy.Labels),
  510. },
  511. TaskTemplate: swarm.TaskSpec{
  512. ContainerSpec: swarm.ContainerSpec{
  513. Image: service.Image,
  514. Command: service.Entrypoint,
  515. Args: service.Command,
  516. Hostname: service.Hostname,
  517. Hosts: convertExtraHosts(service.ExtraHosts),
  518. Healthcheck: healthcheck,
  519. Env: convertEnvironment(service.Environment),
  520. Labels: getStackLabels(namespace.name, service.Labels),
  521. Dir: service.WorkingDir,
  522. User: service.User,
  523. Mounts: mounts,
  524. StopGracePeriod: service.StopGracePeriod,
  525. TTY: service.Tty,
  526. OpenStdin: service.StdinOpen,
  527. },
  528. LogDriver: logDriver,
  529. Resources: resources,
  530. RestartPolicy: restartPolicy,
  531. Placement: &swarm.Placement{
  532. Constraints: service.Deploy.Placement.Constraints,
  533. },
  534. },
  535. EndpointSpec: endpoint,
  536. Mode: mode,
  537. Networks: networks,
  538. UpdateConfig: convertUpdateConfig(service.Deploy.UpdateConfig),
  539. }
  540. return serviceSpec, nil
  541. }
  542. func convertExtraHosts(extraHosts map[string]string) []string {
  543. hosts := []string{}
  544. for host, ip := range extraHosts {
  545. hosts = append(hosts, fmt.Sprintf("%s %s", ip, host))
  546. }
  547. return hosts
  548. }
  549. func convertHealthcheck(healthcheck *composetypes.HealthCheckConfig) (*container.HealthConfig, error) {
  550. if healthcheck == nil {
  551. return nil, nil
  552. }
  553. var (
  554. err error
  555. timeout, interval time.Duration
  556. retries int
  557. )
  558. if healthcheck.Disable {
  559. if len(healthcheck.Test) != 0 {
  560. return nil, fmt.Errorf("command and disable key can't be set at the same time")
  561. }
  562. return &container.HealthConfig{
  563. Test: []string{"NONE"},
  564. }, nil
  565. }
  566. if healthcheck.Timeout != "" {
  567. timeout, err = time.ParseDuration(healthcheck.Timeout)
  568. if err != nil {
  569. return nil, err
  570. }
  571. }
  572. if healthcheck.Interval != "" {
  573. interval, err = time.ParseDuration(healthcheck.Interval)
  574. if err != nil {
  575. return nil, err
  576. }
  577. }
  578. if healthcheck.Retries != nil {
  579. retries = int(*healthcheck.Retries)
  580. }
  581. return &container.HealthConfig{
  582. Test: healthcheck.Test,
  583. Timeout: timeout,
  584. Interval: interval,
  585. Retries: retries,
  586. }, nil
  587. }
  588. func convertRestartPolicy(restart string, source *composetypes.RestartPolicy) (*swarm.RestartPolicy, error) {
  589. // TODO: log if restart is being ignored
  590. if source == nil {
  591. policy, err := runconfigopts.ParseRestartPolicy(restart)
  592. if err != nil {
  593. return nil, err
  594. }
  595. // TODO: is this an accurate convertion?
  596. switch {
  597. case policy.IsNone():
  598. return nil, nil
  599. case policy.IsAlways(), policy.IsUnlessStopped():
  600. return &swarm.RestartPolicy{
  601. Condition: swarm.RestartPolicyConditionAny,
  602. }, nil
  603. case policy.IsOnFailure():
  604. attempts := uint64(policy.MaximumRetryCount)
  605. return &swarm.RestartPolicy{
  606. Condition: swarm.RestartPolicyConditionOnFailure,
  607. MaxAttempts: &attempts,
  608. }, nil
  609. }
  610. }
  611. return &swarm.RestartPolicy{
  612. Condition: swarm.RestartPolicyCondition(source.Condition),
  613. Delay: source.Delay,
  614. MaxAttempts: source.MaxAttempts,
  615. Window: source.Window,
  616. }, nil
  617. }
  618. func convertUpdateConfig(source *composetypes.UpdateConfig) *swarm.UpdateConfig {
  619. if source == nil {
  620. return nil
  621. }
  622. parallel := uint64(1)
  623. if source.Parallelism != nil {
  624. parallel = *source.Parallelism
  625. }
  626. return &swarm.UpdateConfig{
  627. Parallelism: parallel,
  628. Delay: source.Delay,
  629. FailureAction: source.FailureAction,
  630. Monitor: source.Monitor,
  631. MaxFailureRatio: source.MaxFailureRatio,
  632. }
  633. }
  634. func convertResources(source composetypes.Resources) (*swarm.ResourceRequirements, error) {
  635. resources := &swarm.ResourceRequirements{}
  636. if source.Limits != nil {
  637. cpus, err := opts.ParseCPUs(source.Limits.NanoCPUs)
  638. if err != nil {
  639. return nil, err
  640. }
  641. resources.Limits = &swarm.Resources{
  642. NanoCPUs: cpus,
  643. MemoryBytes: int64(source.Limits.MemoryBytes),
  644. }
  645. }
  646. if source.Reservations != nil {
  647. cpus, err := opts.ParseCPUs(source.Reservations.NanoCPUs)
  648. if err != nil {
  649. return nil, err
  650. }
  651. resources.Reservations = &swarm.Resources{
  652. NanoCPUs: cpus,
  653. MemoryBytes: int64(source.Reservations.MemoryBytes),
  654. }
  655. }
  656. return resources, nil
  657. }
  658. func convertEndpointSpec(source []string) (*swarm.EndpointSpec, error) {
  659. portConfigs := []swarm.PortConfig{}
  660. ports, portBindings, err := nat.ParsePortSpecs(source)
  661. if err != nil {
  662. return nil, err
  663. }
  664. for port := range ports {
  665. portConfigs = append(
  666. portConfigs,
  667. opts.ConvertPortToPortConfig(port, portBindings)...)
  668. }
  669. return &swarm.EndpointSpec{Ports: portConfigs}, nil
  670. }
  671. func convertEnvironment(source map[string]string) []string {
  672. var output []string
  673. for name, value := range source {
  674. output = append(output, fmt.Sprintf("%s=%s", name, value))
  675. }
  676. return output
  677. }
  678. func convertDeployMode(mode string, replicas *uint64) (swarm.ServiceMode, error) {
  679. serviceMode := swarm.ServiceMode{}
  680. switch mode {
  681. case "global":
  682. if replicas != nil {
  683. return serviceMode, fmt.Errorf("replicas can only be used with replicated mode")
  684. }
  685. serviceMode.Global = &swarm.GlobalService{}
  686. case "replicated", "":
  687. serviceMode.Replicated = &swarm.ReplicatedService{Replicas: replicas}
  688. default:
  689. return serviceMode, fmt.Errorf("Unknown mode: %s", mode)
  690. }
  691. return serviceMode, nil
  692. }