-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathadmin.go
387 lines (322 loc) · 11.9 KB
/
admin.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
//
// DISCLAIMER
//
// Copyright 2016-2021 ArangoDB GmbH, Cologne, Germany
//
// 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.
//
// Copyright holder is ArangoDB GmbH, Cologne, Germany
//
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"github.com/pkg/errors"
"github.com/spf13/cobra"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/arangodb-helper/go-certificates"
"github.com/arangodb/go-driver/jwt"
"github.com/arangodb/go-driver/v2/connection"
v12 "github.com/arangodb/kube-arangodb/pkg/apis/deployment/v1"
extclient "github.com/arangodb/kube-arangodb/pkg/client"
"github.com/arangodb/kube-arangodb/pkg/util/constants"
"github.com/arangodb/kube-arangodb/pkg/util/k8sutil"
"github.com/arangodb/kube-arangodb/pkg/util/k8sutil/inspector/secret"
)
const ArgDeploymentName = "deployment-name"
func init() {
var deploymentName string
cmdMain.AddCommand(cmdAdmin)
cmdAdmin.AddCommand(cmdAgency)
cmdAgency.AddCommand(cmdAgencyDump)
cmdAgencyDump.Flags().StringVarP(&deploymentName, ArgDeploymentName, "d", "",
"necessary when more than one deployment exist within on namespace")
cmdAgency.AddCommand(cmdAgencyState)
cmdAgencyState.Flags().StringVarP(&deploymentName, ArgDeploymentName, "d", "",
"necessary when more than one deployment exist within on namespace")
}
var cmdAdmin = &cobra.Command{
Use: "admin",
Short: "Administration operations",
Run: adminShowUsage,
}
var cmdAgency = &cobra.Command{
Use: "agency",
Short: "Agency operations",
Run: agencyShowUsage,
}
var cmdAgencyDump = &cobra.Command{
Use: "dump",
Short: "Get agency dump",
Long: "It prints the agency history on the stdout",
Run: cmdGetAgencyDump,
}
var cmdAgencyState = &cobra.Command{
Use: "state",
Short: "Get agency state",
Long: "It prints the agency current state on the stdout",
Run: cmdGetAgencyState,
}
func agencyShowUsage(cmd *cobra.Command, _ []string) {
cmd.Usage()
}
func adminShowUsage(cmd *cobra.Command, _ []string) {
cmd.Usage()
}
func cmdGetAgencyState(cmd *cobra.Command, _ []string) {
deploymentName, _ := cmd.Flags().GetString(ArgDeploymentName)
ctx := getInterruptionContext()
d, certCA, auth, err := getDeploymentAndCredentials(ctx, deploymentName)
if err != nil {
cliLog.Fatal().Err(err).Msg("failed to create basic data for the connection")
}
if d.Spec.GetMode() != v12.DeploymentModeCluster {
cliLog.Fatal().Msgf("agency state does not work for the \"%s\" deployment \"%s\"", d.Spec.GetMode(),
d.GetName())
}
dnsName := k8sutil.CreatePodDNSName(d.GetObjectMeta(), v12.ServerGroupAgents.AsRole(), d.Status.Members.Agents[0].ID)
endpoint := getArangoEndpoint(d.Spec.IsSecure(), dnsName)
conn := createClient([]string{endpoint}, certCA, auth, connection.ApplicationJSON)
leaderID, err := getAgencyLeader(ctx, conn)
if err != nil {
cliLog.Fatal().Err(err).Msg("failed to get leader ID")
}
dnsLeaderName := k8sutil.CreatePodDNSName(d.GetObjectMeta(), v12.ServerGroupAgents.AsRole(), leaderID)
leaderEndpoint := getArangoEndpoint(d.Spec.IsSecure(), dnsLeaderName)
conn = createClient([]string{leaderEndpoint}, certCA, auth, connection.PlainText)
body, err := getAgencyState(ctx, conn)
if body != nil {
defer body.Close()
}
if err != nil {
cliLog.Fatal().Err(err).Msg("can not get state of the agency")
}
// Print and receive parallelly.
io.Copy(os.Stdout, body)
}
func cmdGetAgencyDump(cmd *cobra.Command, _ []string) {
deploymentName, _ := cmd.Flags().GetString(ArgDeploymentName)
ctx := getInterruptionContext()
d, certCA, auth, err := getDeploymentAndCredentials(ctx, deploymentName)
if err != nil {
cliLog.Fatal().Err(err).Msg("failed to create basic data for the connection")
}
if d.Spec.GetMode() != v12.DeploymentModeCluster {
cliLog.Fatal().Msgf("agency dump does not work for the \"%s\" deployment \"%s\"", d.Spec.GetMode(),
d.GetName())
}
endpoint := getArangoEndpoint(d.Spec.IsSecure(), k8sutil.CreateDatabaseClientServiceDNSName(d.GetObjectMeta()))
conn := createClient([]string{endpoint}, certCA, auth, connection.ApplicationJSON)
body, err := getAgencyDump(ctx, conn)
if body != nil {
defer body.Close()
}
if err != nil {
cliLog.Fatal().Err(err).Msg("can not get dump")
}
// Print and receive parallelly.
io.Copy(os.Stdout, body)
}
// getAgencyState returns the current state in the agency.
func getAgencyState(ctx context.Context, conn connection.Connection) (io.ReadCloser, error) {
url := connection.NewUrl("_api", "agency", "read")
data := []byte(`[["/"]]`)
resp, body, err := connection.CallStream(ctx, conn, http.MethodPost, url, connection.WithBody(data))
if err != nil {
return nil, err
}
if resp.Code() != http.StatusOK {
return nil, errors.New(fmt.Sprintf("unexpected HTTP status from \"%s\" endpoint", url))
}
return body, nil
}
// getDeploymentAndCredentials returns deployment and necessary credentials to communicate with ArangoDB pods.
func getDeploymentAndCredentials(ctx context.Context,
deploymentName string) (d v12.ArangoDeployment, certCA *x509.CertPool, auth connection.Authentication, err error) {
namespace := os.Getenv(constants.EnvOperatorPodNamespace)
if len(namespace) == 0 {
err = errors.New(fmt.Sprintf("\"%s\" environment variable missing", constants.EnvOperatorPodNamespace))
return
}
kubeCli, err := k8sutil.NewKubeClient()
if err != nil {
err = errors.WithMessage(err, "failed to create Kubernetes client")
return
}
d, err = getDeployment(ctx, namespace, deploymentName)
if err != nil {
err = errors.WithMessage(err, "failed to get deployment")
return
}
var secrets = kubeCli.CoreV1().Secrets(d.GetNamespace())
certCA, err = getCACertificate(ctx, secrets, d.Spec.TLS.GetCASecretName())
if err != nil {
err = errors.WithMessage(err, "failed to get CA certificate")
return
}
auth, err = getJWTTokenFromSecrets(ctx, secrets, d.Spec.Authentication.GetJWTSecretName())
if err != nil {
err = errors.WithMessage(err, "failed to get JWT token")
return
}
return
}
// getArangoEndpoint returns ArangoDB endpoint with scheme and port for the given dnsName.
func getArangoEndpoint(secure bool, dnsName string) string {
if secure {
return "https://" + net.JoinHostPort(dnsName, strconv.Itoa(k8sutil.ArangoPort))
}
return "http://" + net.JoinHostPort(dnsName, strconv.Itoa(k8sutil.ArangoPort))
}
// getAgencyLeader returns the leader ID of the agency.
func getAgencyLeader(ctx context.Context, conn connection.Connection) (string, error) {
url := connection.NewUrl("_api", "agency", "config")
output := make(map[string]interface{})
resp, err := connection.CallGet(ctx, conn, url, &output)
if err != nil {
return "", err
}
if resp.Code() != http.StatusOK {
return "", errors.New("unexpected HTTP status from agency-dump endpoint")
}
if leaderID, ok := output["leaderId"]; ok {
if id, ok := leaderID.(string); ok {
return id, nil
}
}
return "", errors.New("failed get agency leader ID")
}
// getAgencyDump returns dump of the agency.
func getAgencyDump(ctx context.Context, conn connection.Connection) (io.ReadCloser, error) {
url := connection.NewUrl("_api", "cluster", "agency-dump")
resp, body, err := connection.CallStream(ctx, conn, http.MethodGet, url)
if err != nil {
return nil, err
}
if resp.Code() != http.StatusOK {
return nil, errors.New("unexpected HTTP status from agency-dump endpoint")
}
return body, nil
}
type JWTAuthentication struct {
key, value string
}
func (j JWTAuthentication) RequestModifier(r connection.Request) error {
r.AddHeader(j.key, j.value)
return nil
}
// createClient creates client for the provided credentials.
func createClient(endpoints []string, certCA *x509.CertPool, auth connection.Authentication,
contentType string) connection.Connection {
conf := connection.HttpConfiguration{
Authentication: auth,
ContentType: contentType,
Endpoint: connection.NewEndpoints(endpoints...),
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: certCA,
},
},
}
return connection.NewHttpConnection(conf)
}
// getJWTTokenFromSecrets returns token from the secret.
func getJWTTokenFromSecrets(ctx context.Context, secrets secret.ReadInterface, name string) (connection.Authentication, error) {
ctxChild, cancel := context.WithTimeout(ctx, k8sutil.GetRequestTimeout())
defer cancel()
token, err := k8sutil.GetTokenSecret(ctxChild, secrets, name)
if err != nil {
return nil, errors.WithMessage(err, fmt.Sprintf("failed to get secret \"%s\"", name))
}
bearerToken, err := jwt.CreateArangodJwtAuthorizationHeader(token, "kube-arangodb")
if err != nil {
return nil, errors.WithMessage(err, fmt.Sprintf("failed to create bearer token from secret \"%s\"", name))
}
return JWTAuthentication{key: "Authorization", value: bearerToken}, nil
}
// getCACertificate returns CA certificate from the secret.
func getCACertificate(ctx context.Context, secrets secret.ReadInterface, name string) (*x509.CertPool, error) {
ctxChild, cancel := context.WithTimeout(ctx, k8sutil.GetRequestTimeout())
defer cancel()
s, err := secrets.Get(ctxChild, name, metav1.GetOptions{})
if err != nil {
return nil, errors.WithMessage(err, fmt.Sprintf("failed to get secret \"%s\"", name))
}
if data, ok := s.Data[v1.ServiceAccountRootCAKey]; ok {
return certificates.LoadCertPool(string(data))
}
return nil, errors.New(fmt.Sprintf("the \"%s\" does not exist in the secret \"%s\"", v1.ServiceAccountRootCAKey,
name))
}
// getDeployment returns ArangoDeployment within the provided namespace.
// If there are more than two deployments within one namespace then
// deployment name must be provided, otherwise error is returned.
func getDeployment(ctx context.Context, namespace, deplName string) (v12.ArangoDeployment, error) {
extCli, err := extclient.NewClient()
if err != nil {
return v12.ArangoDeployment{}, errors.WithMessage(err, "failed to create Arango extension client")
}
ctxChild, cancel := context.WithTimeout(ctx, k8sutil.GetRequestTimeout())
defer cancel()
deployments, err := extCli.DatabaseV1().ArangoDeployments(namespace).List(ctxChild, metav1.ListOptions{})
if err != nil {
if v12.IsNotFound(err) {
return v12.ArangoDeployment{}, errors.WithMessage(err, "there are no deployments")
}
return v12.ArangoDeployment{}, errors.WithMessage(err, "failed to get deployments")
}
if len(deployments.Items) == 0 {
return v12.ArangoDeployment{}, errors.WithMessage(err, "there are no deployments")
}
if len(deplName) > 0 {
// The specific deployment is requested.
for _, d := range deployments.Items {
if d.GetName() == deplName {
return d, nil
}
}
return v12.ArangoDeployment{}, errors.New(
fmt.Sprintf("the deployment \"%s\" does not exist in the namespace \"%s\"", deplName, namespace))
}
if len(deployments.Items) == 1 {
// The specific deployment is not requested and the only one deployment exist in the namespace.
return deployments.Items[0], nil
}
message := fmt.Sprintf("more than one deployment exist in the namespace \"%s\":", namespace)
for _, item := range deployments.Items {
message += fmt.Sprintf(" %s", item.GetName())
}
return v12.ArangoDeployment{}, errors.New(message)
}
// getInterruptionContext returns context which will be cancelled when the process is interrupted.
func getInterruptionContext() context.Context {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
go func() {
// Block until SIGTERM or SIGINT occurs.
<-c
cancel()
}()
return ctx
}