-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroot.go
305 lines (264 loc) · 9.05 KB
/
root.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
package cmd
// Copyright (c) 2018 Bhojpur Consulting Private Limited, India. All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import (
"bytes"
"context"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"google.golang.org/grpc"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/portforward"
"k8s.io/client-go/transport/spdy"
)
var (
verbose bool
host string
)
var rootCmdOpts struct {
Verbose bool
Host string
Kubeconfig string
K8sNamespace string
K8sLabelSelector string
K8sPodPort string
DialMode string
}
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "businessctl",
Short: "Bhojpur Central is a distributed autonomous organisation management client",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
if verbose {
log.SetLevel(log.DebugLevel)
log.Debug("verbose logging enabled")
}
},
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
type dialMode string
const (
dialModeHost = "host"
dialModeKubernetes = "kubernetes"
)
func init() {
businessHost := os.Getenv("DIGITAL_BUSINESS_HOST")
if businessHost == "" {
businessHost = "localhost:7777"
}
businessKubeconfig := os.Getenv("KUBECONFIG")
if businessKubeconfig == "" {
home, err := os.UserHomeDir()
if err != nil {
log.WithError(err).Warn("cannot determine user's home directory")
} else {
businessKubeconfig = filepath.Join(home, ".kube", "config")
}
}
businessNamespace := os.Getenv("DIGITAL_BUSINESS_K8S_NAMESPACE")
businessLabelSelector := os.Getenv("DIGITAL_BUSINESS_K8S_LABEL")
if businessLabelSelector == "" {
businessLabelSelector = "app.kubernetes.io/name=business"
}
businessPodPort := os.Getenv("DIGITAL_BUSINESS_K8S_POD_PORT")
if businessPodPort == "" {
businessPodPort = "7777"
}
dialMode := os.Getenv("DIGITAL_BUSINESS_DIAL_MODE")
if dialMode == "" {
dialMode = string(dialModeHost)
}
rootCmd.PersistentFlags().BoolVar(&rootCmdOpts.Verbose, "verbose", false, "en/disable verbose logging")
rootCmd.PersistentFlags().StringVar(&rootCmdOpts.DialMode, "dial-mode", dialMode, "dial mode that determines how we connect to Bhojpur Business. Valid values are \"host\" or \"kubernetes\" (defaults to DIGITAL_BUSINESS_DIAL_MODE env var).")
rootCmd.PersistentFlags().StringVar(&rootCmdOpts.Host, "host", businessHost, "[host dial mode] Bhojpur Business host to talk to (defaults to DIGITAL_BUSINESS_HOST env var)")
rootCmd.PersistentFlags().StringVar(&rootCmdOpts.Kubeconfig, "kubeconfig", businessKubeconfig, "[kubernetes dial mode] kubeconfig file to use (defaults to KUEBCONFIG env var)")
rootCmd.PersistentFlags().StringVar(&rootCmdOpts.K8sNamespace, "k8s-namespace", businessNamespace, "[kubernetes dial mode] Kubernetes namespace in which to look for the Bhojpur Business pods (defaults to DIGITAL_BUSINESS_K8S_NAMESPACE env var, or configured kube context namespace)")
// The following are such specific flags that really only matters if one doesn't use the stock helm charts.
// They can still be set using an env var, but there's no need to clutter the CLI with them.
rootCmdOpts.K8sLabelSelector = businessLabelSelector
rootCmdOpts.K8sPodPort = businessPodPort
}
type closableGrpcClientConnInterface interface {
grpc.ClientConnInterface
io.Closer
}
func dial() (res closableGrpcClientConnInterface) {
var err error
switch rootCmdOpts.DialMode {
case dialModeHost:
res, err = grpc.Dial(rootCmdOpts.Host, grpc.WithInsecure())
case dialModeKubernetes:
res, err = dialKubernetes()
default:
log.Fatalf("unknown dial mode: %s", rootCmdOpts.DialMode)
}
if err != nil {
log.WithError(err).Fatal("cannot connect to Bhojpur Business server")
}
return
}
func dialKubernetes() (closableGrpcClientConnInterface, error) {
kubecfg, namespace, err := getKubeconfig(rootCmdOpts.Kubeconfig)
if err != nil {
return nil, fmt.Errorf("cannot load kubeconfig %s: %w", rootCmdOpts.Kubeconfig, err)
}
if rootCmdOpts.K8sNamespace != "" {
namespace = rootCmdOpts.K8sNamespace
}
clientSet, err := kubernetes.NewForConfig(kubecfg)
if err != nil {
return nil, err
}
pod, err := findBusinessPod(clientSet, namespace, rootCmdOpts.K8sLabelSelector)
if err != nil {
return nil, fmt.Errorf("cannot find Bhojpur Business pod: %w", err)
}
localPort, err := findFreeLocalPort()
ctx, cancel := context.WithCancel(context.Background())
readychan, errchan := forwardPort(ctx, kubecfg, namespace, pod, fmt.Sprintf("%d:%s", localPort, rootCmdOpts.K8sPodPort))
select {
case err := <-errchan:
cancel()
return nil, err
case <-readychan:
}
res, err := grpc.Dial(fmt.Sprintf("localhost:%d", localPort), grpc.WithInsecure())
if err != nil {
cancel()
return nil, fmt.Errorf("cannot dial forwarded connection: %w", err)
}
return closableConn{
ClientConnInterface: res,
Closer: func() error { cancel(); return nil },
}, nil
}
type closableConn struct {
grpc.ClientConnInterface
Closer func() error
}
func (c closableConn) Close() error {
return c.Closer()
}
func findFreeLocalPort() (int, error) {
const (
start = 30000
end = 60000
)
for p := start; p <= end; p++ {
l, err := net.Listen("tcp", fmt.Sprintf(":%d", p))
if err == nil {
l.Close()
return p, nil
}
}
return 0, fmt.Errorf("no free local port found")
}
// GetKubeconfig loads kubernetes connection config from a kubeconfig file
func getKubeconfig(kubeconfig string) (res *rest.Config, namespace string, err error) {
cfg := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig},
&clientcmd.ConfigOverrides{},
)
namespace, _, err = cfg.Namespace()
if err != nil {
return nil, "", err
}
res, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
return nil, namespace, err
}
return res, namespace, nil
}
// findBusinessPod returns the first pod we found for a particular component
func findBusinessPod(clientSet kubernetes.Interface, namespace, selector string) (podName string, err error) {
pods, err := clientSet.CoreV1().Pods(namespace).List(context.Background(), metav1.ListOptions{
LabelSelector: selector,
})
if err != nil {
return "", err
}
if len(pods.Items) == 0 {
return "", fmt.Errorf("no pod in %s with label component=%s", namespace, selector)
}
return pods.Items[0].Name, nil
}
// ForwardPort establishes a TCP port forwarding to a Kubernetes pod
func forwardPort(ctx context.Context, config *rest.Config, namespace, pod, port string) (readychan chan struct{}, errchan chan error) {
errchan = make(chan error, 1)
readychan = make(chan struct{}, 1)
roundTripper, upgrader, err := spdy.RoundTripperFor(config)
if err != nil {
errchan <- err
return
}
path := fmt.Sprintf("/api/v1/namespaces/%s/pods/%s/portforward", namespace, pod)
hostIP := strings.TrimLeft(config.Host, "https://")
serverURL := url.URL{Scheme: "https", Path: path, Host: hostIP}
dialer := spdy.NewDialer(upgrader, &http.Client{Transport: roundTripper}, http.MethodPost, &serverURL)
stopChan := make(chan struct{}, 1)
fwdReadyChan := make(chan struct{}, 1)
out, errOut := new(bytes.Buffer), new(bytes.Buffer)
forwarder, err := portforward.New(dialer, []string{port}, stopChan, fwdReadyChan, out, errOut)
if err != nil {
panic(err)
}
var once sync.Once
go func() {
err := forwarder.ForwardPorts()
if err != nil {
errchan <- err
}
once.Do(func() { close(readychan) })
}()
go func() {
select {
case <-readychan:
// we're out of here
case <-ctx.Done():
close(stopChan)
}
}()
go func() {
for range fwdReadyChan {
}
if errOut.Len() != 0 {
errchan <- fmt.Errorf(errOut.String())
return
}
once.Do(func() { close(readychan) })
}()
return
}