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

     1  /*
     2   *
     3   * Copyright 2018 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 service manages connections between the VM application and the ALTS
    20  // handshaker service.
    21  package service
    22  
    23  import (
    24  	"sync"
    25  
    26  	grpc "gitee.com/ks-custle/core-gm/grpc"
    27  )
    28  
    29  var (
    30  	// mu guards hsConnMap and hsDialer.
    31  	mu sync.Mutex
    32  	// hsConn represents a mapping from a hypervisor handshaker service address
    33  	// to a corresponding connection to a hypervisor handshaker service
    34  	// instance.
    35  	hsConnMap = make(map[string]*grpc.ClientConn)
    36  	// hsDialer will be reassigned in tests.
    37  	hsDialer = grpc.Dial
    38  )
    39  
    40  // Dial dials the handshake service in the hypervisor. If a connection has
    41  // already been established, this function returns it. Otherwise, a new
    42  // connection is created.
    43  func Dial(hsAddress string) (*grpc.ClientConn, error) {
    44  	mu.Lock()
    45  	defer mu.Unlock()
    46  
    47  	hsConn, ok := hsConnMap[hsAddress]
    48  	if !ok {
    49  		// Create a new connection to the handshaker service. Note that
    50  		// this connection stays open until the application is closed.
    51  		var err error
    52  		hsConn, err = hsDialer(hsAddress, grpc.WithInsecure())
    53  		if err != nil {
    54  			return nil, err
    55  		}
    56  		hsConnMap[hsAddress] = hsConn
    57  	}
    58  	return hsConn, nil
    59  }