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
|
package k8s
import (
"bytes"
"context"
"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/module/modagent"
"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/logz"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/kubernetes"
"k8s.io/kubectl/pkg/cmd/util"
"sigs.k8s.io/cli-utils/pkg/apply"
"sigs.k8s.io/cli-utils/pkg/apply/event"
"sigs.k8s.io/cli-utils/pkg/common"
"sigs.k8s.io/cli-utils/pkg/inventory"
"sigs.k8s.io/cli-utils/pkg/kstatus/watcher"
"sigs.k8s.io/cli-utils/pkg/object/validation"
)
type K8sClient struct {
log *zap.Logger
clientset kubernetes.Interface
applier *apply.Applier
factory util.Factory
}
func New(log *zap.Logger, factory util.Factory) (*K8sClient, error) {
clientset, err := factory.KubernetesClientSet()
if err != nil {
return nil, err
}
invClient, err := inventory.ClusterClientFactory{
StatusPolicy: inventory.StatusPolicyNone,
}.NewClient(factory)
if err != nil {
return nil, err
}
applier, err := apply.NewApplierBuilder().
WithFactory(factory).
WithInventoryClient(invClient).
Build()
if err != nil {
return nil, err
}
return &K8sClient{
log: log,
clientset: clientset,
applier: applier,
factory: factory,
}, nil
}
func (k *K8sClient) NamespaceExists(ctx context.Context, name string) bool {
client := k.clientset.CoreV1().Namespaces()
_, err := client.Get(ctx, name, metav1.GetOptions{})
return err == nil
}
func (k *K8sClient) CreateNamespace(ctx context.Context, name string) error {
client := k.clientset.CoreV1().Namespaces()
nsSpec := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
}
_, err := client.Create(ctx, nsSpec, metav1.CreateOptions{})
return err
}
func (k *K8sClient) DeleteNamespace(ctx context.Context, name string) error {
client := k.clientset.CoreV1().Namespaces()
return client.Delete(ctx, name, metav1.DeleteOptions{})
}
func (k *K8sClient) Apply(ctx context.Context, namespace string, config string) error {
objs, err := k.decode([]byte(config))
if err != nil {
return err
}
invObj, objs := k.splitObjects(namespace, objs)
// process work - apply to cluster
k.log.Debug("Applying work to cluster")
applierOptions := apply.ApplierOptions{
ServerSideOptions: common.ServerSideOptions{
ServerSideApply: true,
ForceConflicts: true,
FieldManager: modagent.FieldManager,
},
ReconcileTimeout: 0,
EmitStatusEvents: true,
PruneTimeout: 0,
ValidationPolicy: validation.ExitEarly,
WatcherRESTScopeStrategy: watcher.RESTScopeNamespace,
}
events := k.applier.Run(ctx, inventory.WrapInventoryInfoObj(invObj), objs, applierOptions)
k.log.Debug("Applied work to cluster")
// We listen on the events channel in goroutine
// not to block this function's execution
go func() {
// TODO: Add logging as a part of processing the events above
// issue: https://gitlab.com/gitlab-org/gitlab/-/issues/397001
for e := range events {
k.log.Debug("Applied event", applyEvent(e))
}
}()
return nil
}
func (k *K8sClient) decode(data []byte) ([]*unstructured.Unstructured, error) {
// 1. parse in local mode to retrieve objects.
builder := resource.NewBuilder(k.factory).
ContinueOnError().
Flatten().
Unstructured().
Local()
builder.Stream(bytes.NewReader(data), "main")
result := builder.Do()
var objs []*unstructured.Unstructured
err := result.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
objs = append(objs, info.Object.(*unstructured.Unstructured))
return nil
})
if err != nil {
return nil, err
}
return objs, nil
}
func (k *K8sClient) splitObjects(namespace string, objs []*unstructured.Unstructured) (*unstructured.Unstructured, []*unstructured.Unstructured) {
inventoryObjects := make([]*unstructured.Unstructured, 0, 1)
resources := make([]*unstructured.Unstructured, 0, len(objs))
for _, obj := range objs {
if inventory.IsInventoryObject(obj) {
inventoryObjects = append(inventoryObjects, obj)
} else {
resources = append(resources, obj)
}
}
if len(inventoryObjects) == 0 {
return k.defaultInventoryObjTemplate(namespace), resources
}
return inventoryObjects[0], resources
}
func (k *K8sClient) defaultInventoryObjTemplate(namespace string) *unstructured.Unstructured {
return &unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": "v1",
"kind": "ConfigMap",
"metadata": map[string]interface{}{
"name": "remote-dev-inventory",
"namespace": namespace,
"labels": map[string]interface{}{
common.InventoryLabel: "remote_development",
},
},
},
}
}
func applyEvent(event event.Event) zap.Field {
return zap.Inline(zapcore.ObjectMarshalerFunc(func(encoder zapcore.ObjectEncoder) error {
encoder.AddString(logz.ApplyEvent, event.String())
return nil
}))
}
|