forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
overwrite_bootstrappolicy.go
351 lines (306 loc) · 13.4 KB
/
overwrite_bootstrappolicy.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
package admin
import (
"errors"
"fmt"
"io"
"reflect"
"github.com/spf13/cobra"
kapierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metainternal "k8s.io/apimachinery/pkg/apis/meta/internalversion"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
kerrors "k8s.io/apimachinery/pkg/util/errors"
apirequest "k8s.io/apiserver/pkg/endpoints/request"
kapi "k8s.io/kubernetes/pkg/api"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/resource"
authorizationapi "github.com/openshift/origin/pkg/authorization/api"
policyregistry "github.com/openshift/origin/pkg/authorization/registry/policy"
policyetcd "github.com/openshift/origin/pkg/authorization/registry/policy/etcd"
policybindingregistry "github.com/openshift/origin/pkg/authorization/registry/policybinding"
policybindingetcd "github.com/openshift/origin/pkg/authorization/registry/policybinding/etcd"
rolestorage "github.com/openshift/origin/pkg/authorization/registry/role/policybased"
rolebindingstorage "github.com/openshift/origin/pkg/authorization/registry/rolebinding/policybased"
clusterpolicyregistry "github.com/openshift/origin/pkg/authorization/registry/clusterpolicy"
clusterpolicyetcd "github.com/openshift/origin/pkg/authorization/registry/clusterpolicy/etcd"
clusterpolicybindingregistry "github.com/openshift/origin/pkg/authorization/registry/clusterpolicybinding"
clusterpolicybindingetcd "github.com/openshift/origin/pkg/authorization/registry/clusterpolicybinding/etcd"
clusterrolestorage "github.com/openshift/origin/pkg/authorization/registry/clusterrole/proxy"
clusterrolebindingstorage "github.com/openshift/origin/pkg/authorization/registry/clusterrolebinding/proxy"
"github.com/openshift/origin/pkg/authorization/rulevalidation"
"github.com/openshift/origin/pkg/client"
"github.com/openshift/origin/pkg/cmd/cli/describe"
configapilatest "github.com/openshift/origin/pkg/cmd/server/api/latest"
originrest "github.com/openshift/origin/pkg/cmd/server/origin/rest"
templateapi "github.com/openshift/origin/pkg/template/api"
"github.com/openshift/origin/pkg/util/restoptions"
)
const OverwriteBootstrapPolicyCommandName = "overwrite-policy"
type OverwriteBootstrapPolicyOptions struct {
File string
MasterConfigFile string
Force bool
Out io.Writer
CreateBootstrapPolicyCommand string
}
func NewCommandOverwriteBootstrapPolicy(commandName string, fullName string, createBootstrapPolicyCommand string, out io.Writer) *cobra.Command {
options := &OverwriteBootstrapPolicyOptions{Out: out}
options.CreateBootstrapPolicyCommand = createBootstrapPolicyCommand
cmd := &cobra.Command{
Use: commandName,
Short: "Reset the policy to the default values",
Run: func(cmd *cobra.Command, args []string) {
if err := options.Validate(args); err != nil {
kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
}
if err := options.OverwriteBootstrapPolicy(); err != nil {
kcmdutil.CheckErr(err)
}
},
}
flags := cmd.Flags()
flags.BoolVarP(&options.Force, "force", "f", false, "You must confirm you really want to reset your policy. This will delete any custom settings you may have.")
flags.StringVar(&options.File, "filename", "", "The policy template file containing roles and bindings. One can be created with '"+createBootstrapPolicyCommand+"'.")
flags.StringVar(&options.MasterConfigFile, "master-config", "openshift.local.config/master/master-config.yaml", "Location of the master configuration file to run from in order to connect to etcd and directly modify the policy.")
// autocompletion hints
cmd.MarkFlagFilename("filename")
cmd.MarkFlagFilename("master-config", "yaml", "yml")
return cmd
}
func (o OverwriteBootstrapPolicyOptions) Validate(args []string) error {
if len(args) != 0 {
return errors.New("no arguments are supported")
}
if len(o.File) == 0 {
return errors.New("filename must be provided")
}
if len(o.MasterConfigFile) == 0 {
return errors.New("master-config must be provided")
}
return nil
}
func (o OverwriteBootstrapPolicyOptions) OverwriteBootstrapPolicy() error {
masterConfig, err := configapilatest.ReadAndResolveMasterConfig(o.MasterConfigFile)
if err != nil {
return err
}
// this brings in etcd server client libraries
optsGetter, err := originrest.StorageOptions(*masterConfig)
if err != nil {
return err
}
return OverwriteBootstrapPolicy(optsGetter, o.File, o.CreateBootstrapPolicyCommand, o.Force, o.Out)
}
func OverwriteBootstrapPolicy(optsGetter restoptions.Getter, policyFile, createBootstrapPolicyCommand string, change bool, out io.Writer) error {
if !change {
fmt.Fprintf(out, "Performing a dry run of policy overwrite:\n\n")
}
mapper := kapi.Registry.RESTMapper()
typer := kapi.Scheme
clientMapper := resource.ClientMapperFunc(func(mapping *meta.RESTMapping) (resource.RESTClient, error) {
return nil, nil
})
r := resource.NewBuilder(mapper, typer, clientMapper, kapi.Codecs.UniversalDecoder()).
FilenameParam(false, &resource.FilenameOptions{Recursive: false, Filenames: []string{policyFile}}).
Flatten().
Do()
if r.Err() != nil {
return r.Err()
}
policyStorage, err := policyetcd.NewREST(optsGetter)
if err != nil {
return err
}
policyRegistry := policyregistry.NewRegistry(policyStorage)
policyBindingStorage, err := policybindingetcd.NewREST(optsGetter)
if err != nil {
return err
}
policyBindingRegistry := policybindingregistry.NewRegistry(policyBindingStorage)
clusterPolicyStorage, err := clusterpolicyetcd.NewREST(optsGetter)
if err != nil {
return err
}
clusterPolicyRegistry := clusterpolicyregistry.NewRegistry(clusterPolicyStorage)
clusterPolicyBindingStorage, err := clusterpolicybindingetcd.NewREST(optsGetter)
if err != nil {
return err
}
clusterPolicyBindingRegistry := clusterpolicybindingregistry.NewRegistry(clusterPolicyBindingStorage)
ruleResolver := rulevalidation.NewDefaultRuleResolver(
policyListerNamespacer{registry: policyRegistry},
policyBindingListerNamespacer{registry: policyBindingRegistry},
&clusterpolicyregistry.ReadOnlyClusterPolicyClientShim{
ReadOnlyClusterPolicy: clusterpolicyregistry.ReadOnlyClusterPolicy{Registry: clusterPolicyRegistry},
},
&clusterpolicybindingregistry.ReadOnlyClusterPolicyBindingClientShim{
ReadOnlyClusterPolicyBinding: clusterpolicybindingregistry.ReadOnlyClusterPolicyBinding{Registry: clusterPolicyBindingRegistry},
},
)
roleStorage := rolestorage.NewVirtualStorage(policyRegistry, ruleResolver, nil, authorizationapi.Resource("role"))
roleBindingStorage := rolebindingstorage.NewVirtualStorage(policyBindingRegistry, ruleResolver, nil, authorizationapi.Resource("rolebinding"))
clusterRoleStorage := clusterrolestorage.NewClusterRoleStorage(clusterPolicyRegistry, clusterPolicyBindingRegistry, nil)
clusterRoleBindingStorage := clusterrolebindingstorage.NewClusterRoleBindingStorage(clusterPolicyRegistry, clusterPolicyBindingRegistry, nil)
return r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
template, ok := info.Object.(*templateapi.Template)
if !ok {
return errors.New("policy must be contained in a template. One can be created with '" + createBootstrapPolicyCommand + "'.")
}
runtime.DecodeList(template.Objects, kapi.Codecs.UniversalDecoder())
// For each object, we attempt the following to maximize our ability to persist the desired objects, while minimizing etcd write thrashing:
// 1. Create the object (no-ops if the object already exists)
// 2. If the object already exists, attempt to update the object (no-ops if an identical object is already persisted)
// 3. If we encounter any error updating, delete and recreate
errs := []error{}
for _, item := range template.Objects {
switch t := item.(type) {
case *authorizationapi.Role:
ctx := apirequest.WithNamespace(apirequest.NewContext(), t.Namespace)
if change {
// Attempt to create
_, err := roleStorage.CreateRoleWithEscalation(ctx, t)
// Unconditional replace if it already exists
if kapierrors.IsAlreadyExists(err) {
_, _, err = roleStorage.UpdateRoleWithEscalation(ctx, t)
}
// Delete and recreate as a last resort
if err != nil {
roleStorage.Delete(ctx, t.Name, nil)
_, err = roleStorage.CreateRoleWithEscalation(ctx, t)
}
// Gather any error
if err != nil {
errs = append(errs, err)
}
} else {
fmt.Fprintf(out, "Overwrite role %s/%s\n", t.Namespace, t.Name)
if s, err := describe.DescribeRole(t); err == nil {
fmt.Fprintf(out, "%s\n", s)
}
}
case *authorizationapi.RoleBinding:
ctx := apirequest.WithNamespace(apirequest.NewContext(), t.Namespace)
if change {
// Attempt to create
_, err := roleBindingStorage.CreateRoleBindingWithEscalation(ctx, t)
// Unconditional replace if it already exists
if kapierrors.IsAlreadyExists(err) {
_, _, err = roleBindingStorage.UpdateRoleBindingWithEscalation(ctx, t)
}
// Delete and recreate as a last resort
if err != nil {
roleBindingStorage.Delete(ctx, t.Name, nil)
_, err = roleBindingStorage.CreateRoleBindingWithEscalation(ctx, t)
}
// Gather any error
if err != nil {
errs = append(errs, err)
}
} else {
fmt.Fprintf(out, "Overwrite role binding %s/%s\n", t.Namespace, t.Name)
if s, err := describe.DescribeRoleBinding(t, nil, nil); err == nil {
fmt.Fprintf(out, "%s\n", s)
}
}
case *authorizationapi.ClusterRole:
ctx := apirequest.WithNamespace(apirequest.NewContext(), t.Namespace)
if change {
// Attempt to create
_, err := clusterRoleStorage.CreateClusterRoleWithEscalation(ctx, t)
// Unconditional replace if it already exists
if kapierrors.IsAlreadyExists(err) {
_, _, err = clusterRoleStorage.UpdateClusterRoleWithEscalation(ctx, t)
}
// Delete and recreate as a last resort
if err != nil {
clusterRoleStorage.Delete(ctx, t.Name, nil)
_, err = clusterRoleStorage.CreateClusterRoleWithEscalation(ctx, t)
}
// Gather any error
if err != nil {
errs = append(errs, err)
}
} else {
fmt.Fprintf(out, "Overwrite role %s/%s\n", t.Namespace, t.Name)
if s, err := describe.DescribeRole(authorizationapi.ToRole(t)); err == nil {
fmt.Fprintf(out, "%s\n", s)
}
}
case *authorizationapi.ClusterRoleBinding:
ctx := apirequest.WithNamespace(apirequest.NewContext(), t.Namespace)
if change {
// Attempt to create
_, err := clusterRoleBindingStorage.CreateClusterRoleBindingWithEscalation(ctx, t)
// Unconditional replace if it already exists
if kapierrors.IsAlreadyExists(err) {
_, _, err = clusterRoleBindingStorage.UpdateClusterRoleBindingWithEscalation(ctx, t)
}
// Delete and recreate as a last resort
if err != nil {
clusterRoleBindingStorage.Delete(ctx, t.Name, nil)
_, err = clusterRoleBindingStorage.CreateClusterRoleBindingWithEscalation(ctx, t)
}
// Gather any error
if err != nil {
errs = append(errs, err)
}
} else {
fmt.Fprintf(out, "Overwrite role binding %s/%s\n", t.Namespace, t.Name)
if s, err := describe.DescribeRoleBinding(authorizationapi.ToRoleBinding(t), nil, nil); err == nil {
fmt.Fprintf(out, "%s\n", s)
}
}
default:
errs = append(errs, fmt.Errorf("only roles and rolebindings may be created in this mode, not: %v", reflect.TypeOf(t)))
}
}
if !change {
fmt.Fprintf(out, "To make the changes described above, pass --force\n")
}
return kerrors.NewAggregate(errs)
})
}
type policyListerNamespacer struct {
registry policyregistry.Registry
}
func (s policyListerNamespacer) Policies(namespace string) client.PolicyLister {
return policyLister{registry: s.registry, namespace: namespace}
}
type policyLister struct {
registry policyregistry.Registry
namespace string
}
func (s policyLister) List(options metav1.ListOptions) (*authorizationapi.PolicyList, error) {
optint := metainternal.ListOptions{}
if err := metainternal.Convert_v1_ListOptions_To_internalversion_ListOptions(&options, &optint, nil); err != nil {
return nil, err
}
return s.registry.ListPolicies(apirequest.WithNamespace(apirequest.NewContext(), s.namespace), &optint)
}
func (s policyLister) Get(name string, options metav1.GetOptions) (*authorizationapi.Policy, error) {
return s.registry.GetPolicy(apirequest.WithNamespace(apirequest.NewContext(), s.namespace), name, &options)
}
type policyBindingListerNamespacer struct {
registry policybindingregistry.Registry
}
func (s policyBindingListerNamespacer) PolicyBindings(namespace string) client.PolicyBindingLister {
return policyBindingLister{registry: s.registry, namespace: namespace}
}
type policyBindingLister struct {
registry policybindingregistry.Registry
namespace string
}
func (s policyBindingLister) List(options metav1.ListOptions) (*authorizationapi.PolicyBindingList, error) {
optint := metainternal.ListOptions{}
if err := metainternal.Convert_v1_ListOptions_To_internalversion_ListOptions(&options, &optint, nil); err != nil {
return nil, err
}
return s.registry.ListPolicyBindings(apirequest.WithNamespace(apirequest.NewContext(), s.namespace), &optint)
}
func (s policyBindingLister) Get(name string, options metav1.GetOptions) (*authorizationapi.PolicyBinding, error) {
return s.registry.GetPolicyBinding(apirequest.WithNamespace(apirequest.NewContext(), s.namespace), name, &options)
}