google.golang.org/grpc@v1.62.1/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 "google.golang.org/grpc"
    27  	"google.golang.org/grpc/credentials/insecure"
    28  )
    29  
    30  var (
    31  	// mu guards hsConnMap and hsDialer.
    32  	mu sync.Mutex
    33  	// hsConn represents a mapping from a hypervisor handshaker service address
    34  	// to a corresponding connection to a hypervisor handshaker service
    35  	// instance.
    36  	hsConnMap = make(map[string]*grpc.ClientConn)
    37  	// hsDialer will be reassigned in tests.
    38  	hsDialer = grpc.Dial
    39  )
    40  
    41  // Dial dials the handshake service in the hypervisor. If a connection has
    42  // already been established, this function returns it. Otherwise, a new
    43  // connection is created.
    44  func Dial(hsAddress string) (*grpc.ClientConn, error) {
    45  	mu.Lock()
    46  	defer mu.Unlock()
    47  
    48  	hsConn, ok := hsConnMap[hsAddress]
    49  	if !ok {
    50  		// Create a new connection to the handshaker service. Note that
    51  		// this connection stays open until the application is closed.
    52  		var err error
    53  		hsConn, err = hsDialer(hsAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))
    54  		if err != nil {
    55  			return nil, err
    56  		}
    57  		hsConnMap[hsAddress] = hsConn
    58  	}
    59  	return hsConn, nil
    60  }
    61  
    62  // CloseForTesting closes all open connections to the handshaker service.
    63  //
    64  // For testing purposes only.
    65  func CloseForTesting() error {
    66  	for _, hsConn := range hsConnMap {
    67  		if hsConn == nil {
    68  			continue
    69  		}
    70  		if err := hsConn.Close(); err != nil {
    71  			return err
    72  		}
    73  	}
    74  
    75  	// Reset the connection map.
    76  	hsConnMap = make(map[string]*grpc.ClientConn)
    77  	return nil
    78  }