-
Notifications
You must be signed in to change notification settings - Fork 0
/
annotate.go
320 lines (306 loc) · 11.9 KB
/
annotate.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
package annotate
import (
"context"
"encoding/json"
"github.com/logzio/easy-connect-server/api"
"go.uber.org/zap"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/dynamic/dynamicinformer"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"net/http"
"strings"
"time"
)
const (
LogTypeAnnotation = "logz.io/application_type"
InstrumentationAnnotation = "logz.io/traces_instrument"
ServiceNameAnnotation = "logz.io/service-name"
)
// ResourceAnnotateRequest is the JSON body of the POST request
// It contains the name, controller_kind, namespace, and log type of the resource
// name: name of the resource
// controller_kind: kind of the resource (deployment or statefulset)
// namespace: namespace of the resource
// log_type: desired log type
// container_name: name of the container associated with the request
// service_name: the desired service name for the application, should delete instrumentation if this filed is empty
type ResourceAnnotateRequest struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
ControllerKind string `json:"controller_kind"`
LogType string `json:"log_type,omitempty"`
ContainerName string `json:"container_name"`
ServiceName string `json:"service_name,omitempty"`
}
// ResourceAnnotateResponse is the data structure for the custom resource
// the response will contain a list of these fields
// name: the name of the custom resource
// namespace: the namespace of the custom resource
// controller_kind: the kind of the controller that created the custom resource
// log_type: the log type of the application that the container belongs to
// service_name: the updated service name
type ResourceAnnotateResponse struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
ControllerKind string `json:"controller_kind"`
ServiceName *string `json:"service_name"`
ContainerName string `json:"container_name"`
LogType *string `json:"log_type"`
}
func UpdateResourceAnnotations(w http.ResponseWriter, r *http.Request) {
logger := api.InitLogger()
// Decode JSON body
var resource ResourceAnnotateRequest
err := json.NewDecoder(r.Body).Decode(&resource)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Get the Kubernetes config
config, err := api.GetConfig()
if err != nil {
logger.Error(api.ErrorKubeConfig, err)
http.Error(w, api.ErrorKubeConfig, http.StatusInternalServerError)
return
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Create a dynamic client
dynamicClient, err := dynamic.NewForConfig(config)
if err != nil {
logger.Error(api.ErrorDynamic, zap.Error(err))
http.Error(w, api.ErrorDynamic+err.Error(), http.StatusInternalServerError)
return
}
// instrumented application crd scheme
gvr := schema.GroupVersionResource{
Group: api.ResourceGroup,
Version: api.ResourceVersion,
Resource: api.ResourceInstrumentedApplication,
}
// Validate input before updating resources to avoid changing resources and retuning an error
if !isValidResourceAnnotateRequest(resource) {
logger.Error(api.ErrorInvalidInput)
http.Error(w, api.ErrorInvalidInput, http.StatusBadRequest)
return
}
// Define timeout for the context
ctxDuration, err := api.GetTimeout()
if err != nil {
logger.Error(api.ErrorInvalidInput, err)
http.Error(w, api.ErrorInvalidInput+err.Error(), http.StatusInternalServerError)
return
}
ctx, cancel := context.WithTimeout(context.Background(), ctxDuration)
defer cancel()
customResourceObj, err := dynamicClient.Resource(gvr).Namespace(resource.Namespace).Get(ctx, resource.Name, v1.GetOptions{})
if err != nil {
logger.Error(api.ErrorGet, zap.Error(err))
http.Error(w, api.ErrorGet+err.Error(), http.StatusInternalServerError)
return
}
// Calculate how many crd changes are expected due to the current operations
expectedChanges := calculateExpectedCrdChanges(resource, customResourceObj)
logger.Infof("Expected numbers of changes for %s resource: %d", resource.Name, expectedChanges)
// get
isInstrumentble := isInstrumentable(customResourceObj)
// Create a channel to signal about workload and crd updates
specCh := make(chan struct{})
statusCh := make(chan struct{})
// Create a dynamic factory that watches for changes in the InstrumentedApplication CRD corresponding to the request resource
dynamicFactory := dynamicinformer.NewFilteredDynamicSharedInformerFactory(dynamicClient, 1*time.Second, resource.Namespace, func(options *v1.ListOptions) {
options.FieldSelector = "metadata.name=" + resource.Name
})
crdInformer := dynamicFactory.ForResource(gvr)
// watch for crd status changes to indicate about instrumentation status change (instrument, rollback) and spec changes to indicate about log type changes
crdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
UpdateFunc: func(oldObj, newObj interface{}) {
n := newObj.(*unstructured.Unstructured)
o := oldObj.(*unstructured.Unstructured)
newSpec := n.Object["spec"].(map[string]interface{})
oldSpec := o.Object["spec"].(map[string]interface{})
newStatus := n.Object["status"].(map[string]interface{})
oldStatus := o.Object["status"].(map[string]interface{})
// spec changes to indicate about log type changes and service name changes
if !api.DeepEqualMap(oldSpec, newSpec) {
specCh <- struct{}{} // Signal that the update occurred
}
// status changes to indicate about instrumentation status change
if !api.DeepEqualMap(oldStatus, newStatus) {
statusCh <- struct{}{}
}
},
})
// start watching for changes in crd
dynamicFactory.Start(ctx.Done())
// Create the response
response := ResourceAnnotateResponse{
Name: resource.Name,
Namespace: resource.Namespace,
ControllerKind: resource.ControllerKind,
LogType: &resource.LogType,
ServiceName: &resource.ServiceName,
}
response.ContainerName = resource.ContainerName
// choose the instrumentation annotation value and value according to the service name
actionValue := "true"
if resource.ServiceName == "" {
actionValue = "rollback"
}
// Update workload and custom resources
switch resource.ControllerKind {
case api.KindDeployment:
err = handleUpdateDeployment(ctx, resource, clientset, logger, actionValue, isInstrumentble)
if err != nil {
logger.Error(api.ErrorUpdate, err)
http.Error(w, api.ErrorUpdate+err.Error(), http.StatusInternalServerError)
}
case api.KindStatefulSet:
err = handleUpdateStatefulset(ctx, resource, clientset, logger, actionValue, isInstrumentble)
if err != nil {
logger.Error(api.ErrorUpdate, err)
http.Error(w, api.ErrorUpdate+err.Error(), http.StatusInternalServerError)
}
}
// Wait for the expected numbers of updates to occur or timeout
for changeNum := 0; changeNum < expectedChanges; changeNum++ {
select {
case <-statusCh:
logger.Info("crd status changed: ", resource.Name)
case <-specCh:
logger.Info("crd spec changed: ", resource.Name)
case <-ctx.Done():
logger.Error(api.ErrorTimeout + resource.Name)
http.Error(w, api.ErrorTimeout+resource.Name, http.StatusInternalServerError)
return
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(response)
}
func isValidResourceAnnotateRequest(req ResourceAnnotateRequest) bool {
for _, validKind := range api.ValidKinds {
if req.ControllerKind == strings.ToLower(validKind) {
return true
}
}
return false
}
// isInstrumentable checks if the resource is instrumentable
func isInstrumentable(customResourceObj *unstructured.Unstructured) bool {
if customResourceObj.Object["spec"].(map[string]interface{})["languages"] == nil {
return false
}
return true
}
// handleUpdateDeployment handles update of deployment
func handleUpdateDeployment(ctx context.Context, resource ResourceAnnotateRequest, clientset kubernetes.Interface, logger zap.SugaredLogger, actionValue string, isInstrumentble bool) error {
logger.Info("Updating deployment: ", resource.Name)
deployment, err := clientset.AppsV1().Deployments(resource.Namespace).Get(ctx, resource.Name, v1.GetOptions{})
if err != nil {
logger.Error(api.ErrorGet, err)
return err
}
// handle log type
if deployment.Spec.Template.ObjectMeta.Annotations == nil {
deployment.Spec.Template.ObjectMeta.Annotations = make(map[string]string)
}
if len(resource.LogType) != 0 {
deployment.Spec.Template.ObjectMeta.Annotations[LogTypeAnnotation] = resource.LogType
} else {
delete(deployment.Spec.Template.ObjectMeta.Annotations, LogTypeAnnotation)
}
if isInstrumentble {
// handle traces instrumentation annotations
// logz.io/instrument
deployment.Spec.Template.ObjectMeta.Annotations[InstrumentationAnnotation] = actionValue
// service name
if len(resource.ServiceName) != 0 {
deployment.Spec.Template.ObjectMeta.Annotations[ServiceNameAnnotation] = resource.ServiceName
} else {
delete(deployment.Spec.Template.ObjectMeta.Annotations, ServiceNameAnnotation)
}
}
_, err = clientset.AppsV1().Deployments(resource.Namespace).Update(ctx, deployment, v1.UpdateOptions{})
if err != nil {
logger.Error(api.ErrorUpdate, err)
return err
}
return nil
}
// handleUpdateStatefulset handles update of statefulset
func handleUpdateStatefulset(ctx context.Context, resource ResourceAnnotateRequest, clientset kubernetes.Interface, logger zap.SugaredLogger, actionValue string, isInstrumentble bool) error {
logger.Info("Updating statefulset: ", resource.Name)
statefulSet, err := clientset.AppsV1().StatefulSets(resource.Namespace).Get(ctx, resource.Name, v1.GetOptions{})
if err != nil {
logger.Error(api.ErrorGet, err)
return err
}
if statefulSet.Spec.Template.ObjectMeta.Annotations == nil {
statefulSet.Spec.Template.ObjectMeta.Annotations = make(map[string]string)
}
// handle logs
if len(resource.LogType) != 0 {
statefulSet.Spec.Template.ObjectMeta.Annotations[LogTypeAnnotation] = resource.LogType
} else {
delete(statefulSet.Spec.Template.ObjectMeta.Annotations, LogTypeAnnotation)
}
if isInstrumentble {
// handle traces instrumentation annotations
// logz.io/instrument
statefulSet.Spec.Template.ObjectMeta.Annotations[InstrumentationAnnotation] = actionValue
// service name
if len(resource.ServiceName) != 0 {
statefulSet.Spec.Template.ObjectMeta.Annotations[ServiceNameAnnotation] = resource.ServiceName
} else {
delete(statefulSet.Spec.Template.ObjectMeta.Annotations, ServiceNameAnnotation)
}
}
_, err = clientset.AppsV1().StatefulSets(resource.Namespace).Update(ctx, statefulSet, v1.UpdateOptions{})
if err != nil {
logger.Error(api.ErrorUpdate, err)
return err
}
return nil
}
// calculateExpectedCrdChanges compares log type and service name of the current request and the existing crd, and return the number of expected crd changes
func calculateExpectedCrdChanges(resource ResourceAnnotateRequest, crd *unstructured.Unstructured) int {
expected := 0
// getting the data
spec := crd.Object["spec"].(map[string]interface{})
activeLogType := spec["logType"].(string)
activeServiceName := ""
if spec["languages"] != nil {
services := spec["languages"].([]interface{})
for _, service := range services {
if service.(map[string]interface{})["containerName"].(string) == resource.ContainerName {
activeServiceName = service.(map[string]interface{})["activeServiceName"].(string)
}
}
}
// comparison
if activeLogType != resource.LogType {
expected++
}
// update
if activeServiceName != resource.ServiceName {
expected++
}
// if create operation we are also expecting a status change
if activeServiceName == "" && resource.ServiceName != "" {
expected++
}
// if delete operation we are also expecting a status change
if resource.ServiceName == "" && activeServiceName != "" {
expected++
}
return expected
}