summaryrefslogtreecommitdiffstats
path: root/mock-clamp/loop_handlers.go
blob: ff8a55204150468b2cca2bc75f3f66c333b501d4 (plain)
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
// Copyright 2023 Deutsche Telekom AG, Orange
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"net/http"
	"time"

	"github.com/labstack/echo"
	uuid "github.com/satori/go.uuid"
)

//describes the loop state in term of policy and DCAE
type State struct {
	ComponentState struct {
		StateName string `json:"stateName"`
	} `json:"componentState"`
}

//describes entity id in CLAMP got from SDC
type Resource struct {
	ResourceID struct {
		VfModuleModelName              string `json:"vfModuleModelName"`
		VfModuleModelInvariantUUID     string `json:"vfModuleModelInvariantUUID"`
		VfModuleModelUUID              string `json:"vfModuleModelUUID"`
		VfModuleModelVersion           string `json:"vfModuleModelVersion"`
		VfModuleModelCustomizationUUID string `json:"vfModuleModelCustomizationUUID"`
	} `json:"resourceID"`
}

//frequency limiter configuration
type Frequency_payload struct {
	ID         string `json:"id"`
	Actor      string `json:"actor"`
	Operation  string `json:"operation"`
	Limit      int    `json:"limit"`
	TimeWindow int    `json:"timeWindow"`
	TimeUnits  string `json:"timeUnits"`
}

/*
//describes operational policy configuration in CLAMP
type OperationalPolicy struct {
	Name               string                      `json:"name"`
	PolicyModel        Policy                      `json:"policyModel"`
	ConfigurationsJson struct{ Frequency_payload } `json:"configurationsJson"` //depends on operational policy model
}
*/
//describes TCA POLICY in CLAMP
type Tca_policy struct {
	Domain              string `json:"Domain"`
	MetricsPerEventName []struct {
		PolicyScope string `json:"policyScope"`
		Thresholds  []struct {
			Version               string `json:"version"`
			Severity              string `json:"severity"`
			ThresholdValue        int    `json:"thresholdValue"`
			ClosedLoopEventStatus string `json:"closedLoopEventStatus"`
			ClosedLoopControlName string `json:"closedLoopControlName"`
			Direction             string `json:"direction"`
			FieldPath             string `json:"fieldPath"`
		} `json:"thresholds"`
		EventName             string `json:"eventName"`
		PolicyVersion         string `json:"policyVersion"`
		ControlLoopSchemaType string `json:"controlLoopSchemaType"`
		PolicyName            string `json:"policyName"`
	} `json:"metricsPerEventName"`
}

//describes TCA POLICY payload in CLAMP
type Tca_policy_struct struct {
	TcaPolicy Tca_policy `json:"tca.policy"`
}

//describes microservice policy configuration in CLAMP
type MicroServicePolicy struct {
	Name               string            `json:"name"`
	ConfigurationsJson Tca_policy_struct `json:"configurationsJson"`
	PdpGroup           string            `json:"pdpGroup"`
	PdpSubgroup        string            `json:"pdpSubgroup"`
}

//LoopDetails describes loop innstance in CLAMP
type LoopDetails struct {
	Name                 string       `json:"name"`
	Template             LoopTemplate `json:"loopTemplate"`
	GlobalPropertiesJSON struct {
		DcaeDeployParameters struct {
			UniqueBlueprintParameters struct {
				PolicyID string `json:"policy_id"`
			} `json:"uniqueBlueprintParameters"`
		} `json:"dcaeDeployParameters"`
	} `json:"globalPropertiesJson"`
	LoopElementModelsUsed []string `json:"loopElementModelsUsed"` //microservices from sdc
	Components            struct {
		POLICY State `json:"POLICY"`
		DCAE   State `json:"DCAE"`
	} `json:"components"`
	ModelService struct {
		ResourceDetails struct {
			VFModule Resource `json:"VFModule"`
		} `json:"resourceDetails"`
	} `json:"modelService"`
	OperationalPolicies  []OperationalPolicy_payload `json:"operationalPolicies"`
	MicroServicePolicies []MicroServicePolicy        `json:"microServicePolicies"`
}

var loopInstanceList []LoopDetails

func generateInitialLoopInstances() {
	loopInstanceList = nil
	loop1 := new(LoopDetails)
	loop1.Template = templateList[0]
	loop1.Name = "intance_template01"
	loopInstanceList = append(loopInstanceList, *loop1)
	loop2 := new(LoopDetails)
	loop2.Name = "intance_template02"
	loop2.Template = templateList[1]
	loopInstanceList = append(loopInstanceList, *loop2)
}

func updateLoopDetails(c echo.Context) error {
	loopID := c.Param("loopID")
	for _, loop := range loopInstanceList {
		if loop.Name == loopID {
			return c.JSON(http.StatusOK, loop)
		}
	}
	return c.JSON(http.StatusNotFound, ClampError{
		Message: "No ClosedLoop found",
		Error:   "Not Found",
		Status:  "404"})
}

