blob: eb9070f1620c0e8465e2c2478c5a0a1385160421 [file] [log] [blame]
Lorenz Brun878f5f92020-05-12 16:15:39 +02001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17package main
18
19import (
20 "context"
21 "flag"
22 "fmt"
Serge Bazanskib0272182020-11-02 18:39:44 +010023 "io"
Lorenz Brun878f5f92020-05-12 16:15:39 +020024 "io/ioutil"
25 "math/rand"
26 "os"
Lorenz Brun878f5f92020-05-12 16:15:39 +020027 "time"
28
29 "github.com/spf13/pflag"
30 "google.golang.org/grpc"
31 cliflag "k8s.io/component-base/cli/flag"
32 "k8s.io/kubectl/pkg/cmd/plugin"
33 "k8s.io/kubectl/pkg/util/logs"
34 "k8s.io/kubernetes/pkg/kubectl/cmd"
35
Serge Bazanski31370b02021-01-07 16:31:14 +010036 "source.monogon.dev/metropolis/pkg/logtree"
37 apb "source.monogon.dev/metropolis/proto/api"
Lorenz Brun878f5f92020-05-12 16:15:39 +020038)
39
40func main() {
Serge Bazanskiefdb6e92020-07-13 17:19:27 +020041 ctx := context.Background()
Lorenz Brun878f5f92020-05-12 16:15:39 +020042 // Hardcode localhost since this should never be used to interface with a production node because of missing
43 // encryption & authentication
44 grpcClient, err := grpc.Dial("localhost:7837", grpc.WithInsecure())
45 if err != nil {
46 fmt.Printf("Failed to dial debug service (is it running): %v\n", err)
47 }
Serge Bazanskiefdb6e92020-07-13 17:19:27 +020048 debugClient := apb.NewNodeDebugServiceClient(grpcClient)
Lorenz Brun878f5f92020-05-12 16:15:39 +020049 if len(os.Args) < 2 {
50 fmt.Println("Please specify a subcommand")
51 os.Exit(1)
52 }
53
54 logsCmd := flag.NewFlagSet("logs", flag.ExitOnError)
Serge Bazanskib0272182020-11-02 18:39:44 +010055 logsTailN := logsCmd.Int("tail", -1, "Get last n lines (-1 = whole buffer, 0 = disable)")
56 logsStream := logsCmd.Bool("follow", false, "Stream log entries live from the system")
57 logsRecursive := logsCmd.Bool("recursive", false, "Get entries from entire DN subtree")
Lorenz Brun878f5f92020-05-12 16:15:39 +020058 logsCmd.Usage = func() {
Serge Bazanskib0272182020-11-02 18:39:44 +010059 fmt.Fprintf(os.Stderr, "Usage: %s %s [options] dn\n", os.Args[0], os.Args[1])
Lorenz Brun878f5f92020-05-12 16:15:39 +020060 flag.PrintDefaults()
61
Serge Bazanskib0272182020-11-02 18:39:44 +010062 fmt.Fprintf(os.Stderr, "Example:\n %s %s --tail 5 --follow init\n", os.Args[0], os.Args[1])
Lorenz Brun878f5f92020-05-12 16:15:39 +020063 }
64 conditionCmd := flag.NewFlagSet("condition", flag.ExitOnError)
65 conditionCmd.Usage = func() {
66 fmt.Fprintf(os.Stderr, "Usage: %s %s [options] component_path\n", os.Args[0], os.Args[1])
67 flag.PrintDefaults()
68
69 fmt.Fprintf(os.Stderr, "Example:\n %s %s IPAssigned\n", os.Args[0], os.Args[1])
70 }
Serge Bazanskib0272182020-11-02 18:39:44 +010071
Lorenz Brun878f5f92020-05-12 16:15:39 +020072 switch os.Args[1] {
73 case "logs":
74 logsCmd.Parse(os.Args[2:])
Serge Bazanskib0272182020-11-02 18:39:44 +010075 dn := logsCmd.Arg(0)
76 req := &apb.GetLogsRequest{
77 Dn: dn,
78 BacklogMode: apb.GetLogsRequest_BACKLOG_DISABLE,
79 StreamMode: apb.GetLogsRequest_STREAM_DISABLE,
80 Filters: nil,
81 }
82
83 switch *logsTailN {
84 case 0:
85 case -1:
86 req.BacklogMode = apb.GetLogsRequest_BACKLOG_ALL
87 default:
88 req.BacklogMode = apb.GetLogsRequest_BACKLOG_COUNT
89 req.BacklogCount = int64(*logsTailN)
90 }
91
92 if *logsStream {
93 req.StreamMode = apb.GetLogsRequest_STREAM_UNBUFFERED
94 }
95
96 if *logsRecursive {
97 req.Filters = append(req.Filters, &apb.LogFilter{
98 Filter: &apb.LogFilter_WithChildren_{WithChildren: &apb.LogFilter_WithChildren{}},
99 })
100 }
101
102 stream, err := debugClient.GetLogs(ctx, req)
Lorenz Brun878f5f92020-05-12 16:15:39 +0200103 if err != nil {
104 fmt.Fprintf(os.Stderr, "Failed to get logs: %v\n", err)
105 os.Exit(1)
106 }
Serge Bazanskib0272182020-11-02 18:39:44 +0100107 for {
108 res, err := stream.Recv()
109 if err != nil {
110 if err == io.EOF {
111 os.Exit(0)
112 }
113 fmt.Fprintf(os.Stderr, "Failed to stream logs: %v\n", err)
114 os.Exit(1)
115 }
116 for _, entry := range res.BacklogEntries {
117 entry, err := logtree.LogEntryFromProto(entry)
118 if err != nil {
119 fmt.Printf("error decoding entry: %v", err)
120 continue
121 }
122 fmt.Println(entry.String())
123 }
Lorenz Brun878f5f92020-05-12 16:15:39 +0200124 }
Lorenz Brun878f5f92020-05-12 16:15:39 +0200125 case "kubectl":
126 // Always get a kubeconfig with cluster-admin (group system:masters), kubectl itself can impersonate
127 kubeconfigFile, err := ioutil.TempFile("", "dbg_kubeconfig")
128 if err != nil {
129 fmt.Fprintf(os.Stderr, "Failed to create kubeconfig temp file: %v\n", err)
130 os.Exit(1)
131 }
132 defer kubeconfigFile.Close()
133 defer os.Remove(kubeconfigFile.Name())
134
Serge Bazanskiefdb6e92020-07-13 17:19:27 +0200135 res, err := debugClient.GetDebugKubeconfig(ctx, &apb.GetDebugKubeconfigRequest{Id: "debug-user", Groups: []string{"system:masters"}})
Lorenz Brun878f5f92020-05-12 16:15:39 +0200136 if err != nil {
137 fmt.Fprintf(os.Stderr, "Failed to get kubeconfig: %v\n", err)
138 os.Exit(1)
139 }
140 if _, err := kubeconfigFile.WriteString(res.DebugKubeconfig); err != nil {
141 fmt.Fprintf(os.Stderr, "Failed to write kubeconfig: %v\n", err)
142 os.Exit(1)
143 }
144
145 // This magic sets up everything as if this was just the kubectl binary. It sets the KUBECONFIG environment
146 // variable so that it knows where the Kubeconfig is located and forcibly overwrites the arguments so that
147 // the "wrapper" arguments are not visible to its flags parser. The base code is straight from
148 // https://github.com/kubernetes/kubernetes/blob/master/cmd/kubectl/kubectl.go
149 os.Setenv("KUBECONFIG", kubeconfigFile.Name())
150 rand.Seed(time.Now().UnixNano())
151 pflag.CommandLine.SetNormalizeFunc(cliflag.WordSepNormalizeFunc)
152 pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
153 logs.InitLogs()
154 defer logs.FlushLogs()
155 command := cmd.NewDefaultKubectlCommandWithArgs(cmd.NewDefaultPluginHandler(plugin.ValidPluginFilenamePrefixes), os.Args[2:], os.Stdin, os.Stdout, os.Stderr)
156 command.SetArgs(os.Args[2:])
157 if err := command.Execute(); err != nil {
158 os.Exit(1)
159 }
160 }
161}