This repository has been archived by the owner on Jun 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 308
/
kapp.go
285 lines (253 loc) · 9.77 KB
/
kapp.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
// Copyright 2021 VMware Tanzu Community Edition contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package kapp installs and manages instances of kapp-controller into Kubernetes clusters.
package kapp
import (
"context"
"fmt"
"log"
"strings"
v1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apiv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/restmapper"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
apiRegv1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1"
)
const (
deploymentKind = "Deployment"
metadataKey = "metadata"
nameKey = "name"
namespaceKey = "namespace"
kappControllerDeploymentName = "kapp-controller"
)
// Client is a client for interfacing with kapp-controller.
type Client struct {
dynClient dynamic.Interface
clientSet kubernetes.Interface
restMapper meta.RESTMapper
scheme *runtime.Scheme
}
// InstallOpts contains information about how to install kapp-controller.
type InstallOpts struct {
// MergedManifests represents the final (serialized) data for installing kapp-controller and its ancillary
// resources. This assumes all objects are merged into one byte array. Think of this like a single YAML file
// containing multiple Kubernetes resources.
// It assumes the manifest are in their final state, meaning you could kubectl apply them.
// If template rendering is required (e.g. ytt) this should be done before setting this value.
MergedManifests []byte
// Manifests represents the final (serialized) data for installing kapp-controller and its ancillary
// resources. This assumes each object is contained in its own byte array. Think of this like a many YAML files
// each containing one Kubernetes resources.
// It assumes the manifest are in their final state, meaning you could kubectl apply them.
// If template rendering is required (e.g. ytt) this should be done before setting this value.
Manifests [][]byte
}
// Manager defines the interface for performing kapp operations.
type Manager interface {
// Install installs kapp-controller into the cluster. When successful, it returns the Deployment object that
// manages the kapp-controller pod.
Install(opts InstallOpts) (*v1.Deployment, error)
// Status retrieves the pod status for kapp-controller. It expects to be passed the namespace and name for the
// kapp-controller Deployment object. If it cannot talk to the cluster, that status is reported. If the
// pod cannot be resolved, a status of not created is reported. Otherwise, the exact status message is returned.
Status(ns, name string) string
}
// New instantiates a new KappManager.
func New(kubeconfigBytes []byte) (Manager, error) {
config, err := clientcmd.BuildConfigFromKubeconfigGetter("", func() (*clientcmdapi.Config, error) {
return clientcmd.Load(kubeconfigBytes)
})
// TODO(joshrosso): figure out what to do here
if err != nil {
return nil, fmt.Errorf("could not build config using provided kubeconfig: %s", err.Error())
}
client, err := dynamic.NewForConfig(config)
// TODO(joshrosso): figure out what to do here
if err != nil {
return nil, fmt.Errorf("could not build dynamic client with config: %s", err.Error())
}
clientSet, err := kubernetes.NewForConfig(config)
// TODO(joshrosso): figure out what to do here
if err != nil {
return nil, fmt.Errorf("could not build new client set from config: %s", err.Error())
}
// setting up restMapper is an expensive operation, so do it here and re-use it
// in method invocations
groupResources, err := restmapper.GetAPIGroupResources(clientSet.Discovery())
// TODO(joshrosso): figure out what to do here
if err != nil {
return nil, fmt.Errorf("could not build restMapper: %s", err.Error())
}
rm := restmapper.NewDiscoveryRESTMapper(groupResources)
sch := runtime.NewScheme()
// ensure CRD Definitions are detected
err = apiv1.AddToScheme(sch)
// TODO(joshrosso): figure out what to do here
if err != nil {
return nil, fmt.Errorf("could not detect apiv1 CRD definitions from runtime scheme: %s", err.Error())
}
err = v1.AddToScheme(sch)
// TODO(joshrosso): figure out what to do here
if err != nil {
return nil, fmt.Errorf("could not detect v1 CRD definitions from runtime scheme: %s", err.Error())
}
err = corev1.AddToScheme(sch)
// TODO(joshrosso): figure out what to do here
if err != nil {
return nil, fmt.Errorf("could not detect corev1 CRD definitions from runtime scheme: %s", err.Error())
}
err = rbacv1.AddToScheme(sch)
// TODO(joshrosso): figure out what to do here
if err != nil {
return nil, fmt.Errorf("could not detect rbacv1 CRD definitions from runtime scheme: %s", err.Error())
}
err = apiRegv1.AddToScheme(sch)
// TODO(joshrosso): figure out what to do here
if err != nil {
return nil, fmt.Errorf("could not detect apiRegv1 CRD definitions from runtime scheme: %s", err.Error())
}
return Client{
dynClient: client,
clientSet: clientSet,
restMapper: rm,
scheme: sch,
}, nil
}
// Install performs and installation.
func (k Client) Install(opts InstallOpts) (*v1.Deployment, error) {
if opts.MergedManifests == nil && opts.Manifests == nil {
return nil, fmt.Errorf("no objects were provided to install")
}
var objects []runtime.Object
if opts.MergedManifests != nil {
objects = parseMergedObjects(k.scheme, opts.MergedManifests)
} else {
objects = createObjectList(k.scheme, opts.Manifests)
}
var kappDeployment v1.Deployment
for _, obj := range objects {
createdObj, err := applyObject(k, obj)
if err != nil {
return nil, err
}
// determine if the returned object is kapp-controller, if so plan to return it
// TODO(joshrosso): Really ugly embedded ifs, we should make this better
if createdObj.GetObjectKind().GroupVersionKind().Kind == deploymentKind {
if createdObj.Object[metadataKey].(map[string]interface{})[nameKey] != nil {
if createdObj.Object[metadataKey].(map[string]interface{})[nameKey].(string) == kappControllerDeploymentName {
err = runtime.DefaultUnstructuredConverter.FromUnstructured(createdObj.Object, &kappDeployment)
if err != nil {
return nil, err
}
}
}
}
}
return &kappDeployment, nil
}
// Status gets the status of a package.
func (k Client) Status(ns, name string) string {
pods, err := k.clientSet.CoreV1().Pods(ns).List(context.TODO(), metav1.ListOptions{})
if err != nil {
return "failed to talk to cluster"
}
var kappPod *corev1.Pod
// super bad, should not be iterating through pods on every invocation
for i := range pods.Items {
// pod name will always prefix with deployment name
pod := pods.Items[i]
if strings.HasPrefix(pod.Name, name) {
kappPod = &pod
}
}
if kappPod == nil {
return "Not created"
}
return string(kappPod.Status.Phase)
}
// applyObject takes a runtime.Object and converts it into an unstructured object. It then
// uses the dynamic client to apply the object to the cluster. If the namespace field is nil,
// it applies the object cluster wide, if it contains a string, it applies it in the
// appropriate namespace.
func applyObject(k Client, obj runtime.Object) (*unstructured.Unstructured, error) {
gvk := obj.GetObjectKind().GroupVersionKind()
gk := schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind}
uObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
if err != nil {
return nil, err
}
objectBody := &unstructured.Unstructured{Object: uObj}
mapping, _ := k.restMapper.RESTMapping(gk, gvk.Version)
nsInterface := uObj[metadataKey].(map[string]interface{})[namespaceKey]
var createObj *unstructured.Unstructured
if nsInterface != nil {
ns := nsInterface.(string)
createObj, err = k.dynClient.
Resource(schema.GroupVersionResource{
Group: gvk.Group,
Version: gvk.Version,
Resource: mapping.Resource.Resource,
}).Namespace(ns).
Create(context.TODO(), objectBody, metav1.CreateOptions{})
if err != nil {
return nil, err
}
} else {
createObj, err = k.dynClient.
Resource(schema.GroupVersionResource{
Group: gvk.Group,
Version: gvk.Version,
Resource: mapping.Resource.Resource,
}).
Create(context.TODO(), objectBody, metav1.CreateOptions{})
if err != nil {
return nil, err
}
}
return createObj, nil
}
// parseMergedObjects takes multiple YAML objects, separated by '---' and returns a list of runtime objects.
func parseMergedObjects(sch *runtime.Scheme, fileR []byte) []runtime.Object {
fileAsString := string(fileR)
sepYamlfiles := strings.Split(fileAsString, "---")
retVal := make([]runtime.Object, 0, len(sepYamlfiles))
for _, f := range sepYamlfiles {
if f == "\n" || f == "" {
// ignore empty cases
continue
}
decode := serializer.NewCodecFactory(sch).UniversalDeserializer().Decode
obj, _, err := decode([]byte(f), nil, nil)
if err != nil {
log.Println(fmt.Sprintf("Error while decoding YAML object. Err was: %s", err))
continue
}
retVal = append(retVal, obj)
}
return retVal
}
// createObjectList returns a list of runtime objects based on objects living in a list of byte arrays
func createObjectList(sch *runtime.Scheme, objects [][]byte) []runtime.Object {
retVal := make([]runtime.Object, 0, len(objects))
for _, o := range objects {
decode := serializer.NewCodecFactory(sch).UniversalDeserializer().Decode
obj, _, err := decode(o, nil, nil)
if err != nil {
log.Println(fmt.Sprintf("Error while decoding YAML object. Err was: %s", err))
continue
}
retVal = append(retVal, obj)
}
return retVal
}