deploy.go 18 KB

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