admin.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. *
  3. * Copyright 2021 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Package admin contains internal implementation for admin service.
  19. package admin
  20. import "google.golang.org/grpc"
  21. // services is a map from name to service register functions.
  22. var services []func(grpc.ServiceRegistrar) (func(), error)
  23. // AddService adds a service to the list of admin services.
  24. //
  25. // NOTE: this function must only be called during initialization time (i.e. in
  26. // an init() function), and is not thread-safe.
  27. //
  28. // If multiple services with the same service name are added (e.g. two services
  29. // for `grpc.channelz.v1.Channelz`), the server will panic on `Register()`.
  30. func AddService(f func(grpc.ServiceRegistrar) (func(), error)) {
  31. services = append(services, f)
  32. }
  33. // Register registers the set of admin services to the given server.
  34. func Register(s grpc.ServiceRegistrar) (cleanup func(), _ error) {
  35. var cleanups []func()
  36. for _, f := range services {
  37. cleanup, err := f(s)
  38. if err != nil {
  39. callFuncs(cleanups)
  40. return nil, err
  41. }
  42. if cleanup != nil {
  43. cleanups = append(cleanups, cleanup)
  44. }
  45. }
  46. return func() {
  47. callFuncs(cleanups)
  48. }, nil
  49. }
  50. func callFuncs(fs []func()) {
  51. for _, f := range fs {
  52. f()
  53. }
  54. }