/
app.go
188 lines (163 loc) · 5.25 KB
/
app.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
/*
Copyright 2022 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 app
import (
"context"
"flag"
"runtime/debug"
"strings"
"github.com/spf13/cobra"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/tools/cache"
cliflag "k8s.io/component-base/cli/flag"
"k8s.io/klog/v2"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/manager"
"github.com/k8s-cloud-platform/multi-tenants/cmd/manager/app/options"
"github.com/k8s-cloud-platform/multi-tenants/pkg/apis/tenancy/v1alpha1"
"github.com/k8s-cloud-platform/multi-tenants/pkg/controllers"
)
var (
scheme = runtime.NewScheme()
)
func init() {
utilruntime.Must(corev1.AddToScheme(scheme))
utilruntime.Must(appsv1.AddToScheme(scheme))
utilruntime.Must(v1alpha1.AddToScheme(scheme))
}
// NewControllerManagerCommand creates a *cobra.Command object with default parameters
func NewControllerManagerCommand() *cobra.Command {
opts := options.NewOptions()
cmd := &cobra.Command{
Use: "manager",
Long: `KCP manager for multi-tenants.`,
RunE: func(cmd *cobra.Command, args []string) error {
if err := opts.Log.ValidateAndApply(); err != nil {
return err
}
cliflag.PrintFlags(cmd.Flags())
buildInfo, ok := debug.ReadBuildInfo()
if ok {
klog.Infof("build info: \n%s", buildInfo)
}
if errs := opts.Validate(); len(errs) != 0 {
return errs.ToAggregate()
}
return run(ctrl.SetupSignalHandler(), opts)
},
}
fs := cmd.Flags()
opts.AddFlags(fs)
fs.AddGoFlagSet(flag.CommandLine)
return cmd
}
func run(ctx context.Context, opts *options.Options) error {
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
LeaderElection: opts.LeaderElection.LeaderElect,
LeaderElectionReleaseOnCancel: true,
LeaderElectionResourceLock: opts.LeaderElection.ResourceLock,
LeaderElectionNamespace: opts.LeaderElection.ResourceNamespace,
LeaderElectionID: opts.LeaderElection.ResourceName,
LeaseDuration: &opts.LeaderElection.LeaseDuration.Duration,
RenewDeadline: &opts.LeaderElection.RenewDeadline.Duration,
RetryPeriod: &opts.LeaderElection.RetryPeriod.Duration,
ClientDisableCacheFor: []client.Object{
&corev1.Secret{},
&appsv1.Deployment{},
},
})
if err != nil {
klog.ErrorS(err, "unable to start manager")
return err
}
namespace, name, err := cache.SplitMetaNamespaceKey(opts.EtcdSecret)
if err != nil {
klog.ErrorS(err, "unable to split etcd-secret")
return err
}
if namespace == "" {
namespace = "default"
}
etcdSecret := &corev1.Secret{}
if err := mgr.GetClient().Get(ctx, types.NamespacedName{
Namespace: namespace,
Name: name,
}, etcdSecret); err != nil {
if apierrors.IsNotFound(err) {
klog.ErrorS(err, "secret[etcd-secret] not exists")
return err
}
klog.ErrorS(err, "unable to get secret for etcd-secret")
return err
}
if err = (&controllers.TenantController{
EtcdSecret: etcdSecret.Data,
EtcdServers: opts.EtcdServers,
Client: mgr.GetClient(),
}).SetupWithManager(mgr, controller.Options{
MaxConcurrentReconciles: opts.ConcurrencyTenantSync,
}); err != nil {
klog.ErrorS(err, "unable to create tenant controller")
return err
}
if err := preStart(ctx, mgr, opts); err != nil {
klog.ErrorS(err, "unable to handle pre start")
return err
}
klog.Info("starting manager")
if err := mgr.Start(ctx); err != nil {
klog.ErrorS(err, "unable to run manager")
return err
}
// never reach here
return nil
}
func preStart(ctx context.Context, mgr manager.Manager, opts *options.Options) error {
if opts.DefaultTenants == "" {
klog.V(1).Info("default-tenants is empty, skip")
return nil
}
// handle for default tenants
for _, tenant := range strings.Split(opts.DefaultTenants, ",") {
klog.InfoS("init default tenant", "name", tenant)
tenantObj := &v1alpha1.Tenant{
ObjectMeta: metav1.ObjectMeta{
Name: tenant,
},
}
if err := mgr.GetAPIReader().Get(ctx, client.ObjectKeyFromObject(tenantObj), tenantObj); err != nil {
if !apierrors.IsNotFound(err) {
klog.ErrorS(err, "unable to get tenant", "name", tenant)
return err
}
} else {
klog.InfoS("tenant already exists", "name", tenant)
continue
}
if err := mgr.GetClient().Create(ctx, tenantObj); err != nil {
klog.ErrorS(err, "unable to create tenant", "name", tenant)
return err
}
klog.InfoS("success to create tenant", "name", tenant)
}
return nil
}