-
Notifications
You must be signed in to change notification settings - Fork 1
/
install.go
254 lines (225 loc) · 7.77 KB
/
install.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
package install
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
"encoding/pem"
"flag"
"fmt"
"github.com/chirino/svcteleporter/internal/cmd"
"github.com/chirino/svcteleporter/internal/pkg/utils"
"github.com/spf13/cobra"
"io/ioutil"
"log"
"math/big"
"sigs.k8s.io/yaml"
"strings"
"text/template"
"time"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/config"
)
func New() *cobra.Command {
o := Options{
Proxies: []cmd.ProxySpec{},
}
command := &cobra.Command{Use: `install [[kube-service[:port],]target-host:target:port]+`}
// Lets rexport the flags installed by the controller runtime, and make them a little less kube specific
f := *flag.CommandLine.Lookup("kubeconfig")
f.Name = "config"
f.Usage = "path to the config file to connect to the cluster"
command.PersistentFlags().AddGoFlag(&f)
f = *flag.CommandLine.Lookup("master")
f.Usage = "the address of the cluster API server."
command.PersistentFlags().AddGoFlag(&f)
// cmd.PersistentFlags().StringVar(&options.KubeConfig, "config", , "path to the config file to connect to the cluster")
namespace, _ := GetClientNamespace(o.KubeConfig)
command.PersistentFlags().StringVarP(&o.Namespace, "namespace", "n", namespace, "namespace to run against")
command.Flags().StringVar(&o.ImporterHostPort, "importer-host-port", "", "The public hostname:port the importer will run at")
command.Flags().StringVar(&o.Prefix, "config-prefix", "", "config file prefix")
command.Flags().DurationVar(&o.Duration, "duration", 10*365*24*time.Hour, "duration that mutual TLS certificates will be valid for")
command.Flags().IntVar(&o.KeySize, "key-size", 4096, "size of RSA key to generate.")
command.Flags().StringArrayVar(&o.Kinds, "output", []string{"openshift", "standalone"}, "the types of configuration outputs to generate. on of: openshif or standalone.")
command.RunE = func(c *cobra.Command, args []string) (err error) {
if len(args) < 1 {
return fmt.Errorf("invalid usage. expecting:[proxy-port:target-host:target:port]+")
}
for _, arg := range args {
proxy, err := cmd.ParseProxySpec(arg)
if err != nil {
return err
}
o.Proxies = append(o.Proxies, proxy)
}
utils.ExitOnError(ConfigFiles(o))
return nil
}
return command
}
type Options struct {
KubeConfig string
Namespace string
KeySize int
Duration time.Duration
Prefix string
Kinds []string
ImporterHostPort string
Proxies []cmd.ProxySpec
}
type RenderScope struct {
ImporterConfig *cmd.ImporterConfig
ExporterConfig *cmd.ExporterConfig
ImporterConfigBase64 string
ExporterConfigBase64 string
}
func ConfigFiles(o Options) (err error) {
outputKinds := map[string]bool{}
for _, value := range o.Kinds {
outputKinds[strings.ToLower(value)] = true
}
ic := cmd.ImporterConfig{
Listen: "0.0.0.0:1443",
Services: o.Proxies,
}
ec := cmd.ExporterConfig{
ImporterHostPort: o.ImporterHostPort,
Proxies: o.Proxies,
}
scope := RenderScope{
ImporterConfig: &ic,
ExporterConfig: &ec,
}
ic.Cert, ic.Key, err = createCertificate(o.KeySize, o.Duration, "importer")
if err != nil {
return err
}
ec.Cert, ec.Key, err = createCertificate(o.KeySize, o.Duration, "exporter")
if err != nil {
return err
}
ic.CAs = []string{ec.Cert}
ec.CAs = []string{ic.Cert}
icm, err := yaml.Marshal(ic)
if err != nil {
return err
}
scope.ImporterConfigBase64 = base64.StdEncoding.EncodeToString(icm)
ecm, err := yaml.Marshal(ec)
if err != nil {
return err
}
scope.ExporterConfigBase64 = base64.StdEncoding.EncodeToString(ecm)
if outputKinds["standalone"] {
err = writeFile(o.Prefix+"standalone-importer.yaml", icm)
if err != nil {
return err
}
err = writeFile(o.Prefix+"standalone-exporter.yaml", ecm)
if err != nil {
return err
}
}
if outputKinds["openshift"] {
resources, err := Render(importerOpenshiftTemplate, scope)
if err != nil {
return err
}
err = writeFile(o.Prefix+"openshift-importer.yaml", []byte(resources))
if err != nil {
return err
}
resources, err = Render(exporterOpenshiftTemplate, scope)
if err != nil {
return err
}
err = writeFile(o.Prefix+"openshift-exporter.yaml", []byte(resources))
if err != nil {
return err
}
}
fmt.Println("")
fmt.Println("These files contain secrets. Please be careful sharing them.")
return nil
}
func writeFile(name string, data []byte) error {
err := ioutil.WriteFile(name, data, 0600)
if err != nil {
return err
}
fmt.Println("wrote: ", name)
return nil
}
func Render(goTemplate string, scope interface{}) (string, error) {
t, err := template.New("Render").Funcs(map[string]interface{}{
"add": func(a int, b int) int {
return a + b
},
}).Parse(goTemplate)
if err != nil {
return "", err
}
buffer := bytes.NewBuffer(nil)
err = t.Execute(buffer, scope)
if err != nil {
return "", err
}
s := buffer.String()
return s, nil
}
func createCertificate(keySize int, duration time.Duration, commonName string) (publicCert string, privateKey string, err error) {
priv, err := rsa.GenerateKey(rand.Reader, keySize)
if err != nil {
return "", "", fmt.Errorf("failed to generate private key: %s", err)
}
notBefore := time.Now()
notAfter := notBefore.Add(duration)
serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
log.Fatalf("failed to generate serial number: %s", err)
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"localhost"},
CommonName: commonName,
},
NotBefore: notBefore,
NotAfter: notAfter,
IsCA: true,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
BasicConstraintsValid: true,
DNSNames: []string{commonName},
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
log.Fatalf("Failed to create certificate: %s", err)
}
certOut := bytes.NewBuffer(nil)
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
cert := certOut.String()
keyOut := bytes.NewBuffer(nil)
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
key := keyOut.String()
return cert, key, nil
}
func (o *Options) GetClientConfig() *rest.Config {
c, err := config.GetConfig()
utils.ExitOnError(err)
return c
}
func (o *Options) GetClient() (c client.Client, err error) {
return client.New(o.GetClientConfig(), client.Options{})
}
func (o *Options) NewDynamicClient() (c dynamic.Interface, err error) {
return dynamic.NewForConfig(o.GetClientConfig())
}
func (o *Options) NewApiClient() (*kubernetes.Clientset, error) {
return kubernetes.NewForConfig(o.GetClientConfig())
}