service.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. package controlapi
  2. import (
  3. "errors"
  4. "reflect"
  5. "strings"
  6. "time"
  7. "github.com/docker/distribution/reference"
  8. "github.com/docker/swarmkit/api"
  9. "github.com/docker/swarmkit/api/defaults"
  10. "github.com/docker/swarmkit/api/naming"
  11. "github.com/docker/swarmkit/identity"
  12. "github.com/docker/swarmkit/manager/allocator"
  13. "github.com/docker/swarmkit/manager/constraint"
  14. "github.com/docker/swarmkit/manager/state/store"
  15. "github.com/docker/swarmkit/protobuf/ptypes"
  16. "github.com/docker/swarmkit/template"
  17. gogotypes "github.com/gogo/protobuf/types"
  18. "golang.org/x/net/context"
  19. "google.golang.org/grpc"
  20. "google.golang.org/grpc/codes"
  21. )
  22. var (
  23. errNetworkUpdateNotSupported = errors.New("networks must be migrated to TaskSpec before being changed")
  24. errRenameNotSupported = errors.New("renaming services is not supported")
  25. errModeChangeNotAllowed = errors.New("service mode change is not allowed")
  26. )
  27. const minimumDuration = 1 * time.Millisecond
  28. func validateResources(r *api.Resources) error {
  29. if r == nil {
  30. return nil
  31. }
  32. if r.NanoCPUs != 0 && r.NanoCPUs < 1e6 {
  33. return grpc.Errorf(codes.InvalidArgument, "invalid cpu value %g: Must be at least %g", float64(r.NanoCPUs)/1e9, 1e6/1e9)
  34. }
  35. if r.MemoryBytes != 0 && r.MemoryBytes < 4*1024*1024 {
  36. return grpc.Errorf(codes.InvalidArgument, "invalid memory value %d: Must be at least 4MiB", r.MemoryBytes)
  37. }
  38. return nil
  39. }
  40. func validateResourceRequirements(r *api.ResourceRequirements) error {
  41. if r == nil {
  42. return nil
  43. }
  44. if err := validateResources(r.Limits); err != nil {
  45. return err
  46. }
  47. if err := validateResources(r.Reservations); err != nil {
  48. return err
  49. }
  50. return nil
  51. }
  52. func validateRestartPolicy(rp *api.RestartPolicy) error {
  53. if rp == nil {
  54. return nil
  55. }
  56. if rp.Delay != nil {
  57. delay, err := gogotypes.DurationFromProto(rp.Delay)
  58. if err != nil {
  59. return err
  60. }
  61. if delay < 0 {
  62. return grpc.Errorf(codes.InvalidArgument, "TaskSpec: restart-delay cannot be negative")
  63. }
  64. }
  65. if rp.Window != nil {
  66. win, err := gogotypes.DurationFromProto(rp.Window)
  67. if err != nil {
  68. return err
  69. }
  70. if win < 0 {
  71. return grpc.Errorf(codes.InvalidArgument, "TaskSpec: restart-window cannot be negative")
  72. }
  73. }
  74. return nil
  75. }
  76. func validatePlacement(placement *api.Placement) error {
  77. if placement == nil {
  78. return nil
  79. }
  80. _, err := constraint.Parse(placement.Constraints)
  81. return err
  82. }
  83. func validateUpdate(uc *api.UpdateConfig) error {
  84. if uc == nil {
  85. return nil
  86. }
  87. if uc.Delay < 0 {
  88. return grpc.Errorf(codes.InvalidArgument, "TaskSpec: update-delay cannot be negative")
  89. }
  90. if uc.Monitor != nil {
  91. monitor, err := gogotypes.DurationFromProto(uc.Monitor)
  92. if err != nil {
  93. return err
  94. }
  95. if monitor < 0 {
  96. return grpc.Errorf(codes.InvalidArgument, "TaskSpec: update-monitor cannot be negative")
  97. }
  98. }
  99. if uc.MaxFailureRatio < 0 || uc.MaxFailureRatio > 1 {
  100. return grpc.Errorf(codes.InvalidArgument, "TaskSpec: update-maxfailureratio cannot be less than 0 or bigger than 1")
  101. }
  102. return nil
  103. }
  104. func validateContainerSpec(taskSpec api.TaskSpec) error {
  105. // Building a empty/dummy Task to validate the templating and
  106. // the resulting container spec as well. This is a *best effort*
  107. // validation.
  108. container, err := template.ExpandContainerSpec(&api.Task{
  109. Spec: taskSpec,
  110. ServiceID: "serviceid",
  111. Slot: 1,
  112. NodeID: "nodeid",
  113. Networks: []*api.NetworkAttachment{},
  114. Annotations: api.Annotations{
  115. Name: "taskname",
  116. },
  117. ServiceAnnotations: api.Annotations{
  118. Name: "servicename",
  119. },
  120. Endpoint: &api.Endpoint{},
  121. LogDriver: taskSpec.LogDriver,
  122. })
  123. if err != nil {
  124. return grpc.Errorf(codes.InvalidArgument, err.Error())
  125. }
  126. if err := validateImage(container.Image); err != nil {
  127. return err
  128. }
  129. if err := validateMounts(container.Mounts); err != nil {
  130. return err
  131. }
  132. if err := validateHealthCheck(container.Healthcheck); err != nil {
  133. return err
  134. }
  135. return nil
  136. }
  137. // validateImage validates image name in containerSpec
  138. func validateImage(image string) error {
  139. if image == "" {
  140. return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: image reference must be provided")
  141. }
  142. if _, err := reference.ParseNormalizedNamed(image); err != nil {
  143. return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: %q is not a valid repository/tag", image)
  144. }
  145. return nil
  146. }
  147. // validateMounts validates if there are duplicate mounts in containerSpec
  148. func validateMounts(mounts []api.Mount) error {
  149. mountMap := make(map[string]bool)
  150. for _, mount := range mounts {
  151. if _, exists := mountMap[mount.Target]; exists {
  152. return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: duplicate mount point: %s", mount.Target)
  153. }
  154. mountMap[mount.Target] = true
  155. }
  156. return nil
  157. }
  158. // validateHealthCheck validates configs about container's health check
  159. func validateHealthCheck(hc *api.HealthConfig) error {
  160. if hc == nil {
  161. return nil
  162. }
  163. if hc.Interval != nil {
  164. interval, err := gogotypes.DurationFromProto(hc.Interval)
  165. if err != nil {
  166. return err
  167. }
  168. if interval != 0 && interval < time.Duration(minimumDuration) {
  169. return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: Interval in HealthConfig cannot be less than %s", minimumDuration)
  170. }
  171. }
  172. if hc.Timeout != nil {
  173. timeout, err := gogotypes.DurationFromProto(hc.Timeout)
  174. if err != nil {
  175. return err
  176. }
  177. if timeout != 0 && timeout < time.Duration(minimumDuration) {
  178. return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: Timeout in HealthConfig cannot be less than %s", minimumDuration)
  179. }
  180. }
  181. if hc.StartPeriod != nil {
  182. sp, err := gogotypes.DurationFromProto(hc.StartPeriod)
  183. if err != nil {
  184. return err
  185. }
  186. if sp != 0 && sp < time.Duration(minimumDuration) {
  187. return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: StartPeriod in HealthConfig cannot be less than %s", minimumDuration)
  188. }
  189. }
  190. if hc.Retries < 0 {
  191. return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: Retries in HealthConfig cannot be negative")
  192. }
  193. return nil
  194. }
  195. func validateGenericRuntimeSpec(taskSpec api.TaskSpec) error {
  196. generic := taskSpec.GetGeneric()
  197. if len(generic.Kind) < 3 {
  198. return grpc.Errorf(codes.InvalidArgument, "Generic runtime: Invalid name %q", generic.Kind)
  199. }
  200. reservedNames := []string{"container", "attachment"}
  201. for _, n := range reservedNames {
  202. if strings.ToLower(generic.Kind) == n {
  203. return grpc.Errorf(codes.InvalidArgument, "Generic runtime: %q is a reserved name", generic.Kind)
  204. }
  205. }
  206. payload := generic.Payload
  207. if payload == nil {
  208. return grpc.Errorf(codes.InvalidArgument, "Generic runtime is missing payload")
  209. }
  210. if payload.TypeUrl == "" {
  211. return grpc.Errorf(codes.InvalidArgument, "Generic runtime is missing payload type")
  212. }
  213. if len(payload.Value) == 0 {
  214. return grpc.Errorf(codes.InvalidArgument, "Generic runtime has an empty payload")
  215. }
  216. return nil
  217. }
  218. func validateTaskSpec(taskSpec api.TaskSpec) error {
  219. if err := validateResourceRequirements(taskSpec.Resources); err != nil {
  220. return err
  221. }
  222. if err := validateRestartPolicy(taskSpec.Restart); err != nil {
  223. return err
  224. }
  225. if err := validatePlacement(taskSpec.Placement); err != nil {
  226. return err
  227. }
  228. // Check to see if the secret reference portion of the spec is valid
  229. if err := validateSecretRefsSpec(taskSpec); err != nil {
  230. return err
  231. }
  232. // Check to see if the config reference portion of the spec is valid
  233. if err := validateConfigRefsSpec(taskSpec); err != nil {
  234. return err
  235. }
  236. if taskSpec.GetRuntime() == nil {
  237. return grpc.Errorf(codes.InvalidArgument, "TaskSpec: missing runtime")
  238. }
  239. switch taskSpec.GetRuntime().(type) {
  240. case *api.TaskSpec_Container:
  241. if err := validateContainerSpec(taskSpec); err != nil {
  242. return err
  243. }
  244. case *api.TaskSpec_Generic:
  245. if err := validateGenericRuntimeSpec(taskSpec); err != nil {
  246. return err
  247. }
  248. default:
  249. return grpc.Errorf(codes.Unimplemented, "RuntimeSpec: unimplemented runtime in service spec")
  250. }
  251. return nil
  252. }
  253. func validateEndpointSpec(epSpec *api.EndpointSpec) error {
  254. // Endpoint spec is optional
  255. if epSpec == nil {
  256. return nil
  257. }
  258. type portSpec struct {
  259. publishedPort uint32
  260. protocol api.PortConfig_Protocol
  261. }
  262. portSet := make(map[portSpec]struct{})
  263. for _, port := range epSpec.Ports {
  264. // Publish mode = "ingress" represents Routing-Mesh and current implementation
  265. // of routing-mesh relies on IPVS based load-balancing with input=published-port.
  266. // But Endpoint-Spec mode of DNSRR relies on multiple A records and cannot be used
  267. // with routing-mesh (PublishMode="ingress") which cannot rely on DNSRR.
  268. // But PublishMode="host" doesn't provide Routing-Mesh and the DNSRR is applicable
  269. // for the backend network and hence we accept that configuration.
  270. if epSpec.Mode == api.ResolutionModeDNSRoundRobin && port.PublishMode == api.PublishModeIngress {
  271. return grpc.Errorf(codes.InvalidArgument, "EndpointSpec: port published with ingress mode can't be used with dnsrr mode")
  272. }
  273. // If published port is not specified, it does not conflict
  274. // with any others.
  275. if port.PublishedPort == 0 {
  276. continue
  277. }
  278. portSpec := portSpec{publishedPort: port.PublishedPort, protocol: port.Protocol}
  279. if _, ok := portSet[portSpec]; ok {
  280. return grpc.Errorf(codes.InvalidArgument, "EndpointSpec: duplicate published ports provided")
  281. }
  282. portSet[portSpec] = struct{}{}
  283. }
  284. return nil
  285. }
  286. // validateSecretRefsSpec finds if the secrets passed in spec are valid and have no
  287. // conflicting targets.
  288. func validateSecretRefsSpec(spec api.TaskSpec) error {
  289. container := spec.GetContainer()
  290. if container == nil {
  291. return nil
  292. }
  293. // Keep a map to track all the targets that will be exposed
  294. // The string returned is only used for logging. It could as well be struct{}{}
  295. existingTargets := make(map[string]string)
  296. for _, secretRef := range container.Secrets {
  297. // SecretID and SecretName are mandatory, we have invalid references without them
  298. if secretRef.SecretID == "" || secretRef.SecretName == "" {
  299. return grpc.Errorf(codes.InvalidArgument, "malformed secret reference")
  300. }
  301. // Every secret reference requires a Target
  302. if secretRef.GetTarget() == nil {
  303. return grpc.Errorf(codes.InvalidArgument, "malformed secret reference, no target provided")
  304. }
  305. // If this is a file target, we will ensure filename uniqueness
  306. if secretRef.GetFile() != nil {
  307. fileName := secretRef.GetFile().Name
  308. if fileName == "" {
  309. return grpc.Errorf(codes.InvalidArgument, "malformed file secret reference, invalid target file name provided")
  310. }
  311. // If this target is already in use, we have conflicting targets
  312. if prevSecretName, ok := existingTargets[fileName]; ok {
  313. return grpc.Errorf(codes.InvalidArgument, "secret references '%s' and '%s' have a conflicting target: '%s'", prevSecretName, secretRef.SecretName, fileName)
  314. }
  315. existingTargets[fileName] = secretRef.SecretName
  316. }
  317. }
  318. return nil
  319. }
  320. // validateConfigRefsSpec finds if the configs passed in spec are valid and have no
  321. // conflicting targets.
  322. func validateConfigRefsSpec(spec api.TaskSpec) error {
  323. container := spec.GetContainer()
  324. if container == nil {
  325. return nil
  326. }
  327. // Keep a map to track all the targets that will be exposed
  328. // The string returned is only used for logging. It could as well be struct{}{}
  329. existingTargets := make(map[string]string)
  330. for _, configRef := range container.Configs {
  331. // ConfigID and ConfigName are mandatory, we have invalid references without them
  332. if configRef.ConfigID == "" || configRef.ConfigName == "" {
  333. return grpc.Errorf(codes.InvalidArgument, "malformed config reference")
  334. }
  335. // Every config reference requires a Target
  336. if configRef.GetTarget() == nil {
  337. return grpc.Errorf(codes.InvalidArgument, "malformed config reference, no target provided")
  338. }
  339. // If this is a file target, we will ensure filename uniqueness
  340. if configRef.GetFile() != nil {
  341. fileName := configRef.GetFile().Name
  342. // Validate the file name
  343. if fileName == "" {
  344. return grpc.Errorf(codes.InvalidArgument, "malformed file config reference, invalid target file name provided")
  345. }
  346. // If this target is already in use, we have conflicting targets
  347. if prevConfigName, ok := existingTargets[fileName]; ok {
  348. return grpc.Errorf(codes.InvalidArgument, "config references '%s' and '%s' have a conflicting target: '%s'", prevConfigName, configRef.ConfigName, fileName)
  349. }
  350. existingTargets[fileName] = configRef.ConfigName
  351. }
  352. }
  353. return nil
  354. }
  355. func (s *Server) validateNetworks(networks []*api.NetworkAttachmentConfig) error {
  356. for _, na := range networks {
  357. var network *api.Network
  358. s.store.View(func(tx store.ReadTx) {
  359. network = store.GetNetwork(tx, na.Target)
  360. })
  361. if network == nil {
  362. continue
  363. }
  364. if allocator.IsIngressNetwork(network) {
  365. return grpc.Errorf(codes.InvalidArgument,
  366. "Service cannot be explicitly attached to the ingress network %q", network.Spec.Annotations.Name)
  367. }
  368. }
  369. return nil
  370. }
  371. func validateMode(s *api.ServiceSpec) error {
  372. m := s.GetMode()
  373. switch m.(type) {
  374. case *api.ServiceSpec_Replicated:
  375. if int64(m.(*api.ServiceSpec_Replicated).Replicated.Replicas) < 0 {
  376. return grpc.Errorf(codes.InvalidArgument, "Number of replicas must be non-negative")
  377. }
  378. case *api.ServiceSpec_Global:
  379. default:
  380. return grpc.Errorf(codes.InvalidArgument, "Unrecognized service mode")
  381. }
  382. return nil
  383. }
  384. func validateServiceSpec(spec *api.ServiceSpec) error {
  385. if spec == nil {
  386. return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
  387. }
  388. if err := validateAnnotations(spec.Annotations); err != nil {
  389. return err
  390. }
  391. if err := validateTaskSpec(spec.Task); err != nil {
  392. return err
  393. }
  394. if err := validateUpdate(spec.Update); err != nil {
  395. return err
  396. }
  397. if err := validateEndpointSpec(spec.Endpoint); err != nil {
  398. return err
  399. }
  400. if err := validateMode(spec); err != nil {
  401. return err
  402. }
  403. return nil
  404. }
  405. // checkPortConflicts does a best effort to find if the passed in spec has port
  406. // conflicts with existing services.
  407. // `serviceID string` is the service ID of the spec in service update. If
  408. // `serviceID` is not "", then conflicts check will be skipped against this
  409. // service (the service being updated).
  410. func (s *Server) checkPortConflicts(spec *api.ServiceSpec, serviceID string) error {
  411. if spec.Endpoint == nil {
  412. return nil
  413. }
  414. type portSpec struct {
  415. protocol api.PortConfig_Protocol
  416. publishedPort uint32
  417. }
  418. pcToStruct := func(pc *api.PortConfig) portSpec {
  419. return portSpec{
  420. protocol: pc.Protocol,
  421. publishedPort: pc.PublishedPort,
  422. }
  423. }
  424. ingressPorts := make(map[portSpec]struct{})
  425. hostModePorts := make(map[portSpec]struct{})
  426. for _, pc := range spec.Endpoint.Ports {
  427. if pc.PublishedPort == 0 {
  428. continue
  429. }
  430. switch pc.PublishMode {
  431. case api.PublishModeIngress:
  432. ingressPorts[pcToStruct(pc)] = struct{}{}
  433. case api.PublishModeHost:
  434. hostModePorts[pcToStruct(pc)] = struct{}{}
  435. }
  436. }
  437. if len(ingressPorts) == 0 && len(hostModePorts) == 0 {
  438. return nil
  439. }
  440. var (
  441. services []*api.Service
  442. err error
  443. )
  444. s.store.View(func(tx store.ReadTx) {
  445. services, err = store.FindServices(tx, store.All)
  446. })
  447. if err != nil {
  448. return err
  449. }
  450. isPortInUse := func(pc *api.PortConfig, service *api.Service) error {
  451. if pc.PublishedPort == 0 {
  452. return nil
  453. }
  454. switch pc.PublishMode {
  455. case api.PublishModeHost:
  456. if _, ok := ingressPorts[pcToStruct(pc)]; ok {
  457. return grpc.Errorf(codes.InvalidArgument, "port '%d' is already in use by service '%s' (%s) as a host-published port", pc.PublishedPort, service.Spec.Annotations.Name, service.ID)
  458. }
  459. // Multiple services with same port in host publish mode can
  460. // coexist - this is handled by the scheduler.
  461. return nil
  462. case api.PublishModeIngress:
  463. _, ingressConflict := ingressPorts[pcToStruct(pc)]
  464. _, hostModeConflict := hostModePorts[pcToStruct(pc)]
  465. if ingressConflict || hostModeConflict {
  466. return grpc.Errorf(codes.InvalidArgument, "port '%d' is already in use by service '%s' (%s) as an ingress port", pc.PublishedPort, service.Spec.Annotations.Name, service.ID)
  467. }
  468. }
  469. return nil
  470. }
  471. for _, service := range services {
  472. // If service ID is the same (and not "") then this is an update
  473. if serviceID != "" && serviceID == service.ID {
  474. continue
  475. }
  476. if service.Spec.Endpoint != nil {
  477. for _, pc := range service.Spec.Endpoint.Ports {
  478. if err := isPortInUse(pc, service); err != nil {
  479. return err
  480. }
  481. }
  482. }
  483. if service.Endpoint != nil {
  484. for _, pc := range service.Endpoint.Ports {
  485. if err := isPortInUse(pc, service); err != nil {
  486. return err
  487. }
  488. }
  489. }
  490. }
  491. return nil
  492. }
  493. // checkSecretExistence finds if the secret exists
  494. func (s *Server) checkSecretExistence(tx store.Tx, spec *api.ServiceSpec) error {
  495. container := spec.Task.GetContainer()
  496. if container == nil {
  497. return nil
  498. }
  499. var failedSecrets []string
  500. for _, secretRef := range container.Secrets {
  501. secret := store.GetSecret(tx, secretRef.SecretID)
  502. // Check to see if the secret exists and secretRef.SecretName matches the actual secretName
  503. if secret == nil || secret.Spec.Annotations.Name != secretRef.SecretName {
  504. failedSecrets = append(failedSecrets, secretRef.SecretName)
  505. }
  506. }
  507. if len(failedSecrets) > 0 {
  508. secretStr := "secrets"
  509. if len(failedSecrets) == 1 {
  510. secretStr = "secret"
  511. }
  512. return grpc.Errorf(codes.InvalidArgument, "%s not found: %v", secretStr, strings.Join(failedSecrets, ", "))
  513. }
  514. return nil
  515. }
  516. // checkConfigExistence finds if the config exists
  517. func (s *Server) checkConfigExistence(tx store.Tx, spec *api.ServiceSpec) error {
  518. container := spec.Task.GetContainer()
  519. if container == nil {
  520. return nil
  521. }
  522. var failedConfigs []string
  523. for _, configRef := range container.Configs {
  524. config := store.GetConfig(tx, configRef.ConfigID)
  525. // Check to see if the config exists and configRef.ConfigName matches the actual configName
  526. if config == nil || config.Spec.Annotations.Name != configRef.ConfigName {
  527. failedConfigs = append(failedConfigs, configRef.ConfigName)
  528. }
  529. }
  530. if len(failedConfigs) > 0 {
  531. configStr := "configs"
  532. if len(failedConfigs) == 1 {
  533. configStr = "config"
  534. }
  535. return grpc.Errorf(codes.InvalidArgument, "%s not found: %v", configStr, strings.Join(failedConfigs, ", "))
  536. }
  537. return nil
  538. }
  539. // CreateService creates and returns a Service based on the provided ServiceSpec.
  540. // - Returns `InvalidArgument` if the ServiceSpec is malformed.
  541. // - Returns `Unimplemented` if the ServiceSpec references unimplemented features.
  542. // - Returns `AlreadyExists` if the ServiceID conflicts.
  543. // - Returns an error if the creation fails.
  544. func (s *Server) CreateService(ctx context.Context, request *api.CreateServiceRequest) (*api.CreateServiceResponse, error) {
  545. if err := validateServiceSpec(request.Spec); err != nil {
  546. return nil, err
  547. }
  548. if err := s.validateNetworks(request.Spec.Networks); err != nil {
  549. return nil, err
  550. }
  551. if err := s.checkPortConflicts(request.Spec, ""); err != nil {
  552. return nil, err
  553. }
  554. // TODO(aluzzardi): Consider using `Name` as a primary key to handle
  555. // duplicate creations. See #65
  556. service := &api.Service{
  557. ID: identity.NewID(),
  558. Spec: *request.Spec,
  559. SpecVersion: &api.Version{},
  560. }
  561. if allocator.IsIngressNetworkNeeded(service) {
  562. if _, err := allocator.GetIngressNetwork(s.store); err == allocator.ErrNoIngress {
  563. return nil, grpc.Errorf(codes.FailedPrecondition, "service needs ingress network, but no ingress network is present")
  564. }
  565. }
  566. err := s.store.Update(func(tx store.Tx) error {
  567. // Check to see if all the secrets being added exist as objects
  568. // in our datastore
  569. err := s.checkSecretExistence(tx, request.Spec)
  570. if err != nil {
  571. return err
  572. }
  573. err = s.checkConfigExistence(tx, request.Spec)
  574. if err != nil {
  575. return err
  576. }
  577. return store.CreateService(tx, service)
  578. })
  579. if err != nil {
  580. return nil, err
  581. }
  582. return &api.CreateServiceResponse{
  583. Service: service,
  584. }, nil
  585. }
  586. // GetService returns a Service given a ServiceID.
  587. // - Returns `InvalidArgument` if ServiceID is not provided.
  588. // - Returns `NotFound` if the Service is not found.
  589. func (s *Server) GetService(ctx context.Context, request *api.GetServiceRequest) (*api.GetServiceResponse, error) {
  590. if request.ServiceID == "" {
  591. return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
  592. }
  593. var service *api.Service
  594. s.store.View(func(tx store.ReadTx) {
  595. service = store.GetService(tx, request.ServiceID)
  596. })
  597. if service == nil {
  598. return nil, grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID)
  599. }
  600. if request.InsertDefaults {
  601. service.Spec = *defaults.InterpolateService(&service.Spec)
  602. }
  603. return &api.GetServiceResponse{
  604. Service: service,
  605. }, nil
  606. }
  607. // UpdateService updates a Service referenced by ServiceID with the given ServiceSpec.
  608. // - Returns `NotFound` if the Service is not found.
  609. // - Returns `InvalidArgument` if the ServiceSpec is malformed.
  610. // - Returns `Unimplemented` if the ServiceSpec references unimplemented features.
  611. // - Returns an error if the update fails.
  612. func (s *Server) UpdateService(ctx context.Context, request *api.UpdateServiceRequest) (*api.UpdateServiceResponse, error) {
  613. if request.ServiceID == "" || request.ServiceVersion == nil {
  614. return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
  615. }
  616. if err := validateServiceSpec(request.Spec); err != nil {
  617. return nil, err
  618. }
  619. var service *api.Service
  620. s.store.View(func(tx store.ReadTx) {
  621. service = store.GetService(tx, request.ServiceID)
  622. })
  623. if service == nil {
  624. return nil, grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID)
  625. }
  626. if request.Spec.Endpoint != nil && !reflect.DeepEqual(request.Spec.Endpoint, service.Spec.Endpoint) {
  627. if err := s.checkPortConflicts(request.Spec, request.ServiceID); err != nil {
  628. return nil, err
  629. }
  630. }
  631. err := s.store.Update(func(tx store.Tx) error {
  632. service = store.GetService(tx, request.ServiceID)
  633. if service == nil {
  634. return grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID)
  635. }
  636. // It's not okay to update Service.Spec.Networks on its own.
  637. // However, if Service.Spec.Task.Networks is also being
  638. // updated, that's okay (for example when migrating from the
  639. // deprecated Spec.Networks field to Spec.Task.Networks).
  640. if (len(request.Spec.Networks) != 0 || len(service.Spec.Networks) != 0) &&
  641. !reflect.DeepEqual(request.Spec.Networks, service.Spec.Networks) &&
  642. reflect.DeepEqual(request.Spec.Task.Networks, service.Spec.Task.Networks) {
  643. return grpc.Errorf(codes.Unimplemented, errNetworkUpdateNotSupported.Error())
  644. }
  645. // Check to see if all the secrets being added exist as objects
  646. // in our datastore
  647. err := s.checkSecretExistence(tx, request.Spec)
  648. if err != nil {
  649. return err
  650. }
  651. err = s.checkConfigExistence(tx, request.Spec)
  652. if err != nil {
  653. return err
  654. }
  655. // orchestrator is designed to be stateless, so it should not deal
  656. // with service mode change (comparing current config with previous config).
  657. // proper way to change service mode is to delete and re-add.
  658. if reflect.TypeOf(service.Spec.Mode) != reflect.TypeOf(request.Spec.Mode) {
  659. return grpc.Errorf(codes.Unimplemented, errModeChangeNotAllowed.Error())
  660. }
  661. if service.Spec.Annotations.Name != request.Spec.Annotations.Name {
  662. return grpc.Errorf(codes.Unimplemented, errRenameNotSupported.Error())
  663. }
  664. service.Meta.Version = *request.ServiceVersion
  665. if request.Rollback == api.UpdateServiceRequest_PREVIOUS {
  666. if service.PreviousSpec == nil {
  667. return grpc.Errorf(codes.FailedPrecondition, "service %s does not have a previous spec", request.ServiceID)
  668. }
  669. curSpec := service.Spec.Copy()
  670. curSpecVersion := service.SpecVersion
  671. service.Spec = *service.PreviousSpec.Copy()
  672. service.SpecVersion = service.PreviousSpecVersion.Copy()
  673. service.PreviousSpec = curSpec
  674. service.PreviousSpecVersion = curSpecVersion
  675. service.UpdateStatus = &api.UpdateStatus{
  676. State: api.UpdateStatus_ROLLBACK_STARTED,
  677. Message: "manually requested rollback",
  678. StartedAt: ptypes.MustTimestampProto(time.Now()),
  679. }
  680. } else {
  681. service.PreviousSpec = service.Spec.Copy()
  682. service.PreviousSpecVersion = service.SpecVersion
  683. service.Spec = *request.Spec.Copy()
  684. // Set spec version. Note that this will not match the
  685. // service's Meta.Version after the store update. The
  686. // versions for the spec and the service itself are not
  687. // meant to be directly comparable.
  688. service.SpecVersion = service.Meta.Version.Copy()
  689. // Reset update status
  690. service.UpdateStatus = nil
  691. }
  692. if allocator.IsIngressNetworkNeeded(service) {
  693. if _, err := allocator.GetIngressNetwork(s.store); err == allocator.ErrNoIngress {
  694. return grpc.Errorf(codes.FailedPrecondition, "service needs ingress network, but no ingress network is present")
  695. }
  696. }
  697. return store.UpdateService(tx, service)
  698. })
  699. if err != nil {
  700. return nil, err
  701. }
  702. return &api.UpdateServiceResponse{
  703. Service: service,
  704. }, nil
  705. }
  706. // RemoveService removes a Service referenced by ServiceID.
  707. // - Returns `InvalidArgument` if ServiceID is not provided.
  708. // - Returns `NotFound` if the Service is not found.
  709. // - Returns an error if the deletion fails.
  710. func (s *Server) RemoveService(ctx context.Context, request *api.RemoveServiceRequest) (*api.RemoveServiceResponse, error) {
  711. if request.ServiceID == "" {
  712. return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
  713. }
  714. err := s.store.Update(func(tx store.Tx) error {
  715. return store.DeleteService(tx, request.ServiceID)
  716. })
  717. if err != nil {
  718. if err == store.ErrNotExist {
  719. return nil, grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID)
  720. }
  721. return nil, err
  722. }
  723. return &api.RemoveServiceResponse{}, nil
  724. }
  725. func filterServices(candidates []*api.Service, filters ...func(*api.Service) bool) []*api.Service {
  726. result := []*api.Service{}
  727. for _, c := range candidates {
  728. match := true
  729. for _, f := range filters {
  730. if !f(c) {
  731. match = false
  732. break
  733. }
  734. }
  735. if match {
  736. result = append(result, c)
  737. }
  738. }
  739. return result
  740. }
  741. // ListServices returns a list of all services.
  742. func (s *Server) ListServices(ctx context.Context, request *api.ListServicesRequest) (*api.ListServicesResponse, error) {
  743. var (
  744. services []*api.Service
  745. err error
  746. )
  747. s.store.View(func(tx store.ReadTx) {
  748. switch {
  749. case request.Filters != nil && len(request.Filters.Names) > 0:
  750. services, err = store.FindServices(tx, buildFilters(store.ByName, request.Filters.Names))
  751. case request.Filters != nil && len(request.Filters.NamePrefixes) > 0:
  752. services, err = store.FindServices(tx, buildFilters(store.ByNamePrefix, request.Filters.NamePrefixes))
  753. case request.Filters != nil && len(request.Filters.IDPrefixes) > 0:
  754. services, err = store.FindServices(tx, buildFilters(store.ByIDPrefix, request.Filters.IDPrefixes))
  755. case request.Filters != nil && len(request.Filters.Runtimes) > 0:
  756. services, err = store.FindServices(tx, buildFilters(store.ByRuntime, request.Filters.Runtimes))
  757. default:
  758. services, err = store.FindServices(tx, store.All)
  759. }
  760. })
  761. if err != nil {
  762. return nil, err
  763. }
  764. if request.Filters != nil {
  765. services = filterServices(services,
  766. func(e *api.Service) bool {
  767. return filterContains(e.Spec.Annotations.Name, request.Filters.Names)
  768. },
  769. func(e *api.Service) bool {
  770. return filterContainsPrefix(e.Spec.Annotations.Name, request.Filters.NamePrefixes)
  771. },
  772. func(e *api.Service) bool {
  773. return filterContainsPrefix(e.ID, request.Filters.IDPrefixes)
  774. },
  775. func(e *api.Service) bool {
  776. return filterMatchLabels(e.Spec.Annotations.Labels, request.Filters.Labels)
  777. },
  778. func(e *api.Service) bool {
  779. if len(request.Filters.Runtimes) == 0 {
  780. return true
  781. }
  782. r, err := naming.Runtime(e.Spec.Task)
  783. if err != nil {
  784. return false
  785. }
  786. return filterContains(r, request.Filters.Runtimes)
  787. },
  788. )
  789. }
  790. return &api.ListServicesResponse{
  791. Services: services,
  792. }, nil
  793. }