google.golang.org/grpc@v1.72.2/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 ) 38 39 // Dial dials the handshake service in the hypervisor. If a connection has 40 // already been established, this function returns it. Otherwise, a new 41 // connection is created. 42 func Dial(hsAddress string) (*grpc.ClientConn, error) { 43 mu.Lock() 44 defer mu.Unlock() 45 46 hsConn, ok := hsConnMap[hsAddress] 47 if !ok { 48 // Create a new connection to the handshaker service. Note that 49 // this connection stays open until the application is closed. 50 // Disable the service config to avoid unnecessary TXT record lookups that 51 // cause timeouts with some versions of systemd-resolved. 52 var err error 53 hsConn, err = grpc.NewClient(hsAddress, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithDisableServiceConfig()) 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 }