service.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. package controlapi
  2. import (
  3. "errors"
  4. "path/filepath"
  5. "reflect"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/docker/distribution/reference"
  10. "github.com/docker/swarmkit/api"
  11. "github.com/docker/swarmkit/identity"
  12. "github.com/docker/swarmkit/manager/constraint"
  13. "github.com/docker/swarmkit/manager/state/store"
  14. "github.com/docker/swarmkit/protobuf/ptypes"
  15. "github.com/docker/swarmkit/template"
  16. gogotypes "github.com/gogo/protobuf/types"
  17. "golang.org/x/net/context"
  18. "google.golang.org/grpc"
  19. "google.golang.org/grpc/codes"
  20. )
  21. var (
  22. errNetworkUpdateNotSupported = errors.New("changing network in service is not supported")
  23. errRenameNotSupported = errors.New("renaming services is not supported")
  24. errModeChangeNotAllowed = errors.New("service mode change is not allowed")
  25. )
  26. func validateResources(r *api.Resources) error {
  27. if r == nil {
  28. return nil
  29. }
  30. if r.NanoCPUs != 0 && r.NanoCPUs < 1e6 {
  31. return grpc.Errorf(codes.InvalidArgument, "invalid cpu value %g: Must be at least %g", float64(r.NanoCPUs)/1e9, 1e6/1e9)
  32. }
  33. if r.MemoryBytes != 0 && r.MemoryBytes < 4*1024*1024 {
  34. return grpc.Errorf(codes.InvalidArgument, "invalid memory value %d: Must be at least 4MiB", r.MemoryBytes)
  35. }
  36. return nil
  37. }
  38. func validateResourceRequirements(r *api.ResourceRequirements) error {
  39. if r == nil {
  40. return nil
  41. }
  42. if err := validateResources(r.Limits); err != nil {
  43. return err
  44. }
  45. if err := validateResources(r.Reservations); err != nil {
  46. return err
  47. }
  48. return nil
  49. }
  50. func validateRestartPolicy(rp *api.RestartPolicy) error {
  51. if rp == nil {
  52. return nil
  53. }
  54. if rp.Delay != nil {
  55. delay, err := gogotypes.DurationFromProto(rp.Delay)
  56. if err != nil {
  57. return err
  58. }
  59. if delay < 0 {
  60. return grpc.Errorf(codes.InvalidArgument, "TaskSpec: restart-delay cannot be negative")
  61. }
  62. }
  63. if rp.Window != nil {
  64. win, err := gogotypes.DurationFromProto(rp.Window)
  65. if err != nil {
  66. return err
  67. }
  68. if win < 0 {
  69. return grpc.Errorf(codes.InvalidArgument, "TaskSpec: restart-window cannot be negative")
  70. }
  71. }
  72. return nil
  73. }
  74. func validatePlacement(placement *api.Placement) error {
  75. if placement == nil {
  76. return nil
  77. }
  78. _, err := constraint.Parse(placement.Constraints)
  79. return err
  80. }
  81. func validateUpdate(uc *api.UpdateConfig) error {
  82. if uc == nil {
  83. return nil
  84. }
  85. if uc.Delay < 0 {
  86. return grpc.Errorf(codes.InvalidArgument, "TaskSpec: update-delay cannot be negative")
  87. }
  88. if uc.Monitor != nil {
  89. monitor, err := gogotypes.DurationFromProto(uc.Monitor)
  90. if err != nil {
  91. return err
  92. }
  93. if monitor < 0 {
  94. return grpc.Errorf(codes.InvalidArgument, "TaskSpec: update-monitor cannot be negative")
  95. }
  96. }
  97. if uc.MaxFailureRatio < 0 || uc.MaxFailureRatio > 1 {
  98. return grpc.Errorf(codes.InvalidArgument, "TaskSpec: update-maxfailureratio cannot be less than 0 or bigger than 1")
  99. }
  100. return nil
  101. }
  102. func validateContainerSpec(container *api.ContainerSpec) error {
  103. if container == nil {
  104. return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: missing in service spec")
  105. }
  106. if container.Image == "" {
  107. return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: image reference must be provided")
  108. }
  109. if _, err := reference.ParseNormalizedNamed(container.Image); err != nil {
  110. return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: %q is not a valid repository/tag", container.Image)
  111. }
  112. mountMap := make(map[string]bool)
  113. for _, mount := range container.Mounts {
  114. if _, exists := mountMap[mount.Target]; exists {
  115. return grpc.Errorf(codes.InvalidArgument, "ContainerSpec: duplicate mount point: %s", mount.Target)
  116. }
  117. mountMap[mount.Target] = true
  118. }
  119. return nil
  120. }
  121. func validateTaskSpec(taskSpec api.TaskSpec) error {
  122. if err := validateResourceRequirements(taskSpec.Resources); err != nil {
  123. return err
  124. }
  125. if err := validateRestartPolicy(taskSpec.Restart); err != nil {
  126. return err
  127. }
  128. if err := validatePlacement(taskSpec.Placement); err != nil {
  129. return err
  130. }
  131. // Check to see if the Secret Reference portion of the spec is valid
  132. if err := validateSecretRefsSpec(taskSpec); err != nil {
  133. return err
  134. }
  135. if taskSpec.GetRuntime() == nil {
  136. return grpc.Errorf(codes.InvalidArgument, "TaskSpec: missing runtime")
  137. }
  138. _, ok := taskSpec.GetRuntime().(*api.TaskSpec_Container)
  139. if !ok {
  140. return grpc.Errorf(codes.Unimplemented, "RuntimeSpec: unimplemented runtime in service spec")
  141. }
  142. // Building a empty/dummy Task to validate the templating and
  143. // the resulting container spec as well. This is a *best effort*
  144. // validation.
  145. preparedSpec, err := template.ExpandContainerSpec(&api.Task{
  146. Spec: taskSpec,
  147. ServiceID: "serviceid",
  148. Slot: 1,
  149. NodeID: "nodeid",
  150. Networks: []*api.NetworkAttachment{},
  151. Annotations: api.Annotations{
  152. Name: "taskname",
  153. },
  154. ServiceAnnotations: api.Annotations{
  155. Name: "servicename",
  156. },
  157. Endpoint: &api.Endpoint{},
  158. LogDriver: taskSpec.LogDriver,
  159. })
  160. if err != nil {
  161. return grpc.Errorf(codes.InvalidArgument, err.Error())
  162. }
  163. if err := validateContainerSpec(preparedSpec); err != nil {
  164. return err
  165. }
  166. return nil
  167. }
  168. func validateEndpointSpec(epSpec *api.EndpointSpec) error {
  169. // Endpoint spec is optional
  170. if epSpec == nil {
  171. return nil
  172. }
  173. type portSpec struct {
  174. publishedPort uint32
  175. protocol api.PortConfig_Protocol
  176. }
  177. portSet := make(map[portSpec]struct{})
  178. for _, port := range epSpec.Ports {
  179. // Publish mode = "ingress" represents Routing-Mesh and current implementation
  180. // of routing-mesh relies on IPVS based load-balancing with input=published-port.
  181. // But Endpoint-Spec mode of DNSRR relies on multiple A records and cannot be used
  182. // with routing-mesh (PublishMode="ingress") which cannot rely on DNSRR.
  183. // But PublishMode="host" doesn't provide Routing-Mesh and the DNSRR is applicable
  184. // for the backend network and hence we accept that configuration.
  185. if epSpec.Mode == api.ResolutionModeDNSRoundRobin && port.PublishMode == api.PublishModeIngress {
  186. return grpc.Errorf(codes.InvalidArgument, "EndpointSpec: port published with ingress mode can't be used with dnsrr mode")
  187. }
  188. // If published port is not specified, it does not conflict
  189. // with any others.
  190. if port.PublishedPort == 0 {
  191. continue
  192. }
  193. portSpec := portSpec{publishedPort: port.PublishedPort, protocol: port.Protocol}
  194. if _, ok := portSet[portSpec]; ok {
  195. return grpc.Errorf(codes.InvalidArgument, "EndpointSpec: duplicate published ports provided")
  196. }
  197. portSet[portSpec] = struct{}{}
  198. }
  199. return nil
  200. }
  201. // validateSecretRefsSpec finds if the secrets passed in spec are valid and have no
  202. // conflicting targets.
  203. func validateSecretRefsSpec(spec api.TaskSpec) error {
  204. container := spec.GetContainer()
  205. if container == nil {
  206. return nil
  207. }
  208. // Keep a map to track all the targets that will be exposed
  209. // The string returned is only used for logging. It could as well be struct{}{}
  210. existingTargets := make(map[string]string)
  211. for _, secretRef := range container.Secrets {
  212. // SecretID and SecretName are mandatory, we have invalid references without them
  213. if secretRef.SecretID == "" || secretRef.SecretName == "" {
  214. return grpc.Errorf(codes.InvalidArgument, "malformed secret reference")
  215. }
  216. // Every secret reference requires a Target
  217. if secretRef.GetTarget() == nil {
  218. return grpc.Errorf(codes.InvalidArgument, "malformed secret reference, no target provided")
  219. }
  220. // If this is a file target, we will ensure filename uniqueness
  221. if secretRef.GetFile() != nil {
  222. fileName := secretRef.GetFile().Name
  223. // Validate the file name
  224. if fileName == "" || fileName != filepath.Base(filepath.Clean(fileName)) {
  225. return grpc.Errorf(codes.InvalidArgument, "malformed file secret reference, invalid target file name provided")
  226. }
  227. // If this target is already in use, we have conflicting targets
  228. if prevSecretName, ok := existingTargets[fileName]; ok {
  229. return grpc.Errorf(codes.InvalidArgument, "secret references '%s' and '%s' have a conflicting target: '%s'", prevSecretName, secretRef.SecretName, fileName)
  230. }
  231. existingTargets[fileName] = secretRef.SecretName
  232. }
  233. }
  234. return nil
  235. }
  236. func (s *Server) validateNetworks(networks []*api.NetworkAttachmentConfig) error {
  237. for _, na := range networks {
  238. var network *api.Network
  239. s.store.View(func(tx store.ReadTx) {
  240. network = store.GetNetwork(tx, na.Target)
  241. })
  242. if network == nil {
  243. continue
  244. }
  245. if _, ok := network.Spec.Annotations.Labels["com.docker.swarm.internal"]; ok {
  246. return grpc.Errorf(codes.InvalidArgument,
  247. "Service cannot be explicitly attached to %q network which is a swarm internal network",
  248. network.Spec.Annotations.Name)
  249. }
  250. }
  251. return nil
  252. }
  253. func validateMode(s *api.ServiceSpec) error {
  254. m := s.GetMode()
  255. switch m.(type) {
  256. case *api.ServiceSpec_Replicated:
  257. if int64(m.(*api.ServiceSpec_Replicated).Replicated.Replicas) < 0 {
  258. return grpc.Errorf(codes.InvalidArgument, "Number of replicas must be non-negative")
  259. }
  260. case *api.ServiceSpec_Global:
  261. default:
  262. return grpc.Errorf(codes.InvalidArgument, "Unrecognized service mode")
  263. }
  264. return nil
  265. }
  266. func validateServiceSpec(spec *api.ServiceSpec) error {
  267. if spec == nil {
  268. return grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
  269. }
  270. if err := validateAnnotations(spec.Annotations); err != nil {
  271. return err
  272. }
  273. if err := validateTaskSpec(spec.Task); err != nil {
  274. return err
  275. }
  276. if err := validateUpdate(spec.Update); err != nil {
  277. return err
  278. }
  279. if err := validateEndpointSpec(spec.Endpoint); err != nil {
  280. return err
  281. }
  282. if err := validateMode(spec); err != nil {
  283. return err
  284. }
  285. return nil
  286. }
  287. // checkPortConflicts does a best effort to find if the passed in spec has port
  288. // conflicts with existing services.
  289. // `serviceID string` is the service ID of the spec in service update. If
  290. // `serviceID` is not "", then conflicts check will be skipped against this
  291. // service (the service being updated).
  292. func (s *Server) checkPortConflicts(spec *api.ServiceSpec, serviceID string) error {
  293. if spec.Endpoint == nil {
  294. return nil
  295. }
  296. pcToString := func(pc *api.PortConfig) string {
  297. port := strconv.FormatUint(uint64(pc.PublishedPort), 10)
  298. return port + "/" + pc.Protocol.String()
  299. }
  300. reqPorts := make(map[string]bool)
  301. for _, pc := range spec.Endpoint.Ports {
  302. if pc.PublishedPort > 0 {
  303. reqPorts[pcToString(pc)] = true
  304. }
  305. }
  306. if len(reqPorts) == 0 {
  307. return nil
  308. }
  309. var (
  310. services []*api.Service
  311. err error
  312. )
  313. s.store.View(func(tx store.ReadTx) {
  314. services, err = store.FindServices(tx, store.All)
  315. })
  316. if err != nil {
  317. return err
  318. }
  319. for _, service := range services {
  320. // If service ID is the same (and not "") then this is an update
  321. if serviceID != "" && serviceID == service.ID {
  322. continue
  323. }
  324. if service.Spec.Endpoint != nil {
  325. for _, pc := range service.Spec.Endpoint.Ports {
  326. if reqPorts[pcToString(pc)] {
  327. return grpc.Errorf(codes.InvalidArgument, "port '%d' is already in use by service '%s' (%s)", pc.PublishedPort, service.Spec.Annotations.Name, service.ID)
  328. }
  329. }
  330. }
  331. if service.Endpoint != nil {
  332. for _, pc := range service.Endpoint.Ports {
  333. if reqPorts[pcToString(pc)] {
  334. return grpc.Errorf(codes.InvalidArgument, "port '%d' is already in use by service '%s' (%s)", pc.PublishedPort, service.Spec.Annotations.Name, service.ID)
  335. }
  336. }
  337. }
  338. }
  339. return nil
  340. }
  341. // checkSecretExistence finds if the secret exists
  342. func (s *Server) checkSecretExistence(tx store.Tx, spec *api.ServiceSpec) error {
  343. container := spec.Task.GetContainer()
  344. if container == nil {
  345. return nil
  346. }
  347. var failedSecrets []string
  348. for _, secretRef := range container.Secrets {
  349. secret := store.GetSecret(tx, secretRef.SecretID)
  350. // Check to see if the secret exists and secretRef.SecretName matches the actual secretName
  351. if secret == nil || secret.Spec.Annotations.Name != secretRef.SecretName {
  352. failedSecrets = append(failedSecrets, secretRef.SecretName)
  353. }
  354. }
  355. if len(failedSecrets) > 0 {
  356. secretStr := "secrets"
  357. if len(failedSecrets) == 1 {
  358. secretStr = "secret"
  359. }
  360. return grpc.Errorf(codes.InvalidArgument, "%s not found: %v", secretStr, strings.Join(failedSecrets, ", "))
  361. }
  362. return nil
  363. }
  364. // CreateService creates and returns a Service based on the provided ServiceSpec.
  365. // - Returns `InvalidArgument` if the ServiceSpec is malformed.
  366. // - Returns `Unimplemented` if the ServiceSpec references unimplemented features.
  367. // - Returns `AlreadyExists` if the ServiceID conflicts.
  368. // - Returns an error if the creation fails.
  369. func (s *Server) CreateService(ctx context.Context, request *api.CreateServiceRequest) (*api.CreateServiceResponse, error) {
  370. if err := validateServiceSpec(request.Spec); err != nil {
  371. return nil, err
  372. }
  373. if err := s.validateNetworks(request.Spec.Networks); err != nil {
  374. return nil, err
  375. }
  376. if err := s.checkPortConflicts(request.Spec, ""); err != nil {
  377. return nil, err
  378. }
  379. // TODO(aluzzardi): Consider using `Name` as a primary key to handle
  380. // duplicate creations. See #65
  381. service := &api.Service{
  382. ID: identity.NewID(),
  383. Spec: *request.Spec,
  384. }
  385. err := s.store.Update(func(tx store.Tx) error {
  386. // Check to see if all the secrets being added exist as objects
  387. // in our datastore
  388. err := s.checkSecretExistence(tx, request.Spec)
  389. if err != nil {
  390. return err
  391. }
  392. return store.CreateService(tx, service)
  393. })
  394. if err != nil {
  395. return nil, err
  396. }
  397. return &api.CreateServiceResponse{
  398. Service: service,
  399. }, nil
  400. }
  401. // GetService returns a Service given a ServiceID.
  402. // - Returns `InvalidArgument` if ServiceID is not provided.
  403. // - Returns `NotFound` if the Service is not found.
  404. func (s *Server) GetService(ctx context.Context, request *api.GetServiceRequest) (*api.GetServiceResponse, error) {
  405. if request.ServiceID == "" {
  406. return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
  407. }
  408. var service *api.Service
  409. s.store.View(func(tx store.ReadTx) {
  410. service = store.GetService(tx, request.ServiceID)
  411. })
  412. if service == nil {
  413. return nil, grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID)
  414. }
  415. return &api.GetServiceResponse{
  416. Service: service,
  417. }, nil
  418. }
  419. // UpdateService updates a Service referenced by ServiceID with the given ServiceSpec.
  420. // - Returns `NotFound` if the Service is not found.
  421. // - Returns `InvalidArgument` if the ServiceSpec is malformed.
  422. // - Returns `Unimplemented` if the ServiceSpec references unimplemented features.
  423. // - Returns an error if the update fails.
  424. func (s *Server) UpdateService(ctx context.Context, request *api.UpdateServiceRequest) (*api.UpdateServiceResponse, error) {
  425. if request.ServiceID == "" || request.ServiceVersion == nil {
  426. return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
  427. }
  428. if err := validateServiceSpec(request.Spec); err != nil {
  429. return nil, err
  430. }
  431. var service *api.Service
  432. s.store.View(func(tx store.ReadTx) {
  433. service = store.GetService(tx, request.ServiceID)
  434. })
  435. if service == nil {
  436. return nil, grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID)
  437. }
  438. if request.Spec.Endpoint != nil && !reflect.DeepEqual(request.Spec.Endpoint, service.Spec.Endpoint) {
  439. if err := s.checkPortConflicts(request.Spec, request.ServiceID); err != nil {
  440. return nil, err
  441. }
  442. }
  443. err := s.store.Update(func(tx store.Tx) error {
  444. service = store.GetService(tx, request.ServiceID)
  445. if service == nil {
  446. return grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID)
  447. }
  448. // temporary disable network update
  449. requestSpecNetworks := request.Spec.Task.Networks
  450. if len(requestSpecNetworks) == 0 {
  451. requestSpecNetworks = request.Spec.Networks
  452. }
  453. specNetworks := service.Spec.Task.Networks
  454. if len(specNetworks) == 0 {
  455. specNetworks = service.Spec.Networks
  456. }
  457. if !reflect.DeepEqual(requestSpecNetworks, specNetworks) {
  458. return grpc.Errorf(codes.Unimplemented, errNetworkUpdateNotSupported.Error())
  459. }
  460. // Check to see if all the secrets being added exist as objects
  461. // in our datastore
  462. err := s.checkSecretExistence(tx, request.Spec)
  463. if err != nil {
  464. return err
  465. }
  466. // orchestrator is designed to be stateless, so it should not deal
  467. // with service mode change (comparing current config with previous config).
  468. // proper way to change service mode is to delete and re-add.
  469. if reflect.TypeOf(service.Spec.Mode) != reflect.TypeOf(request.Spec.Mode) {
  470. return grpc.Errorf(codes.Unimplemented, errModeChangeNotAllowed.Error())
  471. }
  472. if service.Spec.Annotations.Name != request.Spec.Annotations.Name {
  473. return grpc.Errorf(codes.Unimplemented, errRenameNotSupported.Error())
  474. }
  475. service.Meta.Version = *request.ServiceVersion
  476. if request.Rollback == api.UpdateServiceRequest_PREVIOUS {
  477. if service.PreviousSpec == nil {
  478. return grpc.Errorf(codes.FailedPrecondition, "service %s does not have a previous spec", request.ServiceID)
  479. }
  480. curSpec := service.Spec.Copy()
  481. service.Spec = *service.PreviousSpec.Copy()
  482. service.PreviousSpec = curSpec
  483. service.UpdateStatus = &api.UpdateStatus{
  484. State: api.UpdateStatus_ROLLBACK_STARTED,
  485. Message: "manually requested rollback",
  486. StartedAt: ptypes.MustTimestampProto(time.Now()),
  487. }
  488. } else {
  489. service.PreviousSpec = service.Spec.Copy()
  490. service.Spec = *request.Spec.Copy()
  491. // Reset update status
  492. service.UpdateStatus = nil
  493. }
  494. return store.UpdateService(tx, service)
  495. })
  496. if err != nil {
  497. return nil, err
  498. }
  499. return &api.UpdateServiceResponse{
  500. Service: service,
  501. }, nil
  502. }
  503. // RemoveService removes a Service referenced by ServiceID.
  504. // - Returns `InvalidArgument` if ServiceID is not provided.
  505. // - Returns `NotFound` if the Service is not found.
  506. // - Returns an error if the deletion fails.
  507. func (s *Server) RemoveService(ctx context.Context, request *api.RemoveServiceRequest) (*api.RemoveServiceResponse, error) {
  508. if request.ServiceID == "" {
  509. return nil, grpc.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
  510. }
  511. err := s.store.Update(func(tx store.Tx) error {
  512. return store.DeleteService(tx, request.ServiceID)
  513. })
  514. if err != nil {
  515. if err == store.ErrNotExist {
  516. return nil, grpc.Errorf(codes.NotFound, "service %s not found", request.ServiceID)
  517. }
  518. return nil, err
  519. }
  520. return &api.RemoveServiceResponse{}, nil
  521. }
  522. func filterServices(candidates []*api.Service, filters ...func(*api.Service) bool) []*api.Service {
  523. result := []*api.Service{}
  524. for _, c := range candidates {
  525. match := true
  526. for _, f := range filters {
  527. if !f(c) {
  528. match = false
  529. break
  530. }
  531. }
  532. if match {
  533. result = append(result, c)
  534. }
  535. }
  536. return result
  537. }
  538. // ListServices returns a list of all services.
  539. func (s *Server) ListServices(ctx context.Context, request *api.ListServicesRequest) (*api.ListServicesResponse, error) {
  540. var (
  541. services []*api.Service
  542. err error
  543. )
  544. s.store.View(func(tx store.ReadTx) {
  545. switch {
  546. case request.Filters != nil && len(request.Filters.Names) > 0:
  547. services, err = store.FindServices(tx, buildFilters(store.ByName, request.Filters.Names))
  548. case request.Filters != nil && len(request.Filters.NamePrefixes) > 0:
  549. services, err = store.FindServices(tx, buildFilters(store.ByNamePrefix, request.Filters.NamePrefixes))
  550. case request.Filters != nil && len(request.Filters.IDPrefixes) > 0:
  551. services, err = store.FindServices(tx, buildFilters(store.ByIDPrefix, request.Filters.IDPrefixes))
  552. default:
  553. services, err = store.FindServices(tx, store.All)
  554. }
  555. })
  556. if err != nil {
  557. return nil, err
  558. }
  559. if request.Filters != nil {
  560. services = filterServices(services,
  561. func(e *api.Service) bool {
  562. return filterContains(e.Spec.Annotations.Name, request.Filters.Names)
  563. },
  564. func(e *api.Service) bool {
  565. return filterContainsPrefix(e.Spec.Annotations.Name, request.Filters.NamePrefixes)
  566. },
  567. func(e *api.Service) bool {
  568. return filterContainsPrefix(e.ID, request.Filters.IDPrefixes)
  569. },
  570. func(e *api.Service) bool {
  571. return filterMatchLabels(e.Spec.Annotations.Labels, request.Filters.Labels)
  572. },
  573. )
  574. }
  575. return &api.ListServicesResponse{
  576. Services: services,
  577. }, nil
  578. }