func createLoopInstance(c echo.Context) error {
	loopID := c.Param("loopID")
	templateName := c.QueryParam("templateName")
	loop := new(LoopDetails)

	//must add the constraint of limit number of instances for a template
	for _, l := range loopInstanceList {
		if l.Name == loopID &&
			l.Template.Name == templateName {
			//in reality it's overwritten
			return c.JSON(http.StatusBadRequest, ClampError{
				Message: "loop of same Name and for same template exists",
				Error:   "Exists",
				Status:  "500"})
		}
	}
	loop.Name = loopID
	loop.Template.Name = templateName
	//For drools configuration
	resource := new(Resource)
	resource.ResourceID.VfModuleModelUUID = uuid.NewV4().String()
	resource.ResourceID.VfModuleModelName = uuid.NewV4().String()
	resource.ResourceID.VfModuleModelInvariantUUID = uuid.NewV4().String()
	resource.ResourceID.VfModuleModelVersion = uuid.NewV4().String()
	resource.ResourceID.VfModuleModelCustomizationUUID = uuid.NewV4().String()
	loop.ModelService.ResourceDetails.VFModule = *resource
	//must generate as much microservices as tca blueprints count
	loop.LoopElementModelsUsed = append(loop.LoopElementModelsUsed, "microservice01")
	nb_microservices := len(loop.LoopElementModelsUsed)
	for i := 0; i < nb_microservices; i++ {
		loop.MicroServicePolicies = append(loop.MicroServicePolicies, MicroServicePolicy{
			Name: "Microservice" + uuid.NewV4().String(),
		})
	}
	loop.GlobalPropertiesJSON.DcaeDeployParameters.UniqueBlueprintParameters.PolicyID = "Microservice" + uuid.NewV4().String()
	state := new(State)
	state.ComponentState.StateName = "NOT_SENT"
	loop.Components.POLICY = *state
	state.ComponentState.StateName = "BLUEPRINT_DEPLOYED"
	loop.Components.DCAE = *state

	loopInstanceList = append(loopInstanceList, *loop)
	return c.JSON(http.StatusCreated, *loop)
}

func addOperationaPolicy(c echo.Context) error {
	loopID := c.Param("loopID")
	policyType := c.Param("policyType")
	policyVersion := c.Param("policyVersion")
	op_policy := new(struct {
		PolicyModelType string `json:"policyModelType"`
		Version         string `json:"version"`
		PolicyAcronym   string `json:"policyAcronym"`
		PolicyPdpGroup  struct {
			SupportedPdpGroups []struct {
				DefaultGroup []string `json:"defaultGroup"`
			} `json:"supportedPdpGroups"`
		} `json:"policyPdpGroup"`
		CreatedDate time.Time `json:"createdDate"`
		UpdatedDate time.Time `json:"updatedDate"`
		UpdatedBy   string    `json:"updatedBy"`
		CreatedBy   string    `json:"createdBy"`
	})
	for _, p := range policyList {
		if p.PolicyModelType == policyType &&
			p.Version == policyVersion {
			for j, l := range loopInstanceList {
				if l.Name == loopID {
					op_policy.PolicyAcronym = p.PolicyAcronym
					loopInstanceList[j].OperationalPolicies = append(loopInstanceList[j].OperationalPolicies,
						OperationalPolicy_payload{
							Name:        "OPERATIONAL" + uuid.NewV4().String(),
							PolicyModel: *op_policy,
						})
					return c.JSON(http.StatusOK, loopInstanceList[j])
				}
			}
			return c.JSON(http.StatusBadRequest, ClampError{
				Message: "loop not found",
				Error:   "Not Found",
				Status:  "404"})
		}
	}
	return c.JSON(http.StatusBadRequest, ClampError{
		Message: "Policy not found",
		Error:   "Not Found",
		Status:  "404"})
}

//remove operation is not working in the real CLAMP
func removeOperationaPolicy(c echo.Context) error {
	loopID := c.Param("loopID")
	policyType := c.Param("policyType")
	policyVersion := c.Param("policyVersion")

	for j, l := range loopInstanceList {
		if l.Name == loopID {
			for i, pp := range l.OperationalPolicies {
				if pp.PolicyModel.PolicyModelType == policyType &&
					pp.PolicyModel.Version == policyVersion {
					loopInstanceList[j].OperationalPolicies = append(loopInstanceList[j].OperationalPolicies[:i],
						loopInstanceList[j].OperationalPolicies[i+1:]...)
					return c.JSON(http.StatusOK, l)
				}
			}
			return c.JSON(http.StatusBadRequest, ClampError{
				Message: "Policy not found",
				Error:   "Not Found",
				Status:  "404"})
		}
	}
	return c.JSON(http.StatusBadRequest, ClampError{
		Message: "loop not found",
		Error:   "Not Found",
		Status:  "404"})
}

