Debian Codegraph @

pkg/apis/apiserver/load/load.go

raw
1 /*
2 Copyright 2023 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package load
18
19 import (
20 "fmt"
21 "io"
22 "os"
23
24 "k8s.io/apimachinery/pkg/runtime"
25 "k8s.io/apimachinery/pkg/runtime/serializer"
26 api "k8s.io/apiserver/pkg/apis/apiserver"
27 "k8s.io/apiserver/pkg/apis/apiserver/install"
28 externalapi "k8s.io/apiserver/pkg/apis/apiserver/v1alpha1"
29 )
30
31 var (
32 scheme = runtime.NewScheme()
33 codecs = serializer.NewCodecFactory(scheme, serializer.EnableStrict)
34 )
35
36 func init() {
37 install.Install(scheme)
38 }
39
40 func LoadFromFile(file string) (*api.AuthorizationConfiguration, error) {
41 data, err := os.ReadFile(file)
42 if err != nil {
43 return nil, err
44 }
45 return LoadFromData(data)
46 }
47
48 func LoadFromReader(reader io.Reader) (*api.AuthorizationConfiguration, error) {
49 if reader == nil {
50 // no reader specified, use default config
51 return LoadFromData(nil)
52 }
53
54 data, err := io.ReadAll(reader)
55 if err != nil {
56 return nil, err
57 }
58 return LoadFromData(data)
59 }
60
61 func LoadFromData(data []byte) (*api.AuthorizationConfiguration, error) {
62 if len(data) == 0 {
63 // no config provided, return default
64 externalConfig := &externalapi.AuthorizationConfiguration{}
65 scheme.Default(externalConfig)
66 internalConfig := &api.AuthorizationConfiguration{}
67 if err := scheme.Convert(externalConfig, internalConfig, nil); err != nil {
68 return nil, err
69 }
70 return internalConfig, nil
71 }
72
73 decodedObj, err := runtime.Decode(codecs.UniversalDecoder(), data)
74 if err != nil {
75 return nil, err
76 }
77 configuration, ok := decodedObj.(*api.AuthorizationConfiguration)
78 if !ok {
79 return nil, fmt.Errorf("expected AuthorizationConfiguration, got %T", decodedObj)
80 }
81 return configuration, nil
82 }