aboutsummaryrefslogtreecommitdiffstats
path: root/src/orchestrator/pkg/appcontext/appcontext.go
blob: db2ba43245218ec69980669d1f2697ef67f1df2b (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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
/*
 * Copyright 2020 Intel Corporation, Inc
 *
 * 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 appcontext

import (
	"fmt"
	"strings"

	log "github.com/onap/multicloud-k8s/src/orchestrator/pkg/infra/logutils"
	"github.com/onap/multicloud-k8s/src/orchestrator/pkg/rtcontext"
	pkgerrors "github.com/pkg/errors"
)

// metaPrefix used for denoting clusterMeta level
const metaGrpPREFIX = "!@#metaGrp"

type AppContext struct {
	initDone bool
	rtcObj   rtcontext.RunTimeContext
	rtc      rtcontext.Rtcontext
}

// AppContextStatus represents the current status of the appcontext
//	Instantiating - instantiate has been invoked and is still in progress
//	Instantiated - instantiate has completed
//	PreTerminate - terminate has been invoked when in Instantiating status - need to clean up first
//	Terminating - terminate has been invoked and is still in progress
//	Terminated - terminate has completed
//	Failed - the instantiate or terminate action has failed
type AppContextStatus struct {
	Status StatusValue
}
type StatusValue string
type statuses struct {
	Instantiating StatusValue
	Instantiated  StatusValue
	PreTerminate  StatusValue
	Terminating   StatusValue
	Terminated    StatusValue
	Failed        StatusValue
}

var AppContextStatusEnum = &statuses{
	Instantiating: "Instantiating",
	Instantiated:  "Instantiated",
	PreTerminate:  "PreTerminate",
	Terminating:   "Terminating",
	Terminated:    "Terminated",
	Failed:        "Failed",
}

// CompositeAppMeta consists of projectName, CompositeAppName,
// CompositeAppVersion, ReleaseName. This shall be used for
// instantiation of a compositeApp
type CompositeAppMeta struct {
	Project      string `json:"Project"`
	CompositeApp string `json:"CompositeApp"`
	Version      string `json:"Version"`
	Release      string `json:"Release"`
}

// Init app context
func (ac *AppContext) InitAppContext() (interface{}, error) {
	ac.rtcObj = rtcontext.RunTimeContext{}
	ac.rtc = &ac.rtcObj
	return ac.rtc.RtcInit()
}

// Load app context that was previously created
func (ac *AppContext) LoadAppContext(cid interface{}) (interface{}, error) {
	ac.rtcObj = rtcontext.RunTimeContext{}
	ac.rtc = &ac.rtcObj
	return ac.rtc.RtcLoad(cid)
}

// CreateCompositeApp method returns composite app handle as interface.
func (ac *AppContext) CreateCompositeApp() (interface{}, error) {
	h, err := ac.rtc.RtcCreate()
	if err != nil {
		return nil, err
	}
	log.Info(":: CreateCompositeApp ::", log.Fields{"CompositeAppHandle": h})
	return h, nil
}

// AddCompositeAppMeta adds the meta data associated with a composite app
func (ac *AppContext) AddCompositeAppMeta(meta interface{}) error {
	err := ac.rtc.RtcAddMeta(meta)
	if err != nil {
		return err
	}
	return nil
}

// Deletes the entire context
func (ac *AppContext) DeleteCompositeApp() error {
	h, err := ac.rtc.RtcGet()
	if err != nil {
		return err
	}
	err = ac.rtc.RtcDeletePrefix(h)
	if err != nil {
		return err
	}
	return nil
}

//Returns the handles for a given composite app context
func (ac *AppContext) GetCompositeAppHandle() (interface{}, error) {
	h, err := ac.rtc.RtcGet()
	if err != nil {
		return nil, err
	}
	return h, nil
}

// GetLevelHandle returns the handle for the supplied level at the given handle.
// For example, to get the handle of the 'status' level at a given handle.
func (ac *AppContext) GetLevelHandle(handle interface{}, level string) (interface{}, error) {
	ach := fmt.Sprintf("%v%v/", handle, level)
	hs, err := ac.rtc.RtcGetHandles(ach)
	if err != nil {
		return nil, err
	}
	for _, v := range hs {
		if v == ach {
			return v, nil
		}
	}
	return nil, pkgerrors.Errorf("No handle was found for level %v", level)
}

//Add app to the context under composite app
func (ac *AppContext) AddApp(handle interface{}, appname string) (interface{}, error) {
	h, err := ac.rtc.RtcAddLevel(handle, "app", appname)
	if err != nil {
		return nil, err
	}
	log.Info(":: Added app handle ::", log.Fields{"AppHandle": h})
	return h, nil
}

//Delete app from the context and everything underneth
func (ac *AppContext) DeleteApp(handle interface{}) error {
	err := ac.rtc.RtcDeletePrefix(handle)
	if err != nil {
		return err
	}
	return nil
}

//Returns the handle for a given app
func (ac *AppContext) GetAppHandle(appname string) (interface{}, error) {
	if appname == "" {
		return nil, pkgerrors.Errorf("Not a valid run time context app name")
	}

	rh, err := ac.rtc.RtcGet()
	if err != nil {
		return nil, err
	}

	apph := fmt.Sprintf("%v", rh) + "app/" + appname + "/"
	hs, err := ac.rtc.RtcGetHandles(apph)
	if err != nil {
		return nil, err
	}
	for _, v := range hs {
		if v == apph {
			return v, nil
		}
	}
	return nil, pkgerrors.Errorf("No handle was found for the given app")
}

// AddCluster helps to add cluster to the context under app. It takes in the app handle and clusterName as value.
func (ac *AppContext) AddCluster(handle interface{}, clustername string) (interface{}, error) {
	h, err := ac.rtc.RtcAddLevel(handle, "cluster", clustername)
	if err != nil {
		return nil, err
	}
	log.Info(":: Added cluster handle ::", log.Fields{"ClusterHandler": h})
	return h, nil
}

// AddClusterMetaGrp adds the meta info of groupNumber to which a cluster belongs.
// It takes in cluster handle and groupNumber as arguments
func (ac *AppContext) AddClusterMetaGrp(ch interface{}, gn string) error {
	mh, err := ac.rtc.RtcAddOneLevel(ch, metaGrpPREFIX, gn)
	if err != nil {
		return err
	}
	log.Info(":: Added cluster meta handle ::", log.Fields{"ClusterMetaHandler": mh})
	return nil
}

// DeleteClusterMetaGrpHandle deletes the group number to which the cluster belongs, it takes in the cluster handle.
func (ac *AppContext) DeleteClusterMetaGrpHandle(ch interface{}) error {
	err := ac.rtc.RtcDeletePrefix(ch)
	if err != nil {
		return err
	}
	log.Info(":: Deleted cluster meta handle ::", log.Fields{"ClusterMetaHandler": ch})
	return nil
}

/*
GetClusterMetaHandle takes in appName and ClusterName as string arguments and return the ClusterMetaHandle as string
*/
func (ac *AppContext) GetClusterMetaHandle(app string, cluster string) (string, error) {
	if app == "" {
		return "", pkgerrors.Errorf("Not a valid run time context app name")
	}
	if cluster == "" {
		return "", pkgerrors.Errorf("Not a valid run time context cluster name")
	}

	ch, err := ac.GetClusterHandle(app, cluster)
	if err != nil {
		return "", err
	}
	cmh := fmt.Sprintf("%v", ch) + metaGrpPREFIX + "/"
	return cmh, nil

}

/*
GetClusterGroupMap shall take in appName and return a map showing the grouping among the clusters.
sample output of "GroupMap" :{"1":["cluster_provider1+clusterName3","cluster_provider1+clusterName5"],"2":["cluster_provider2+clusterName4","cluster_provider2+clusterName6"]}
*/
func (ac *AppContext) GetClusterGroupMap(an string) (map[string][]string, error) {
	cl, err := ac.GetClusterNames(an)
	if err != nil {
		log.Info(":: Unable to fetch clusterList for app ::", log.Fields{"AppName ": an})
		return nil, err
	}
	rh, err := ac.rtc.RtcGet()
	if err != nil {
		return nil, err
	}

	var gmap = make(map[string][]string)
	for _, cn := range cl {
		s := fmt.Sprintf("%v", rh) + "app/" + an + "/cluster/" + cn + "/" + metaGrpPREFIX + "/"
		var v string
		err = ac.rtc.RtcGetValue(s, &v)
		if err != nil {
			log.Info(":: No group number for cluster  ::", log.Fields{"cluster": cn, "Reason": err})
			continue
		}
		gn := fmt.Sprintf("%v", v)
		log.Info(":: GroupNumber retrieved  ::", log.Fields{"GroupNumber": gn})

		cl, found := gmap[gn]
		if found == false {
			cl = make([]string, 0)
		}
		cl = append(cl, cn)
		gmap[gn] = cl
	}
	return gmap, nil
}

//Delete cluster from the context and everything underneth
func (ac *AppContext) DeleteCluster(handle interface{}) error {
	err := ac.rtc.RtcDeletePrefix(handle)
	if err != nil {
		return err
	}
	return nil
}

//Returns the handle for a given app and cluster
func (ac *AppContext) GetClusterHandle(appname string, clustername string) (interface{}, error) {
	if appname == "" {
		return nil, pkgerrors.Errorf("Not a valid run time context app name")
	}
	if clustername == "" {
		return nil, pkgerrors.Errorf("Not a valid run time context cluster name")
	}

	rh, err := ac.rtc.RtcGet()
	if err != nil {
		return nil, err
	}

	ach := fmt.Sprintf("%v", rh) + "app/" + appname + "/cluster/" + clustername + "/"
	hs, err := ac.rtc.RtcGetHandles(ach)
	if err != nil {
		return nil, err
	}
	for _, v := range hs {
		if v == ach {
			return v, nil
		}
	}
	return nil, pkgerrors.Errorf("No handle was found for the given cluster")
}

//Returns a list of all clusters for a given app
func (ac *AppContext) GetClusterNames(appname string) ([]string, error) {
	if appname == "" {
		return nil, pkgerrors.Errorf("Not a valid run time context app name")
	}

	rh, err := ac.rtc.RtcGet()
	if err != nil {
		return nil, err
	}

	prefix := fmt.Sprintf("%v", rh) + "app/" + appname + "/cluster/"
	hs, err := ac.rtc.RtcGetHandles(prefix)
	if err != nil {
		return nil, pkgerrors.Errorf("Error getting handles for %v", prefix)
	}
	var cs []string
	for _, h := range hs {
		hstr := fmt.Sprintf("%v", h)
		ks := strings.Split(hstr, prefix)
		for _, k := range ks {
			ck := strings.Split(k, "/")
			if len(ck) == 2 && ck[1] == "" {
				cs = append(cs, ck[0])
			}
		}
	}
	return cs, nil
}

//Add resource under app and cluster
func (ac *AppContext) AddResource(handle interface{}, resname string, value interface{}) (interface{}, error) {
	h, err := ac.rtc.RtcAddResource(handle, resname, value)
	if err != nil {
		return nil, err
	}
	log.Info(":: Added resource handle ::", log.Fields{"ResourceHandler": h})

	return h, nil
}

//Return the handle for given app, cluster and resource name
func (ac *AppContext) GetResourceHandle(appname string, clustername string, resname string) (interface{}, error) {
	if appname == "" {
		return nil, pkgerrors.Errorf("Not a valid run time context app name")
	}
	if clustername == "" {
		return nil, pkgerrors.Errorf("Not a valid run time context cluster name")
	}

	rh, err := ac.rtc.RtcGet()
	if err != nil {
		return nil, err
	}

	acrh := fmt.Sprintf("%v", rh) + "app/" + appname + "/cluster/" + clustername + "/resource/" + resname + "/"
	hs, err := ac.rtc.RtcGetHandles(acrh)
	if err != nil {
		return nil, err
	}
	for _, v := range hs {
		if v == acrh {
			return v, nil
		}
	}
	return nil, pkgerrors.Errorf("No handle was found for the given resource")
}

//Update the resource value using the given handle
func (ac *AppContext) UpdateResourceValue(handle interface{}, value interface{}) error {
	return ac.rtc.RtcUpdateValue(handle, value)
}

//Return the handle for given app, cluster and resource name
func (ac *AppContext) GetResourceStatusHandle(appname string, clustername string, resname string) (interface{}, error) {
	if appname == "" {
		return nil, pkgerrors.Errorf("Not a valid run time context app name")
	}
	if clustername == "" {
		return nil, pkgerrors.Errorf("Not a valid run time context cluster name")
	}
	if resname == "" {
		return nil, pkgerrors.Errorf("Not a valid run time context resource name")
	}

	rh, err := ac.rtc.RtcGet()
	if err != nil {
		return nil, err
	}

	acrh := fmt.Sprintf("%v", rh) + "app/" + appname + "/cluster/" + clustername + "/resource/" + resname + "/status/"
	hs, err := ac.rtc.RtcGetHandles(acrh)
	if err != nil {
		return nil, err
	}
	for _, v := range hs {
		if v == acrh {
			return v, nil
		}
	}
	return nil, pkgerrors.Errorf("No handle was found for the given resource")
}

//Add instruction under given handle and type
func (ac *AppContext) AddInstruction(handle interface{}, level string, insttype string, value interface{}) (interface{}, error) {
	if !(insttype == "order" || insttype == "dependency") {
		return nil, pkgerrors.Errorf("Not a valid app context instruction type")
	}
	if !(level == "app" || level == "resource") {
		return nil, pkgerrors.Errorf("Not a valid app context instruction level")
	}
	h, err := ac.rtc.RtcAddInstruction(handle, level, insttype, value)
	if err != nil {
		return nil, err
	}
	log.Info(":: Added instruction handle ::", log.Fields{"InstructionHandler": h})
	return h, nil
}

//Delete instruction under given handle
func (ac *AppContext) DeleteInstruction(handle interface{}) error {
	err := ac.rtc.RtcDeletePair(handle)
	if err != nil {
		return err
	}
	return nil
}

//Returns the app instruction for a given instruction type
func (ac *AppContext) GetAppInstruction(insttype string) (interface{}, error) {
	if !(insttype == "order" || insttype == "dependency") {
		return nil, pkgerrors.Errorf("Not a valid app context instruction type")
	}
	rh, err := ac.rtc.RtcGet()
	if err != nil {
		return nil, err
	}
	s := fmt.Sprintf("%v", rh) + "app/" + "instruction/" + insttype + "/"
	var v string
	err = ac.rtc.RtcGetValue(s, &v)
	if err != nil {
		return nil, err
	}
	return v, nil
}

//Update the instruction usign the given handle
func (ac *AppContext) UpdateInstructionValue(handle interface{}, value interface{}) error {
	return ac.rtc.RtcUpdateValue(handle, value)
}

//Returns the resource instruction for a given instruction type
func (ac *AppContext) GetResourceInstruction(appname string, clustername string, insttype string) (interface{}, error) {
	if !(insttype == "order" || insttype == "dependency") {
		return nil, pkgerrors.Errorf("Not a valid app context instruction type")
	}
	rh, err := ac.rtc.RtcGet()
	if err != nil {
		return nil, err
	}
	s := fmt.Sprintf("%v", rh) + "app/" + appname + "/cluster/" + clustername + "/resource/instruction/" + insttype + "/"
	var v string
	err = ac.rtc.RtcGetValue(s, &v)
	if err != nil {
		return nil, err
	}
	return v, nil
}

// AddLevelValue for holding a state object at a given level
// will make a handle with an appended "<level>/" to the key
func (ac *AppContext) AddLevelValue(handle interface{}, level string, value interface{}) (interface{}, error) {
	h, err := ac.rtc.RtcAddOneLevel(handle, level, value)
	if err != nil {
		return nil, err
	}
	log.Info(":: Added handle ::", log.Fields{"Handle": h})

	return h, nil
}

// GetClusterStatusHandle returns the handle for cluster status for a given app and cluster
func (ac *AppContext) GetClusterStatusHandle(appname string, clustername string) (interface{}, error) {
	if appname == "" {
		return nil, pkgerrors.Errorf("Not a valid run time context app name")
	}
	if clustername == "" {
		return nil, pkgerrors.Errorf("Not a valid run time context cluster name")
	}

	rh, err := ac.rtc.RtcGet()
	if err != nil {
		return nil, err
	}

	acrh := fmt.Sprintf("%v", rh) + "app/" + appname + "/cluster/" + clustername + "/status/"
	hs, err := ac.rtc.RtcGetHandles(acrh)
	if err != nil {
		return nil, err
	}
	for _, v := range hs {
		if v == acrh {
			return v, nil
		}
	}
	return nil, pkgerrors.Errorf("No handle was found for the given resource")
}

//UpdateStatusValue updates the status value with the given handle
func (ac *AppContext) UpdateStatusValue(handle interface{}, value interface{}) error {
	return ac.rtc.RtcUpdateValue(handle, value)
}

//UpdateValue updates the state value with the given handle
func (ac *AppContext) UpdateValue(handle interface{}, value interface{}) error {
	return ac.rtc.RtcUpdateValue(handle, value)
}

//Return all the handles under the composite app
func (ac *AppContext) GetAllHandles(handle interface{}) ([]interface{}, error) {
	hs, err := ac.rtc.RtcGetHandles(handle)
	if err != nil {
		return nil, err
	}
	return hs, nil
}

//Returns the value for a given handle
func (ac *AppContext) GetValue(handle interface{}) (interface{}, error) {
	var v interface{}
	err := ac.rtc.RtcGetValue(handle, &v)
	if err != nil {
		return nil, err
	}
	return v, nil
}

// GetCompositeAppMeta returns the meta data associated with the compositeApp
// Its return type is CompositeAppMeta
func (ac *AppContext) GetCompositeAppMeta() (CompositeAppMeta, error) {
	mi, err := ac.rtcObj.RtcGetMeta()

	if err != nil {
		return CompositeAppMeta{}, pkgerrors.Errorf("Failed to get compositeApp meta")
	}
	datamap, ok := mi.(map[string]interface{})
	if ok == false {
		return CompositeAppMeta{}, pkgerrors.Errorf("Failed to cast meta interface to compositeApp meta")
	}

	p := fmt.Sprintf("%v", datamap["Project"])
	ca := fmt.Sprintf("%v", datamap["CompositeApp"])
	v := fmt.Sprintf("%v", datamap["Version"])
	rn := fmt.Sprintf("%v", datamap["Release"])

	return CompositeAppMeta{Project: p, CompositeApp: ca, Version: v, Release: rn}, nil
}