This repository has been archived by the owner on Dec 21, 2023. It is now read-only.
/
configure_domain.go
348 lines (284 loc) · 9.35 KB
/
configure_domain.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package cmd
import (
"bufio"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"math/big"
"net/http"
"net/url"
"os"
"strings"
"time"
keptnutils "github.com/keptn/go-utils/pkg/utils"
"github.com/keptn/keptn/cli/utils"
"github.com/spf13/cobra"
)
var configVersion *string
const apiVirtualServiceURL = "/installer/manifests/keptn/keptn-api-virtualservice.yaml"
const domainConfigMapURL = "/installer/manifests/keptn/keptn-domain-configmap.yaml"
const uniformServicesURL = "/installer/manifests/keptn/uniform-services.yaml"
var platformID *string
// domainCmd represents the domain command
var domainCmd = &cobra.Command{
Use: "domain domain_url",
Short: "Configures the domain",
SilenceUsage: true,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
cmd.SilenceUsage = false
return errors.New("Requires a domain as argument")
}
_, err := url.Parse(args[0])
if err != nil {
cmd.SilenceUsage = false
return errors.New("Cannot parse provided domain")
}
return nil
},
PreRunE: func(cmd *cobra.Command, args []string) error {
if insecureSkipTLSVerify {
kubectlOptions = "--insecure-skip-tls-verify=true"
}
resourcesAvailable, err := checkResourceAvailablity()
if err != nil || !resourcesAvailable {
return errors.New("Resources not found under:\n" +
getAPIVirtualServiceURL() + "\n" +
getDomainConfigMapURL() + "\n" +
getUniformServicesURL())
}
kubernetesPlatform := newKubernetesPlatform()
return kubernetesPlatform.checkRequirements()
},
RunE: func(cmd *cobra.Command, args []string) error {
ctx, _ := getKubeContext()
fmt.Println("Your kubernetes current context is configured to cluster: " + strings.TrimSpace(ctx))
fmt.Println("Would you like to update the keptn domain for this cluster? (y/n)")
reader := bufio.NewReader(os.Stdin)
in, err := reader.ReadString('\n')
if err != nil {
return err
}
in = strings.TrimSpace(in)
if in != "y" && in != "yes" {
fmt.Println("Please first configure your kubernetes current context so that it" +
"points to the cluster where you would like to update the keptn domain.")
return nil
}
fmt.Println("Please note that the domain of already onboarded services is not updated!")
utils.PrintLog("Starting to configure domain", utils.InfoLevel)
path, err := keptnutils.GetKeptnDirectory()
if err != nil {
return err
}
if !mocking {
err = updateKeptnAPIVirtualService(path, args[0])
if err != nil {
return err
}
// Generate new certificate
err = updateCertificate(path, args[0])
if err != nil {
return err
}
err = updateKeptnDomainConfigMap(path, args[0])
if err != nil {
return err
}
err = reDeployGithubService()
if err != nil {
return err
}
if strings.ToLower(*platformID) == openshift {
fmt.Println("Please manually execute the following commands for deleting an old route and creating a new route:")
fmt.Println("oc delete route istio-wildcard-ingress-secure-keptn -n istio-system")
fmt.Println("oc create route passthrough istio-wildcard-ingress-secure-keptn --service=istio-ingressgateway --hostname=\"www.keptn.ingress-gateway. " +
args[0] + "\" --port=https --wildcard-policy=Subdomain --insecure-policy='None' -n istio-system")
fmt.Println()
token, err := getAPITokenUsingKube()
if err != nil {
return err
}
fmt.Println("Afterwards, you can login with 'keptn auth --endpoint=https://api.keptn." + args[0] + " --token=" + token + "'")
} else {
fmt.Println("Successfully configured domain")
err = authUsingKube()
if err != nil {
return err
}
}
configured, err := checkIfConfiguredUsingKube()
if err != nil {
return err
}
if !configured {
fmt.Println("No GitHub configuration found on your keptn installation. Please exectue 'keptn configure'")
}
}
return nil
},
}
func reDeployGithubService() error {
o := options{"delete", "deployment", "github-service", "-n", "keptn"}
o.appendIfNotEmpty(kubectlOptions)
_, err := keptnutils.ExecuteCommand("kubectl", o)
if err != nil {
return err
}
o = options{"apply", "-f", getUniformServicesURL()}
o.appendIfNotEmpty(kubectlOptions)
_, err = keptnutils.ExecuteCommand("kubectl", o)
return err
}
func updateKeptnDomainConfigMap(path, domain string) error {
keptnDomainConfigMap := path + "keptn-domain-configmap.yaml"
if err := utils.DownloadFile(keptnDomainConfigMap, getDomainConfigMapURL()); err != nil {
return err
}
if err := utils.Replace(keptnDomainConfigMap,
utils.PlaceholderReplacement{PlaceholderValue: "DOMAIN_PLACEHOLDER", DesiredValue: domain}); err != nil {
return err
}
o := options{"delete", "-f", keptnDomainConfigMap}
o.appendIfNotEmpty(kubectlOptions)
_, err := keptnutils.ExecuteCommand("kubectl", o)
if err != nil {
return err
}
// Add config map in keptn namespace that contains the domain - this will be used by other services as well
o = options{"apply", "-f", keptnDomainConfigMap}
o.appendIfNotEmpty(kubectlOptions)
_, err = keptnutils.ExecuteCommand("kubectl", o)
return err
}
func updateKeptnAPIVirtualService(path, domain string) error {
keptnAPIVSPath := path + "keptn-api-virtualservice.yaml"
if err := utils.DownloadFile(keptnAPIVSPath, getAPIVirtualServiceURL()); err != nil {
return err
}
if err := utils.Replace(keptnAPIVSPath,
utils.PlaceholderReplacement{PlaceholderValue: "DOMAIN_PLACEHOLDER", DesiredValue: domain}); err != nil {
return err
}
// Delete old api virtual service
o := options{"delete", "-f", keptnAPIVSPath}
o.appendIfNotEmpty(kubectlOptions)
_, err := keptnutils.ExecuteCommand("kubectl", o)
if err != nil {
return err
}
// Apply new api virtual service
o = options{"apply", "-f", keptnAPIVSPath}
o.appendIfNotEmpty(kubectlOptions)
_, err = keptnutils.ExecuteCommand("kubectl", o)
return err
}
func updateCertificate(path, domain string) error {
// Source: https://golang.org/src/crypto/tls/generate_cert.go
// We can verify the generated key with 'openssl rsa -in key.pem -check'
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return err
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Keptn"},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(1, 0, 0),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
DNSNames: []string{domain},
}
// generate private key
privatekey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
publickey := &privatekey.PublicKey
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publickey, privatekey)
if err != nil {
return err
}
privateKeyPath := path + "private.key"
certPath := path + "cert.pem"
certOut, err := os.Create(certPath)
if err != nil {
return err
}
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
return err
}
if err := certOut.Close(); err != nil {
return err
}
defer os.Remove(certPath)
keyOut, err := os.OpenFile(privateKeyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
if err := pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privatekey)}); err != nil {
return err
}
if err := keyOut.Close(); err != nil {
return err
}
defer os.Remove(privateKeyPath)
// First delete secret
o := options{"delete", "--namespace", "istio-system", "secret", "istio-ingressgateway-certs"}
o.appendIfNotEmpty(kubectlOptions)
_, err = keptnutils.ExecuteCommand("kubectl", o)
o = options{"create", "--namespace", "istio-system", "secret", "tls", "istio-ingressgateway-certs",
"--key", privateKeyPath, "--cert", certPath}
o.appendIfNotEmpty(kubectlOptions)
_, err = keptnutils.ExecuteCommand("kubectl", o)
return err
}
func getAPIVirtualServiceURL() string {
return installerPrefixURL + *configVersion + apiVirtualServiceURL
}
func getDomainConfigMapURL() string {
return installerPrefixURL + *configVersion + domainConfigMapURL
}
func getUniformServicesURL() string {
return installerPrefixURL + *configVersion + uniformServicesURL
}
func checkResourceAvailablity() (bool, error) {
resp, err := http.Get(getAPIVirtualServiceURL())
if err != nil {
return false, err
}
if resp.StatusCode != http.StatusOK {
return false, nil
}
resp, err = http.Get(getDomainConfigMapURL())
if err != nil {
return false, err
}
if resp.StatusCode != http.StatusOK {
return false, nil
}
resp, err = http.Get(getUniformServicesURL())
if err != nil {
return false, err
}
if resp.StatusCode != http.StatusOK {
return false, nil
}
return true, nil
}
func init() {
configureCmd.AddCommand(domainCmd)
configVersion = domainCmd.Flags().StringP("keptn-version", "k", "master",
"The branch or tag of the version which is used for updating the domain")
domainCmd.Flags().MarkHidden("keptn-version")
domainCmd.PersistentFlags().BoolVarP(&insecureSkipTLSVerify, "insecure-skip-tls-verify", "s", false, "Skip tls verification for kubectl commands")
platformID = domainCmd.Flags().StringP("platform", "p", "gke", "The platform on which keptn is running [gke,openshift,aks,kubernetes]")
}