-
Notifications
You must be signed in to change notification settings - Fork 10
/
shared.go
297 lines (248 loc) · 8.89 KB
/
shared.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package shared
import (
"errors"
"fmt"
"io"
"net/url"
"os"
"reflect"
"strings"
"github.com/apigee/apigee-remote-service-cli/apigee"
"github.com/apigee/apigee-remote-service-cli/testutil"
"github.com/apigee/apigee-remote-service-envoy/server"
"github.com/spf13/cobra"
)
const (
// GCPExperienceBase is the default management API URL for GCP Experience
GCPExperienceBase = "https://apigee.googleapis.com"
// LegacySaaSManagementBase is the default base for legacy SaaS management operations
LegacySaaSManagementBase = "https://api.enterprise.apigee.com"
// DefaultManagementBase is the base URL for GCE Experience management operations
DefaultManagementBase = GCPExperienceBase
// RuntimeBaseFormat is a format for base of the organization runtime URL (legacy SaaS and OPDK)
RuntimeBaseFormat = "https://%s-%s.apigee.net"
internalProxyURLLegacySaaS = "https://istioservices.apigee.net/edgemicro"
internalProxyURLFormatOPDK = "%s/edgemicro" // runtimeBase
remoteServicePath = "/remote-service"
remoteServiceProxyURLFormat = "%s" + remoteServicePath // runtimeBase
)
// BuildInfoType holds version information
type BuildInfoType struct {
Version string
Commit string
Date string
}
// BuildInfo is populated by main init()
var BuildInfo BuildInfoType
// RootArgs is the base struct to hold all command arguments
type RootArgs struct {
RuntimeBase string // "https://org-env.apigee.net"
ManagementBase string // "https://api.enterprise.apigee.com"
Verbose bool
Org string
Env string
Username string
Password string
MFAToken string
Token string
NetrcPath string
IsOPDK bool
IsLegacySaaS bool
IsGCPManaged bool
ConfigPath string
InsecureSkipVerify bool
Namespace string
ServerConfig *server.Config // config loaded from ConfigPath
// the following is derived in Resolve()
InternalProxyURL string
RemoteServiceProxyURL string
ApigeeClient *apigee.EdgeClient
ClientOpts *apigee.EdgeClientOptions
}
// AddCommandWithFlags adds to the root command with standard flags
func AddCommandWithFlags(c *cobra.Command, rootArgs *RootArgs, cmds ...*cobra.Command) {
for _, subC := range cmds {
subC.PersistentFlags().StringVarP(&rootArgs.RuntimeBase, "runtime", "r",
"", "Apigee runtime base URL (required for hybrid or opdk)")
subC.PersistentFlags().BoolVarP(&rootArgs.Verbose, "verbose", "v",
false, "verbose output")
subC.PersistentFlags().StringVarP(&rootArgs.Org, "organization", "o",
"", "Apigee organization name")
subC.PersistentFlags().StringVarP(&rootArgs.Env, "environment", "e",
"", "Apigee environment name")
subC.PersistentFlags().StringVarP(&rootArgs.ConfigPath, "config", "c",
"", "path to Apigee Remote Service config file")
subC.PersistentFlags().BoolVarP(&rootArgs.InsecureSkipVerify, "insecure", "",
false, "allow insecure server connections when using SSL")
c.AddCommand(subC)
}
}
// Resolve is used to populate shared args, it's automatically called prior when creating the root command
func (r *RootArgs) Resolve(skipAuth, requireRuntime bool) error {
if err := r.loadConfig(); err != nil {
return err
}
if r.IsLegacySaaS && r.IsOPDK {
return errors.New("--legacy and --opdk options are exclusive")
}
r.IsGCPManaged = !(r.IsLegacySaaS || r.IsOPDK)
if r.ManagementBase == "" {
r.ManagementBase = DefaultManagementBase
}
if r.ManagementBase == DefaultManagementBase {
if r.IsLegacySaaS {
r.ManagementBase = LegacySaaSManagementBase
}
if r.IsOPDK {
if r.RuntimeBase == "" {
return fmt.Errorf("--runtime or --config is required and used as the management url if --management is not explicitly set for opdk")
}
r.ManagementBase = r.RuntimeBase
}
}
if r.IsLegacySaaS {
if r.Org == "" || r.Env == "" {
return fmt.Errorf("--organization and --environment are required for legacy saas")
}
if r.RuntimeBase == "" {
r.RuntimeBase = fmt.Sprintf(RuntimeBaseFormat, r.Org, r.Env)
}
}
if requireRuntime && r.RuntimeBase == "" {
return errors.New("--runtime is required for hybrid or opdk (or --organization and --environment with --legacy)")
}
// calculate internal proxy URL from runtime URL for LegacySaaS or OPDK
// note: GCPExperience doesn't have an internal proxy
if r.IsOPDK {
r.InternalProxyURL = fmt.Sprintf(internalProxyURLFormatOPDK, r.RuntimeBase)
}
if r.IsLegacySaaS {
r.InternalProxyURL = internalProxyURLLegacySaaS
}
r.RemoteServiceProxyURL = fmt.Sprintf(remoteServiceProxyURLFormat, r.RuntimeBase)
if r.IsGCPManaged && !skipAuth && r.Token == "" {
return fmt.Errorf("--token is required for hybrid")
}
r.ClientOpts = &apigee.EdgeClientOptions{
MgmtURL: r.ManagementBase,
Org: r.Org,
Env: r.Env,
Auth: &apigee.EdgeAuth{
NetrcPath: r.NetrcPath,
Username: r.Username,
Password: r.Password,
BearerToken: r.Token,
MFAToken: r.MFAToken,
SkipAuth: skipAuth,
},
GCPManaged: r.IsGCPManaged,
Debug: r.Verbose,
InsecureSkipVerify: r.InsecureSkipVerify,
}
var err error
r.ApigeeClient, err = apigee.NewEdgeClient(r.ClientOpts)
if err != nil {
if strings.Contains(err.Error(), ".netrc") { // no .netrc and no auth
baseURL, err := url.Parse(r.ManagementBase)
if err != nil {
return fmt.Errorf("unable to parse managementBase url %s: %v", r.ManagementBase, err)
}
return fmt.Errorf("no auth: must have username and password or a ~/.netrc entry for %s", baseURL.Host)
}
if strings.Contains(err.Error(), "oauth") { // OAuth failure
return fmt.Errorf("error authorizing for OAuth token: %v", err)
}
return fmt.Errorf("error initializing Edge client: %v", err)
}
return nil
}
// FormatFn formats the supplied arguments according to the format string
// provided and executes some set of operations with the result.
type FormatFn func(format string, args ...interface{})
// Printf is a FormatFn that prints the formatted string to os.Stdout.
func Printf(format string, args ...interface{}) {
fmt.Printf(format+"\n", args...)
}
// Errorf is a FormatFn that prints the formatted string to os.Stderr.
func Errorf(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format+"\n", args...)
}
// NoPrintf is a FormatFn that does nothing
func NoPrintf(format string, args ...interface{}) {
}
// FormatFnWriter bridges io.Writer to FormatFn
func FormatFnWriter(fn FormatFn) io.Writer {
return &formatFnWriter{fn}
}
type formatFnWriter struct {
formatFn FormatFn
}
func (w *formatFnWriter) Write(p []byte) (n int, err error) {
if reflect.ValueOf(w.formatFn).Pointer() == reflect.ValueOf(Printf).Pointer() {
fmt.Printf("%s", p)
}
if reflect.ValueOf(w.formatFn).Pointer() == reflect.ValueOf(Errorf).Pointer() {
fmt.Fprintf(os.Stderr, "%s", p)
}
tp := testutil.TestPrint{}
if reflect.ValueOf(w.formatFn).Pointer() == reflect.ValueOf(tp.Printf).Pointer() {
w.formatFn("%s", p)
}
return len(p), nil
}
// OverrideEnv is subconfig of overrideConfig
type OverrideEnv struct {
Name string `yaml:"name"`
HostAlias string `yaml:"hostAlias"`
}
func (r *RootArgs) loadConfig() error {
if r.ConfigPath == "" {
return nil
}
r.ServerConfig = &server.Config{}
err := r.ServerConfig.Load(r.ConfigPath, "", "", false)
if err != nil {
return err
}
r.RuntimeBase = strings.Split(r.ServerConfig.Tenant.RemoteServiceAPI, remoteServicePath)[0]
r.Org = r.ServerConfig.Tenant.OrgName
r.Env = r.ServerConfig.Tenant.EnvName
r.InsecureSkipVerify = r.ServerConfig.Tenant.AllowUnverifiedSSLCert
r.Namespace = r.ServerConfig.Global.Namespace
if r.ServerConfig.IsGCPManaged() {
r.ManagementBase = GCPExperienceBase
r.IsGCPManaged = true
if r.ServerConfig.Tenant.PrivateKey == nil || r.ServerConfig.Tenant.PrivateKeyID == "" {
return fmt.Errorf("Secret CRD not found in file: %s", r.ConfigPath)
}
}
if r.ServerConfig.IsApigeeManaged() {
r.ManagementBase = LegacySaaSManagementBase
r.IsLegacySaaS = true
}
if r.ServerConfig.IsOPDK() {
r.ManagementBase = r.RuntimeBase
r.IsOPDK = true
}
return nil
}
// PrintMissingFlags will aggregate and print an error for the passed set of flags
func (r *RootArgs) PrintMissingFlags(missingFlagNames []string) error {
if len(missingFlagNames) > 0 {
return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))
}
return nil
}