-
Notifications
You must be signed in to change notification settings - Fork 50
/
registry_grpc_client.go
194 lines (167 loc) · 5.12 KB
/
registry_grpc_client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package catalogsource
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/url"
"os"
"time"
"github.com/operator-framework/api/pkg/operators/v1alpha1"
"github.com/operator-framework/deppy/pkg/deppy/input"
catalogsourceapi "github.com/operator-framework/operator-registry/pkg/api"
"golang.org/x/net/http/httpproxy"
"golang.org/x/net/proxy"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials/insecure"
)
type RegistryClient interface {
ListEntities(ctx context.Context, catsrc *v1alpha1.CatalogSource) ([]*input.Entity, error)
}
type registryGRPCClient struct {
timeout time.Duration
}
func NewRegistryGRPCClient(grpcTimeout time.Duration) RegistryClient {
if grpcTimeout == 0 {
grpcTimeout = DefaultGRPCTimeout
}
return ®istryGRPCClient{timeout: grpcTimeout}
}
func (r *registryGRPCClient) ListEntities(ctx context.Context, catalogSource *v1alpha1.CatalogSource) ([]*input.Entity, error) {
// TODO: create GRPC connections separately
conn, err := ConnectGRPCWithTimeout(ctx, catalogSource.Address(), r.timeout)
if conn != nil {
// ConnectGRPCWithTimeout may fail to establish a READY connection
// close any opened connection regardless of its state.
defer conn.Close()
}
if err != nil {
return nil, err
}
catsrcClient := catalogsourceapi.NewRegistryClient(conn)
stream, err := catsrcClient.ListBundles(ctx, &catalogsourceapi.ListBundlesRequest{})
if err != nil {
return nil, fmt.Errorf("ListBundles failed: %v", err)
}
var entities []*input.Entity
catalogPackages := map[string]*catalogsourceapi.Package{}
catalogSourceID := fmt.Sprintf("%s/%s", catalogSource.Namespace, catalogSource.Name)
for {
bundle, err := stream.Recv()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return nil, fmt.Errorf("failed to read bundle stream: %v", err)
}
packageKey := fmt.Sprintf("%s/%s", catalogSourceID, bundle.PackageName)
pkg, ok := catalogPackages[packageKey]
if !ok {
pkg, err = catsrcClient.GetPackage(ctx, &catalogsourceapi.GetPackageRequest{Name: bundle.PackageName})
if err != nil {
return nil, fmt.Errorf("failed to get package %s: %v", bundle.PackageName, err)
}
catalogPackages[packageKey] = pkg
}
entity, err := EntityFromBundle(catalogSourceID, pkg, bundle)
if err != nil {
return nil, fmt.Errorf("failed to parse entity %s: %v", entity.Identifier(), err)
}
entities = append(entities, entity)
}
return entities, nil
}
const DefaultGRPCTimeout = 2 * time.Minute
func ConnectGRPCWithTimeout(ctx context.Context, address string, timeout time.Duration) (conn *grpc.ClientConn, err error) {
// based on https://github.com/operator-framework/operator-lifecycle-manager/blob/afc0848d102ecdc01a0b0f3b55d389bb66acf168/pkg/controller/registry/grpc/source.go#L149
conn, err = grpcConnection(address)
if err != nil {
return nil, fmt.Errorf("GRPC connection failed: %v", err)
}
if timeout == 0 {
timeout = DefaultGRPCTimeout
}
if err := waitForGRPCWithTimeout(ctx, conn, timeout, address); err != nil {
return conn, fmt.Errorf("GRPC timeout: %v", err)
}
return conn, nil
}
func waitForGRPCWithTimeout(ctx context.Context, conn *grpc.ClientConn, timeout time.Duration, address string) error {
if conn == nil {
return fmt.Errorf("nil connection")
}
state := conn.GetState()
if state == connectivity.Ready {
return nil
}
oldState := state
ctx2, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
for {
select {
case <-ctx2.Done():
return fmt.Errorf("%v %s timed out waiting for ready state, %v", time.Now(), address, timeout)
default:
state := conn.GetState()
if state != oldState {
oldState = state
}
if state == connectivity.Ready {
return nil
}
}
}
}
func grpcConnection(address string) (*grpc.ClientConn, error) {
dialOptions := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
proxyURL, err := grpcProxyURL(address)
if err != nil {
return nil, err
}
if proxyURL != nil {
dialOptions = append(dialOptions, grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
dialer, err := proxy.FromURL(proxyURL, &net.Dialer{})
if err != nil {
return nil, err
}
return dialer.Dial("tcp", addr)
}))
}
return grpc.Dial(address, dialOptions...)
}
func grpcProxyURL(addr string) (*url.URL, error) {
// Handle ip addresses
host, _, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
url, err := url.Parse(host)
if err != nil {
return nil, err
}
// Hardcode fields required for proxy resolution
url.Host = addr
url.Scheme = "http"
// Override HTTPS_PROXY and HTTP_PROXY with GRPC_PROXY
proxyConfig := &httpproxy.Config{
HTTPProxy: getGRPCProxyEnv(),
HTTPSProxy: getGRPCProxyEnv(),
NoProxy: getEnvAny("NO_PROXY", "no_proxy"),
CGI: os.Getenv("REQUEST_METHOD") != "",
}
// Check if a proxy should be used based on environment variables
return proxyConfig.ProxyFunc()(url)
}
func getGRPCProxyEnv() string {
return getEnvAny("GRPC_PROXY", "grpc_proxy")
}
func getEnvAny(names ...string) string {
for _, n := range names {
if val := os.Getenv(n); val != "" {
return val
}
}
return ""
}