//must review tca_policy struct
func addTcaConfig(c echo.Context) error {
	loopID := c.Param("loopID")
	data := new(MicroServicePolicy)
	if err := c.Bind(data); err != nil {
		return err
	}
	for j, l := range loopInstanceList {
		if l.Name == loopID {
			if l.MicroServicePolicies != nil {
				for i, _ := range l.MicroServicePolicies {
					loopInstanceList[j].MicroServicePolicies[i] = *data
				}
				return c.JSON(http.StatusOK, loopInstanceList[j].MicroServicePolicies[0])
			}
			return c.JSON(http.StatusBadRequest, ClampError{
				Message: "Microservice policy not found",
				Error:   "Not Found",
				Status:  "404"})
		}
	}
	return c.JSON(http.StatusBadRequest, ClampError{
		Message: "Loop not found",
		Error:   "Not Found",
		Status:  "404"})
}

func addOperationalPolicyConfig(c echo.Context) error {
	loopID := c.Param("loopID")
	for j, l := range loopInstanceList {
		if l.Name == loopID {
			/*
				//cannot bind a list as said in labstack echo bind
				data := new([]OperationalPolicy_payload)
				if err := c.Bind(data); err != nil {
					return err
				}
			*/
			if l.OperationalPolicies != nil {
				//loopInstanceList[j].OperationalPolicies = *data
				loopInstanceList[j].OperationalPolicies[len(l.OperationalPolicies)-1].ConfigurationsJSON.Actor = "Test"
				return c.JSON(http.StatusOK, loopInstanceList[j])
			}
			return c.JSON(http.StatusBadRequest, ClampError{
				Message: "Operational Policy not found",
				Error:   "Not Found",
				Status:  "404"})
		}
	}
	return c.JSON(http.StatusBadRequest, ClampError{
		Message: "Loop not found",
		Error:   "Not Found",
		Status:  "404"})
}

//util function
func checkPoliciesConfiguration(l LoopDetails) bool {
	var empty struct {
		Actor      string `json:"actor"`
		Operation  string `json:"operation"`
		Limit      int    `json:"limit"`
		TimeWindow int    `json:"timeWindow"`
		TimeUnits  string `json:"timeUnits"`
	}

	for i, _ := range l.MicroServicePolicies {
		if l.MicroServicePolicies[i].ConfigurationsJson.TcaPolicy.Domain == "" {
			return false
		}
	}
	for i, _ := range l.OperationalPolicies {
		if l.OperationalPolicies[i].ConfigurationsJSON == empty {
			return false
		}
	}
	return true
}

func putLoopAction(c echo.Context) error {
	action := c.Param("action")
	loopID := c.Param("loopID")
	state := new(State)
	for j, l := range loopInstanceList {
		if l.Name == loopID {
			//POLICY actions
			if action == "submit" {
				if checkPoliciesConfiguration(loopInstanceList[j]) {
					state.ComponentState.StateName = "SENT_AND_DEPLOYED"
					loopInstanceList[j].Components.POLICY = *state
					return c.JSON(http.StatusOK, loopInstanceList[j].Components.POLICY.ComponentState)
				}
				return c.JSON(http.StatusBadRequest, ClampError{
					Message: "Policies are not well Configured",
					Error:   "Bad Action",
					Status:  "401"})
			}
			if action == "stop" {
				if l.Components.POLICY.ComponentState.StateName == "NOT_SENT" {
					return c.JSON(http.StatusBadRequest, ClampError{
						Message: "Cannot perform this action",
						Error:   "Bad Action",
						Status:  "400"})
				}
				state.ComponentState.StateName = "SENT"
				loopInstanceList[j].Components.POLICY = *state
				return c.JSON(http.StatusOK, "{}")
			}
			if action == "restart" {
				state.ComponentState.StateName = "SENT_AND_DEPLOYED"
				loopInstanceList[j].Components.POLICY = *state
				return c.JSON(http.StatusOK, "{}")
			}
			//DCAE actions
			if action == "deploy" {
				//must add deploy failure
				state.ComponentState.StateName = "MICROSERVICE_INSTALLED_SUCCESSFULLY"
				loopInstanceList[j].Components.DCAE = *state
				return c.JSON(http.StatusOK, "{}")
			}
			if action == "undeploy" {
				state.ComponentState.StateName = "MICROSERVICE_UNINSTALLED_SUCCESSFULLY"
				loopInstanceList[j].Components.DCAE = *state
				return c.JSON(http.StatusOK, "{}")
			}
			//LOOP action
			if action == "delete" {
				loopInstanceList = append(loopInstanceList[:j], loopInstanceList[j+1:]...)
				return c.JSON(http.StatusOK, "{}")
			}
			//action failure
			return c.JSON(http.StatusBadRequest, ClampError{
				Message: "Cannot perform this action",
				Error:   "Bad Action",
				Status:  "400"})
		}
	}
	return c.JSON(http.StatusBadRequest, ClampError{
		Message: "Loop not found",
		Error:   "Not Found",
		Status:  "404"})
}