Newer
Older
/*
* Copyright (c) 2024 The AdvantEDGE Authors
*
* 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 server
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"time"
dkm "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-data-key-mgr"
log "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-logger"
mq "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-mq"
redis "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-redis"
subs "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-subscriptions"
uuid "github.com/google/uuid"
"github.com/gorilla/mux"
)
const moduleName = "meep-app-enablement"
const svcMgmtBasePath = "mec_service_mgmt/v1/"
const appEnablementKey = "app-enablement"
const globalMepName = "global"
const SER_AVAILABILITY_NOTIF_SUB_TYPE = "SerAvailabilityNotificationSubscription"
const SER_AVAILABILITY_NOTIF_TYPE = "SerAvailabilityNotification"
const APP_STATE_READY = "READY"
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
const serviceName = "App Enablement Service"
// App Info fields
const fieldState = "state"
// MQ payload fields
const fieldSvcInfo = "svc-info"
const fieldAppId = "app-id"
const fieldChangeType = "change-type"
const fieldMepName = "mep-name"
var mutex *sync.Mutex
var redisAddr string // = "meep-redis-master.default.svc.cluster.local:6379"
var APP_ENABLEMENT_DB = 0
var rc *redis.Connector
var mqLocal *mq.MsgQueue
var hostUrl *url.URL
var sandboxName string
var mepName string
var basePath string
var baseKey string
var baseKeyAnyMep string
var subMgr *subs.SubscriptionMgr
type ServiceInfoList struct {
Services []ServiceInfo
ConsumedLocalOnlyPresent bool
IsLocalPresent bool
Filters *FilterParameters
}
type FilterParameters struct {
serInstanceId []string
serName []string
serCategoryId string
consumedLocalOnly bool
isLocal bool
scopeOfLocality string
}
type StateData struct {
State ServiceState
AppId string
}
var livenessTimerList map[string]ServiceLivenessInfo
func Init(sandbox string, mep string, host *url.URL, msgQueue *mq.MsgQueue, redisAddr_ string, globalMutex *sync.Mutex) (err error) {
redisAddr = redisAddr_
sandboxName = sandbox
mepName = mep
hostUrl = host
mqLocal = msgQueue
mutex = globalMutex
// Set base path & storage key
if mepName == globalMepName {
basePath = "/" + sandboxName + "/" + svcMgmtBasePath
baseKey = dkm.GetKeyRoot(sandboxName) + appEnablementKey + ":mep-global:"
baseKeyAnyMep = dkm.GetKeyRoot(sandboxName) + appEnablementKey + ":mep-global:"
} else {
basePath = "/" + sandboxName + "/" + mepName + "/" + svcMgmtBasePath
baseKey = dkm.GetKeyRoot(sandboxName) + appEnablementKey + ":mep:" + mepName + ":"
baseKeyAnyMep = dkm.GetKeyRoot(sandboxName) + appEnablementKey + ":mep:*:"
}
// Connect to Redis DB
rc, err = redis.NewConnector(redisAddr, APP_ENABLEMENT_DB)
if err != nil {
log.Error("Failed connection to Redis DB. Error: ", err)
return err
}
log.Info("Connected to Redis DB")
// Create Subscription Manager
subMgrCfg := &subs.SubscriptionMgrCfg{
Module: moduleName,
Sandbox: sandboxName,
Mep: mepName,
Service: serviceName,
Basekey: baseKey,
MetricsEnabled: true,
ExpiredSubCb: nil,
PeriodicSubCb: nil,
TestNotifCb: nil,
NewWsCb: nil,
}
subMgr, err = subs.NewSubscriptionMgr(subMgrCfg, redisAddr)
if err != nil {
log.Error("Failed to create Subscription Manager. Error: ", err)
return err
}
log.Info("Created Subscription Manager")
livenessTimerList = make(map[string]ServiceLivenessInfo)
// TODO -- Initialize subscriptions from DB
return nil
}
// Run - Start Service Mgmt
func Run() (err error) {
// Register Message Queue handler
handler := mq.MsgHandler{Handler: msgHandler, UserData: nil}
_, err = mqLocal.RegisterHandler(handler)
if err != nil {
log.Error("Failed to listen for sandbox updates: ", err.Error())
return err
}
return nil
}
// Stop - Stop Service Mgmt
func Stop() (err error) {
if len(livenessTimerList) != 0 {
livenessTimerList = make(map[string]ServiceLivenessInfo)
}
return nil
}
func createLivenessTicker(sInfo ServiceInfo) {
log.Debug(">>> createLivenessTicker: ", sInfo)
livenessTimerList[sInfo.SerInstanceId] = ServiceLivenessInfo{
State: &ACTIVE_ServiceState,
TimeStamp: &ServiceLivenessInfoTimeStamp{Seconds: 0, NanoSeconds: 0},
Interval: sInfo.LivenessInterval,
}
}
func updateLivenessTicker(sInfo ServiceInfo) {
log.Debug(">>> updateLivenessTicker: ", sInfo)
if sInfo.LivenessInterval != livenessTimerList[sInfo.SerInstanceId].Interval {
deleteLivenessTicker(sInfo.SerInstanceId)
createLivenessTicker(sInfo)
}
}
func deleteLivenessTicker(serInstanceId string) {
log.Debug(">>> deleteLivenessTicker: ", serInstanceId)
delete(livenessTimerList, serInstanceId)
}
// Message Queue handler
func msgHandler(msg *mq.Msg, userData interface{}) {
switch msg.Message {
case mq.MsgMecSvcUpdate:
log.Debug("RX MSG: ", mq.PrintMsg(msg))
sInfoJson := msg.Payload[fieldSvcInfo]
mep := msg.Payload[fieldMepName]
changeType := msg.Payload[fieldChangeType]
processSvcUpdate(sInfoJson, mep, changeType)
default:
}
}
func appServicesPOST(w http.ResponseWriter, r *http.Request) {
log.Info("appServicesPOST")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
appId := vars["appInstanceId"]
mutex.Lock()
defer mutex.Unlock()
// Get App instance
appInfo, err := getAppInfo(appId)
if err != nil {
errHandlerProblemDetails(w, err.Error(), http.StatusNotFound)
return
}
// Validate App info
code, problemDetails, err := validateAppInfo(appInfo)
if err != nil {
log.Error(err.Error())
if problemDetails != "" {
w.WriteHeader(code)
fmt.Fprint(w, problemDetails)
} else {
errHandlerProblemDetails(w, err.Error(), code)
}
return
}
// Retrieve request parameters from body
if r.Body == nil {
err := errors.New("Request body is missing")
errHandlerProblemDetails(w, err.Error(), http.StatusBadRequest)
return
}
// NOTE: Set default values for omitted fields
locality := MEC_HOST_LocalityType
sInfoPost := ServiceInfo{
ScopeOfLocality: &locality,
IsLocal: true,
ConsumedLocalOnly: true,
}
decoder := json.NewDecoder(r.Body)
err = decoder.Decode(&sInfoPost)
if err != nil {
log.Error(err.Error())
errHandlerProblemDetails(w, err.Error(), http.StatusInternalServerError)
return
}
// Check for mandatory properties
if sInfoPost.SerInstanceId != "" {
errStr := "Service instance ID must not be present"
log.Error(errStr)
errHandlerProblemDetails(w, errStr, http.StatusBadRequest)
return
}
if sInfoPost.SerName == "" {
errStr := "Mandatory Service Name parameter not present"
log.Error(errStr)
errHandlerProblemDetails(w, errStr, http.StatusBadRequest)
return
}
if sInfoPost.Version == "" {
errStr := "Mandatory Service Version parameter not present"
log.Error(errStr)
errHandlerProblemDetails(w, errStr, http.StatusBadRequest)
return
}
if sInfoPost.State == nil {
errStr := "Mandatory Service State parameter not present"
log.Error(errStr)
errHandlerProblemDetails(w, errStr, http.StatusBadRequest)
return
}
if sInfoPost.Serializer == nil {
errStr := "Mandatory Serializer parameter not present"
log.Error(errStr)
errHandlerProblemDetails(w, errStr, http.StatusBadRequest)
return
}
if sInfoPost.SerCategory != nil {
errStr := validateCategoryRef(sInfoPost.SerCategory)
if errStr != "" {
log.Error(errStr)
errHandlerProblemDetails(w, errStr, http.StatusBadRequest)
return
}
}
if (sInfoPost.TransportId != "" && sInfoPost.TransportInfo != nil) ||
(sInfoPost.TransportId == "" && sInfoPost.TransportInfo == nil) {
errStr := "Either transportId or transportInfo but not both shall be present"
log.Error(errStr)
errHandlerProblemDetails(w, errStr, http.StatusBadRequest)
return
}
if sInfoPost.Links != nil {
errStr := "Links parameter should not be present in request"
log.Error(errStr)
errHandlerProblemDetails(w, errStr, http.StatusBadRequest)
return
}
if sInfoPost.TransportInfo != nil {
if sInfoPost.TransportInfo.Id == "" ||
sInfoPost.TransportInfo.Name == "" ||
string(*sInfoPost.TransportInfo.Type_) == "" ||
sInfoPost.TransportInfo.Protocol == "" ||
sInfoPost.TransportInfo.Version == "" ||
sInfoPost.TransportInfo.Endpoint == nil {
errStr := "Id, Name, Type, Protocol, Version, Endpoint are all mandatory parameters of TransportInfo"
log.Error(errStr)
errHandlerProblemDetails(w, errStr, http.StatusBadRequest)
return
}
}
// Create Service
sInfo := &ServiceInfo{
SerInstanceId: uuid.New().String(),
SerName: sInfoPost.SerName,
SerCategory: sInfoPost.SerCategory,
Version: sInfoPost.Version,
State: sInfoPost.State,
TransportInfo: sInfoPost.TransportInfo,
Serializer: sInfoPost.Serializer,
ScopeOfLocality: sInfoPost.ScopeOfLocality,
ConsumedLocalOnly: sInfoPost.ConsumedLocalOnly,
// although IsLocal is reevaluated when a query is replied to, value stored in sInfo as is for now
IsLocal: sInfoPost.IsLocal,
LivenessInterval: sInfoPost.LivenessInterval,
}
sInfo.Links = &ServiceInfoLinks{
Self: &LinkType{
Href: hostUrl.String() + basePath + "applications/" + appId + "/services/" + sInfo.SerInstanceId,
},
}
if sInfo.LivenessInterval != 0 {
sInfo.Links.Liveness = &LinkType{
Href: hostUrl.String() + basePath + "resource_uri_allocated_by_MEC_platform/" + sInfo.SerInstanceId,
}
}
err, retCode := setService(appId, sInfo, ADDED_ServiceAvailabilityNotificationChangeType)
if err != nil {
log.Error(err.Error())
errHandlerProblemDetails(w, err.Error(), retCode)
return
}
// Send response
w.Header().Set("Location", hostUrl.String()+basePath+"applications/"+appId+"/services/"+sInfo.SerInstanceId)
w.WriteHeader(http.StatusCreated)
fmt.Fprint(w, convertServiceInfoToJson(sInfo))
}
func appServicesByIdPUT(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
log.Info("appServicesByIdPUT")
vars := mux.Vars(r)
appId := vars["appInstanceId"]
svcId := vars["serviceId"]
mutex.Lock()
defer mutex.Unlock()
// Get App instance
appInfo, err := getAppInfo(appId)
if err != nil {
errHandlerProblemDetails(w, err.Error(), http.StatusNotFound)
return
}
// Validate App info
code, problemDetails, err := validateAppInfo(appInfo)
if err != nil {
log.Error(err.Error())
if problemDetails != "" {
w.WriteHeader(code)
fmt.Fprint(w, problemDetails)
} else {
errHandlerProblemDetails(w, err.Error(), code)
}
return
}
// Get previous service info
sInfoPrevJson, err := getServiceById(appId, svcId)
if err != nil {
log.Error(err.Error())
w.WriteHeader(http.StatusNotFound)
return
}
sInfoPrev := convertJsonToServiceInfo(sInfoPrevJson)
// Retrieve request parameters from body
if r.Body == nil {
err := errors.New("Request body is missing")
errHandlerProblemDetails(w, err.Error(), http.StatusBadRequest)
return
}
// NOTE: Set default values for omitted fields
locality := MEC_HOST_LocalityType
sInfo := ServiceInfo{
ScopeOfLocality: &locality,
IsLocal: true,
ConsumedLocalOnly: true,
}
decoder := json.NewDecoder(r.Body)
err = decoder.Decode(&sInfo)
if err != nil {
log.Error(err.Error())
errHandlerProblemDetails(w, err.Error(), http.StatusInternalServerError)
return
}
// Current implementation only supports state parameter change;
// Make sure none of the other service information fields have changed
state := *sInfo.State
*sInfo.State = *sInfoPrev.State
// isLocal is only set in responses, subscriptions and notifications;
// Ignore this field while comparing the previous & new service info structs
sInfo.IsLocal = sInfoPrev.IsLocal
// Compare service information as JSON strings
/* FSCOM: It is not specified that only the ServiceInfo state property may be changed in ETSI GS MEC 011 V3.2.1 (2024-04)
sInfoJson := convertServiceInfoToJson(&sInfo)
if sInfoJson != sInfoPrevJson {
errStr := "Only the ServiceInfo state property may be changed"
log.Error(errStr)
errHandlerProblemDetails(w, errStr, http.StatusBadRequest)
return
}*/
// Compare service info states & update DB if necessary
*sInfo.State = state
if *sInfo.State != *sInfoPrev.State {
err, retCode := setService(appId, &sInfo, STATE_CHANGED_ServiceAvailabilityNotificationChangeType)
if err != nil {
log.Error(err.Error())
errHandlerProblemDetails(w, err.Error(), retCode)
return
}
}
// Compare LivenessInterval
if sInfo.LivenessInterval != sInfoPrev.LivenessInterval {
if _, ok := livenessTimerList[sInfo.SerInstanceId]; ok { // An entry already exist
if sInfo.LivenessInterval != 0 { // update it
updateLivenessTicker(sInfo)
} else {
deleteLivenessTicker(sInfo.SerInstanceId)
}
} else { // No entry
if sInfo.LivenessInterval != 0 { // Create a new entry
createLivenessTicker(sInfo)
}
}
} // else, nothing to do
sInfo.LivenessInterval = sInfoPrev.LivenessInterval
// Send response
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, convertServiceInfoToJson(&sInfo))
}
func appServicesByIdDELETE(w http.ResponseWriter, r *http.Request) {
log.Info("appServicesByIdDELETE")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
appId := vars["appInstanceId"]
svcId := vars["serviceId"]
mutex.Lock()
defer mutex.Unlock()
// Get App instance
appInfo, err := getAppInfo(appId)
if err != nil {
errHandlerProblemDetails(w, err.Error(), http.StatusNotFound)
return
}
// Validate App info
code, problemDetails, err := validateAppInfo(appInfo)
if err != nil {
log.Error(err.Error())
if problemDetails != "" {
w.WriteHeader(code)
fmt.Fprint(w, problemDetails)
} else {
errHandlerProblemDetails(w, err.Error(), code)
}
return
}
// Get service info
sInfoJson, err := getServiceById(appId, svcId)
if err != nil {
log.Error(err.Error())
w.WriteHeader(http.StatusNotFound)
return
}
sInfo := convertJsonToServiceInfo(sInfoJson)
// Delete service
err = delServiceById(appId, svcId)
if err != nil {
errHandlerProblemDetails(w, err.Error(), http.StatusInternalServerError)
return
}
// Notify remote listeners (except if global instance)
changeType := REMOVED_ServiceAvailabilityNotificationChangeType
if mepName != globalMepName {
sendSvcUpdateMsg(sInfoJson, appId, mepName, string(changeType))
}
// Send local service availability notifications
checkSerAvailNotification(sInfo, mepName, changeType)
w.WriteHeader(http.StatusNoContent)
}
func appServicesGET(w http.ResponseWriter, r *http.Request) {
log.Info("appServicesGET")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
appId := vars["appInstanceId"]
mutex.Lock()
defer mutex.Unlock()
// Get App instance
appInfo, err := getAppInfoAnyMep(appId)
if err != nil {
errHandlerProblemDetails(w, err.Error(), http.StatusNotFound)
return
}
// Validate App info
code, problemDetails, err := validateAppInfo(appInfo)
if err != nil {
log.Error(err.Error())
if problemDetails != "" {
w.WriteHeader(code)
fmt.Fprint(w, problemDetails)
} else {
errHandlerProblemDetails(w, err.Error(), code)
}
return
}
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
}
func appServicesByIdGET(w http.ResponseWriter, r *http.Request) {
log.Info("appServicesByIdGET")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
svcId := vars["serviceId"]
appId := vars["appInstanceId"]
mutex.Lock()
defer mutex.Unlock()
// Get App instance
appInfo, err := getAppInfoAnyMep(appId)
if err != nil {
errHandlerProblemDetails(w, err.Error(), http.StatusNotFound)
return
}
// Validate App info
code, problemDetails, err := validateAppInfo(appInfo)
if err != nil {
log.Error(err.Error())
if problemDetails != "" {
w.WriteHeader(code)
fmt.Fprint(w, problemDetails)
} else {
errHandlerProblemDetails(w, err.Error(), code)
}
return
}
getService(w, r, appId, svcId)
}
func servicesByIdGET(w http.ResponseWriter, r *http.Request) {
log.Info("servicesByIdGET")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
svcId := vars["serviceId"]
mutex.Lock()
defer mutex.Unlock()
getService(w, r, "", svcId)
}
func servicesGET(w http.ResponseWriter, r *http.Request) {
log.Info("servicesGET")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
mutex.Lock()
defer mutex.Unlock()
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
}
func applicationsSubscriptionsPOST(w http.ResponseWriter, r *http.Request) {
log.Info("applicationsSubscriptionsPOST")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
appId := vars["appInstanceId"]
mutex.Lock()
defer mutex.Unlock()
// Get App instance
appInfo, err := getAppInfo(appId)
if err != nil {
errHandlerProblemDetails(w, err.Error(), http.StatusNotFound)
return
}
// Validate App info
code, problemDetails, err := validateAppInfo(appInfo)
if err != nil {
log.Error(err.Error())
if problemDetails != "" {
w.WriteHeader(code)
fmt.Fprint(w, problemDetails)
} else {
errHandlerProblemDetails(w, err.Error(), code)
}
return
}
// Retrieve subscription request
if r.Body == nil {
err := errors.New("Request body is missing")
errHandlerProblemDetails(w, err.Error(), http.StatusBadRequest)
return
}
var serAvailNotifSub SerAvailabilityNotificationSubscription
decoder := json.NewDecoder(r.Body)
err = decoder.Decode(&serAvailNotifSub)
if err != nil {
log.Error(err.Error())
errHandlerProblemDetails(w, err.Error(), http.StatusInternalServerError)
return
}
// Validate mandatory properties
if serAvailNotifSub.CallbackReference == "" {
log.Error("Mandatory CallbackReference parameter not present")
errHandlerProblemDetails(w, "Mandatory CallbackReference parameter not present", http.StatusBadRequest)
return
}
if serAvailNotifSub.SubscriptionType != SER_AVAILABILITY_NOTIF_SUB_TYPE {
log.Error("SubscriptionType shall be SerAvailabilityNotificationSubscription")
errHandlerProblemDetails(w, "SubscriptionType shall be SerAvailabilityNotificationSubscription", http.StatusBadRequest)
return
}
// Validate Service filter params
if serAvailNotifSub.FilteringCriteria != nil {
nbMutuallyExclusiveParams := 0
if serAvailNotifSub.FilteringCriteria.SerInstanceIds != nil {
if len(serAvailNotifSub.FilteringCriteria.SerInstanceIds) > 0 {
nbMutuallyExclusiveParams++
}
}
if serAvailNotifSub.FilteringCriteria.SerNames != nil {
if len(serAvailNotifSub.FilteringCriteria.SerNames) > 0 {
nbMutuallyExclusiveParams++
}
}
if serAvailNotifSub.FilteringCriteria.SerCategories != nil {
for _, categoryRef := range serAvailNotifSub.FilteringCriteria.SerCategories {
errStr := validateCategoryRef(&categoryRef)
if errStr != "" {
log.Error(errStr)
errHandlerProblemDetails(w, errStr, http.StatusBadRequest)
return
}
}
if len(serAvailNotifSub.FilteringCriteria.SerCategories) > 0 {
nbMutuallyExclusiveParams++
}
}
if nbMutuallyExclusiveParams > 1 {
errStr := "FilteringCriteria attributes serInstanceIds, serNames, serCategories are mutually-exclusive"
log.Error(errStr)
errHandlerProblemDetails(w, errStr, http.StatusBadRequest)
return
}
}
// Get a new subscription ID
subId := subMgr.GenerateSubscriptionId()
// Set resource link
serAvailNotifSub.Links = &Self{
Self: &LinkType{
Href: hostUrl.String() + basePath + "applications/" + appId + "/subscriptions/" + subId,
},
}
// Create & store subscription
subCfg := newSerAvailabilityNotifSubCfg(&serAvailNotifSub, subId, appId)
jsonSub := convertSerAvailabilityNotifSubToJson(&serAvailNotifSub)
_, err = subMgr.CreateSubscription(subCfg, jsonSub)
if err != nil {
log.Error("Failed to create subscription")
errHandlerProblemDetails(w, "Failed to create subscription", http.StatusInternalServerError)
return
}
// Send response
w.Header().Set("Location", serAvailNotifSub.Links.Self.Href)
w.WriteHeader(http.StatusCreated)
fmt.Fprint(w, jsonSub)
}
func applicationsSubscriptionGET(w http.ResponseWriter, r *http.Request) {
log.Info("applicationsSubscriptionGET")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
subId := vars["subscriptionId"]
appId := vars["appInstanceId"]
mutex.Lock()
defer mutex.Unlock()
// Get App instance info
appInfo, err := getAppInfo(appId)
if err != nil {
errHandlerProblemDetails(w, err.Error(), http.StatusNotFound)
return
}
// Validate App info
code, problemDetails, err := validateAppInfo(appInfo)
if err != nil {
log.Error(err.Error())
if problemDetails != "" {
w.WriteHeader(code)
fmt.Fprint(w, problemDetails)
} else {
errHandlerProblemDetails(w, err.Error(), code)
}
return
}
// Find subscription by ID
sub, err := subMgr.GetSubscription(subId)
if err != nil {
log.Error(err.Error())
errHandlerProblemDetails(w, err.Error(), http.StatusNotFound)
return
}
// Validate subscription
// Validate subscription
if sub.Cfg.AppId != appId || sub.Cfg.Type != SER_AVAILABILITY_NOTIF_SUB_TYPE {
err = errors.New("Subscription not found")
log.Error(err.Error())
errHandlerProblemDetails(w, err.Error(), http.StatusNotFound)
return
}
// Return original marshalled subscription
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, sub.JsonSubOrig)
}
func applicationsSubscriptionDELETE(w http.ResponseWriter, r *http.Request) {
log.Info("applicationsSubscriptionDELETE")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
subId := vars["subscriptionId"]
appId := vars["appInstanceId"]
mutex.Lock()
defer mutex.Unlock()
// Get App instance info
appInfo, err := getAppInfo(appId)
if err != nil {
errHandlerProblemDetails(w, err.Error(), http.StatusNotFound)
return
}
// Validate App info
code, problemDetails, err := validateAppInfo(appInfo)
if err != nil {
log.Error(err.Error())
if problemDetails != "" {
w.WriteHeader(code)
fmt.Fprint(w, problemDetails)
} else {
errHandlerProblemDetails(w, err.Error(), code)
}
return
}
// Find subscription by ID
sub, err := subMgr.GetSubscription(subId)
if err != nil {
log.Error(err.Error())
errHandlerProblemDetails(w, err.Error(), http.StatusNotFound)
return
}
// Validate subscription
if sub.Cfg.AppId != appId || sub.Cfg.Type != SER_AVAILABILITY_NOTIF_SUB_TYPE {
err = errors.New("Subscription not found")
log.Error(err.Error())
errHandlerProblemDetails(w, err.Error(), http.StatusNotFound)
return
}
// Delete subscription
err = subMgr.DeleteSubscription(sub)
if err != nil {
log.Error(err.Error())
errHandlerProblemDetails(w, err.Error(), http.StatusInternalServerError)
return
}
// Send response
w.WriteHeader(http.StatusNoContent)
}
func applicationsSubscriptionsGET(w http.ResponseWriter, r *http.Request) {
log.Info("applicationsSubscriptionsGET")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
appId := vars["appInstanceId"]
mutex.Lock()
defer mutex.Unlock()
// Get App instance info
appInfo, err := getAppInfo(appId)
if err != nil {
errHandlerProblemDetails(w, err.Error(), http.StatusNotFound)
return
}
// Validate App info
code, problemDetails, err := validateAppInfo(appInfo)
if err != nil {
log.Error(err.Error())
if problemDetails != "" {
w.WriteHeader(code)
fmt.Fprint(w, problemDetails)
} else {
errHandlerProblemDetails(w, err.Error(), code)
}
return
}
// Get subscriptions for App instance
subList, err := subMgr.GetFilteredSubscriptions(appId, SER_AVAILABILITY_NOTIF_SUB_TYPE)
if err != nil {
log.Error("Failed to get subscription list with err: ", err.Error())
return
}
// Create subscription link list
subscriptionLinkList := &SubscriptionLinkList{
Links: &SubscriptionLinkListLinks{
Self: &LinkType{
Href: hostUrl.String() + basePath + "applications/" + appId + "/subscriptions",
},
},
}
for _, sub := range subList {
// Create subscription reference & append it to link list
subscription := SubscriptionLinkListLinksSubscriptions{
// In v2.1.1 it should be SubscriptionType, but spec is expecting "rel" as per v1.1.1
SubscriptionType: sub.Cfg.Type,
Href: sub.Cfg.Self,
}
subscriptionLinkList.Links.Subscriptions = append(subscriptionLinkList.Links.Subscriptions, subscription)
}
// Send response
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, convertSubscriptionLinkListToJson(subscriptionLinkList))
}
func getIndividualMECService(w http.ResponseWriter, r *http.Request) {
log.Info("getIndividualMECService")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
serInstanceId := vars["serInstanceId"]
mutex.Lock()
defer mutex.Unlock()
if serInstanceId == "" {
err := errors.New("wrong request parameters")
errHandlerProblemDetails(w, err.Error(), http.StatusBadRequest)
return
}
log.Info("getIndividualMECService: ", serInstanceId)
if entry, ok := livenessTimerList[serInstanceId]; !ok {
err := errors.New("Invalid Service instance ID")
errHandlerProblemDetails(w, err.Error(), http.StatusNotFound)
return
} else {
entry.TimeStamp = &ServiceLivenessInfoTimeStamp{
Seconds: int32(time.Now().Unix()),
}
fmt.Fprint(w, convertServiceLivenessInfoToJson(&entry))
livenessTimerList[serInstanceId] = entry
}
// Send response
w.WriteHeader(http.StatusOK)
}
func patchIndividualMECService(w http.ResponseWriter, r *http.Request) {
log.Info("patchIndividualMECService")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
vars := mux.Vars(r)
serInstanceId := vars["serInstanceId"]
mutex.Lock()
defer mutex.Unlock()
if serInstanceId == "" {
err := errors.New("wrong request parameters")
errHandlerProblemDetails(w, err.Error(), http.StatusBadRequest)
return
}
log.Info("patchIndividualMECService: ", serInstanceId)
if entry, ok := livenessTimerList[serInstanceId]; !ok {
err := errors.New("Invalid Service instance ID")
errHandlerProblemDetails(w, err.Error(), http.StatusNotFound)
return
} else {
// Retrieve request
if r.Body == nil {
err := errors.New("Request body is missing")
errHandlerProblemDetails(w, err.Error(), http.StatusBadRequest)
return
}
var serviceLivenessUpdate ServiceLivenessUpdate
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&serviceLivenessUpdate)
if err != nil {
log.Error(err.Error())
errHandlerProblemDetails(w, err.Error(), http.StatusInternalServerError)
return
}
log.Info("patchIndividualMECService: serviceLivenessUpdate: ", serviceLivenessUpdate)
if *serviceLivenessUpdate.State == ACTIVE_ServiceState {
entry.State = &ACTIVE_ServiceState
} else { // ETSI GS MEC 011 V3.2.1 (2024-04) Table 8.1.2.5-1: Attributes of ServiceLivenessUpdate
err := errors.New("Wrong body content")
errHandlerProblemDetails(w, err.Error(), http.StatusBadRequest)
return
}
entry.TimeStamp = &ServiceLivenessInfoTimeStamp{
Seconds: 0,
}
fmt.Fprint(w, convertServiceLivenessInfoToJson(&entry))
livenessTimerList[serInstanceId] = entry
}
// Send response