gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/grpc/internal/admin/admin.go (about)

     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  
    19  // Package admin contains internal implementation for admin service.
    20  package admin
    21  
    22  import "gitee.com/ks-custle/core-gm/grpc"
    23  
    24  // services is a map from name to service register functions.
    25  var services []func(grpc.ServiceRegistrar) (func(), error)
    26  
    27  // AddService adds a service to the list of admin services.
    28  //
    29  // NOTE: this function must only be called during initialization time (i.e. in
    30  // an init() function), and is not thread-safe.
    31  //
    32  // If multiple services with the same service name are added (e.g. two services
    33  // for `grpc.channelz.v1.Channelz`), the server will panic on `Register()`.
    34  func AddService(f func(grpc.ServiceRegistrar) (func(), error)) {
    35  	services = append(services, f)
    36  }
    37  
    38  // Register registers the set of admin services to the given server.
    39  func Register(s grpc.ServiceRegistrar) (cleanup func(), _ error) {
    40  	var cleanups []func()
    41  	for _, f := range services {
    42  		cleanup, err := f(s)
    43  		if err != nil {
    44  			callFuncs(cleanups)
    45  			return nil, err
    46  		}
    47  		if cleanup != nil {
    48  			cleanups = append(cleanups, cleanup)
    49  		}
    50  	}
    51  	return func() {
    52  		callFuncs(cleanups)
    53  	}, nil
    54  }
    55  
    56  func callFuncs(fs []func()) {
    57  	for _, f := range fs {
    58  		f()
    59  	}
    60  }