|
| 1 | +package usecase |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/md5" |
| 5 | + "encoding/hex" |
| 6 | + "fmt" |
| 7 | + |
| 8 | + "github.com/forest33/warthog/business/entity" |
| 9 | +) |
| 10 | + |
| 11 | +func (uc *GrpcUseCase) getPortForwardErrorHandler(srv entity.WorkspaceItemServer, serverID int64) func(error) { |
| 12 | + return func(err error) { |
| 13 | + uc.deletePortForward(srv) |
| 14 | + if uc.curConnectedServerID == serverID { |
| 15 | + uc.curConnectedServerID = 0 |
| 16 | + uc.errorCh <- &entity.Error{ |
| 17 | + Message: err.Error(), |
| 18 | + } |
| 19 | + } |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +func (uc *GrpcUseCase) getPortForward(srv *entity.WorkspaceItemServer) *forwardPort { |
| 24 | + uc.muForwardPorts.RLock() |
| 25 | + defer uc.muForwardPorts.RUnlock() |
| 26 | + |
| 27 | + if uc.forwardPorts == nil { |
| 28 | + return nil |
| 29 | + } |
| 30 | + |
| 31 | + if fp, ok := uc.forwardPorts[srv.K8SPortForward.LocalPort]; ok { |
| 32 | + return fp |
| 33 | + } |
| 34 | + |
| 35 | + return nil |
| 36 | +} |
| 37 | + |
| 38 | +func (uc *GrpcUseCase) addPortForward(srv *entity.WorkspaceItemServer, control entity.PortForwardControl) { |
| 39 | + uc.muForwardPorts.Lock() |
| 40 | + defer uc.muForwardPorts.Unlock() |
| 41 | + |
| 42 | + if uc.forwardPorts == nil { |
| 43 | + uc.forwardPorts = make(map[int16]*forwardPort, 10) |
| 44 | + } |
| 45 | + |
| 46 | + uc.forwardPorts[srv.K8SPortForward.LocalPort] = &forwardPort{ |
| 47 | + control: control, |
| 48 | + hash: getPortForwardHash(srv), |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +func (uc *GrpcUseCase) deletePortForward(srv entity.WorkspaceItemServer) { |
| 53 | + uc.muForwardPorts.Lock() |
| 54 | + defer uc.muForwardPorts.Unlock() |
| 55 | + |
| 56 | + if uc.forwardPorts == nil { |
| 57 | + return |
| 58 | + } |
| 59 | + |
| 60 | + delete(uc.forwardPorts, srv.K8SPortForward.LocalPort) |
| 61 | +} |
| 62 | + |
| 63 | +func getPortForwardHash(srv *entity.WorkspaceItemServer) string { |
| 64 | + data := fmt.Sprintf("%d|%s|%s|%s", |
| 65 | + srv.K8SPortForward.PodPort, |
| 66 | + srv.K8SPortForward.Namespace, |
| 67 | + srv.K8SPortForward.PodName, |
| 68 | + srv.K8SPortForward.PodNameSelector, |
| 69 | + ) |
| 70 | + |
| 71 | + if srv.K8SPortForward.ClientConfig.GCSAuth != nil && srv.K8SPortForward.ClientConfig.GCSAuth.Enabled { |
| 72 | + data = fmt.Sprintf("|%s|%s|%s|%s", |
| 73 | + data, |
| 74 | + srv.K8SPortForward.ClientConfig.GCSAuth.Project, |
| 75 | + srv.K8SPortForward.ClientConfig.GCSAuth.Location, |
| 76 | + srv.K8SPortForward.ClientConfig.GCSAuth.Cluster, |
| 77 | + ) |
| 78 | + } |
| 79 | + |
| 80 | + hash := md5.Sum([]byte(data)) |
| 81 | + return hex.EncodeToString(hash[:]) |
| 82 | +} |
0 commit comments