-
Notifications
You must be signed in to change notification settings - Fork 3
/
tmc.go
200 lines (170 loc) · 6.25 KB
/
tmc.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
/*
Copyright 2021 The KCP Authors.
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.
*/
package main
import (
"fmt"
"math/rand"
"os"
"strings"
"time"
"github.com/kcp-dev/kcp/pkg/embeddedetcd"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/util/errors"
genericapiserver "k8s.io/apiserver/pkg/server"
"k8s.io/client-go/rest"
"k8s.io/component-base/cli"
cliflag "k8s.io/component-base/cli/flag"
"k8s.io/component-base/cli/globalflag"
"k8s.io/component-base/logs"
logsapiv1 "k8s.io/component-base/logs/api/v1"
_ "k8s.io/component-base/logs/json/register"
"k8s.io/component-base/term"
"k8s.io/component-base/version"
"k8s.io/klog/v2"
"github.com/kcp-dev/contrib-tmc/tmc/cmd/help"
tmcfeatures "github.com/kcp-dev/contrib-tmc/tmc/features"
tmcserver "github.com/kcp-dev/contrib-tmc/tmc/server"
"github.com/kcp-dev/contrib-tmc/tmc/server/options"
)
func main() {
rand.Seed(time.Now().UTC().UnixNano())
cmd := &cobra.Command{
Use: "tmc",
Short: "TMC - Transparent Multi Cluster - kcp subproject for multi-cluster workload management",
Long: help.Doc(`
TMC is the easiest way to manage Kubernetes applications against one or
more clusters, by giving you a personal control plane that schedules your
workloads onto one or many clusters, and making it simple to pick up and
move. It supports advanced use cases such as spreading your apps across
clusters for resiliency, scheduling batch workloads onto clusters with
free capacity, and enabling collaboration for individual teams without
having access to the underlying clusters.
To get started, launch a new cluster with 'tmc start', which will
initialize tmc and bootstrap its resources inside KCP
`),
SilenceUsage: true,
SilenceErrors: true,
}
cols, _, _ := term.TerminalSize(cmd.OutOrStdout())
// manually extract root directory from flags first as it influence all other flags
rootDir := ".tmc"
for i, f := range os.Args {
if f == "--root-directory" {
if i < len(os.Args)-1 {
rootDir = os.Args[i+1]
} // else let normal flag processing fail
} else if strings.HasPrefix(f, "--root-directory=") {
rootDir = strings.TrimPrefix(f, "--root-directory=")
}
}
// HACK: We already pass the root directory to the generic options, but we need to
// strip it from the command line arguments so that the generic options don't
// complain about unknown flags.
for i, f := range os.Args {
if f == "--root-directory" || strings.HasPrefix(f, "--root-directory=") {
os.Args = append(os.Args[:i], os.Args[i+2:]...)
break
}
}
serverOptions := options.NewOptions(rootDir)
serverOptions.Core.GenericControlPlane.Logs.Verbosity = logsapiv1.VerbosityLevel(2)
startCmd := &cobra.Command{
Use: "start",
Short: "Start the control plane process",
Long: help.Doc(`
Start the control plane process
The server process listens on port 6443 and will act like a Kubernetes
API server. It will initialize any necessary data to the provided start
location or as a '.kcp' directory in the current directory. An admin
kubeconfig file will be generated at initialization time that may be
used to access the control plane.
`),
PersistentPreRunE: func(*cobra.Command, []string) error {
// silence client-go warnings.
// apiserver loopback clients should not log self-issued warnings.
rest.SetDefaultWarningHandler(rest.NoWarnings{})
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
// run as early as possible to avoid races later when some components (e.g. grpc) start early using klog
if err := logsapiv1.ValidateAndApply(serverOptions.Core.GenericControlPlane.Logs, tmcfeatures.DefaultFeatureGate); err != nil {
return err
}
completed, err := serverOptions.Complete(rootDir)
if err != nil {
return err
}
if errs := completed.Validate(); len(errs) > 0 {
return errors.NewAggregate(errs)
}
logger := klog.FromContext(cmd.Context())
logger.Info("running with selected batteries", "batteries", strings.Join(completed.Core.Extra.BatteriesIncluded, ","))
config, err := tmcserver.NewConfig(*completed)
if err != nil {
return err
}
completedConfig, err := config.Complete()
if err != nil {
return err
}
ctx := genericapiserver.SetupSignalContext()
// the etcd server must be up before NewServer because storage decorators access it right away
if completedConfig.Core.EmbeddedEtcd.Config != nil {
if err := embeddedetcd.NewServer(completedConfig.Core.EmbeddedEtcd).Run(ctx); err != nil {
return err
}
}
s, err := tmcserver.NewServer(completedConfig)
if err != nil {
return err
}
return s.Run(ctx)
},
}
// add start named flag sets to start flags
fss := cliflag.NamedFlagSets{}
serverOptions.AddFlags(&fss)
globalflag.AddGlobalFlags(fss.FlagSet("global"), cmd.Name(), logs.SkipLoggingConfigurationFlags())
startFlags := startCmd.Flags()
for _, f := range fss.FlagSets {
startFlags.AddFlagSet(f)
}
startOptionsCmd := &cobra.Command{
Use: "options",
Short: "Show all start command options",
Long: help.Doc(`
Show all start command options
"tmc start"" has a large number of options. This command shows all of them.
`),
PersistentPreRunE: func(*cobra.Command, []string) error {
// silence client-go warnings.
// apiserver loopback clients should not log self-issued warnings.
rest.SetDefaultWarningHandler(rest.NoWarnings{})
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Fprintf(cmd.OutOrStderr(), usageFmt, startCmd.UseLine())
cliflag.PrintSections(cmd.OutOrStderr(), fss, cols)
return nil
},
}
startCmd.AddCommand(startOptionsCmd)
cmd.AddCommand(startCmd)
help.FitTerminal(cmd.OutOrStdout())
if v := version.Get().String(); len(v) == 0 {
cmd.Version = "<unknown>"
} else {
cmd.Version = v
}
os.Exit(cli.Run(cmd))
}