Newer
Older
* Copyright (c) 2019 InterDigital Communications, 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 server
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
Kevin Di Lallo
committed
"os"
"time"
sbi "github.com/InterDigitalInc/AdvantEDGE/go-apps/meep-loc-serv/sbi"
appInfoClient "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-app-info-client"
appSupportClient "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-app-support-client"
Kevin Di Lallo
committed
dkm "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-data-key-mgr"
gisClient "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-gis-engine-client"
httpLog "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-http-logger"
log "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-logger"
Kevin Di Lallo
committed
met "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-metrics"
redis "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-redis"
srvMgmtClient "github.com/InterDigitalInc/AdvantEDGE/go-packages/meep-service-mgmt-client"
Simon Pastor
committed
"github.com/gorilla/mux"
)
Kevin Di Lallo
committed
const locServKey = "loc-serv:"
const logModuleLocServ = "meep-loc-serv"
const serviceName = "Location Service"
const typeZone = "zone"
const typeAccessPoint = "accessPoint"
const typeUser = "user"
const typeZonalSubscription = "zonalsubs"
const typeUserSubscription = "usersubs"
const typeZoneStatusSubscription = "zonestatus"
const typeDistanceSubscription = "distance"
const typeAreaCircleSubscription = "areacircle"
Kevin Di Lallo
committed
const (
notifZonalPresence = "ZonalPresenceNotification"
notifZoneStatus = "ZoneStatusNotification"
Kevin Di Lallo
committed
)
Kevin Di Lallo
committed
type UeUserData struct {
queryZoneId []string
queryApId []string
queryAddress []string
Kevin Di Lallo
committed
}
type ApUserData struct {
queryInterestRealm string
apList *AccessPointList
}
var nextZonalSubscriptionIdAvailable int
var nextUserSubscriptionIdAvailable int
Simon Pastor
committed
var nextZoneStatusSubscriptionIdAvailable int
var nextDistanceSubscriptionIdAvailable int
var nextAreaCircleSubscriptionIdAvailable int
var zonalSubscriptionEnteringMap = map[int]string{}
var zonalSubscriptionLeavingMap = map[int]string{}
var zonalSubscriptionTransferringMap = map[int]string{}
var zonalSubscriptionMap = map[int]string{}
var userSubscriptionEnteringMap = map[int]string{}
var userSubscriptionLeavingMap = map[int]string{}
var userSubscriptionTransferringMap = map[int]string{}
var userSubscriptionMap = map[int]string{}
Simon Pastor
committed
var zoneStatusSubscriptionMap = map[int]*ZoneStatusCheck{}
var areaCircleSubscriptionMap = map[int]*AreaCircleCheck{}
var periodicSubscriptionMap = map[int]*PeriodicCheck{}
Simon Pastor
committed
type ZoneStatusCheck struct {
ZoneId string
Serviceable bool
Unserviceable bool
Unknown bool
Simon Pastor
committed
}
NextTts int32 //next time to send, derived from frequency
NbNotificationsSent int32
NotificationCheckReady bool
Subscription *DistanceNotificationSubscription
NextTts int32 //next time to send, derived from frequency
AddrInArea map[string]bool
NbNotificationsSent int32
NotificationCheckReady bool
Subscription *CircleNotificationSubscription
type PeriodicCheck struct {
NextTts int32 //next time to send, derived from frequency
Subscription *PeriodicNotificationSubscription
}
Kevin Di Lallo
committed
var LOC_SERV_DB = 0
var redisAddr string = "meep-redis-master.default.svc.cluster.local:6379"
var influxAddr string = "http://meep-influxdb.default.svc.cluster.local:8086"
Kevin Di Lallo
committed
var hostUrl *url.URL
Kevin Di Lallo
committed
var sandboxName string
Kevin Di Lallo
committed
var basePath string
Kevin Di Lallo
committed
var baseKey string
Simon Pastor
committed
var gisAppClientUrl string = "http://meep-gis-engine"
//MEC011 section begin
const serviceAppName = "Location"
const serviceAppVersion = "2.1.1"
var serviceAppInstanceId string
var appEnablementClientUrl string = "http://meep-app-enablement"
var appEnablementAppSupportClient *appSupportClient.APIClient
var sendAppTerminationWhenDone bool = false
var retryAppEnablementTicker *time.Ticker
//MEC011 section end
func notImplemented(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusNotImplemented)
}
// Init - Location Service initialization
func Init() (err error) {
sandboxNameEnv := strings.TrimSpace(os.Getenv("MEEP_SANDBOX_NAME"))
if sandboxNameEnv != "" {
sandboxName = sandboxNameEnv
}
if sandboxName == "" {
err = errors.New("MEEP_SANDBOX_NAME env variable not set")
log.Error(err.Error())
return err
}
log.Info("MEEP_SANDBOX_NAME: ", sandboxName)
Kevin Di Lallo
committed
// hostUrl is the url of the node serving the resourceURL
// Retrieve public url address where service is reachable, if not present, use Host URL environment variable
hostUrl, err = url.Parse(strings.TrimSpace(os.Getenv("MEEP_PUBLIC_URL")))
if err != nil || hostUrl == nil || hostUrl.String() == "" {
hostUrl, err = url.Parse(strings.TrimSpace(os.Getenv("MEEP_HOST_URL")))
if err != nil {
hostUrl = new(url.URL)
}
Kevin Di Lallo
committed
}
Kevin Di Lallo
committed
// Set base path
basePath = "/" + sandboxName + LocServBasePath
Kevin Di Lallo
committed
Kevin Di Lallo
committed
// Get base storage key
baseKey = dkm.GetKeyRoot(sandboxName) + locServKey
Kevin Di Lallo
committed
// Connect to Redis DB
_ = rc.DBFlush(baseKey)
gisAppClientCfg.BasePath = gisAppClientUrl + "/gis/v1"
gisAppClient = gisClient.NewAPIClient(gisAppClientCfg)
if gisAppClient == nil {
log.Error("Failed to create GIS App REST API client: ", gisAppClientCfg.BasePath)
err := errors.New("Failed to create GIS App REST API client")
return err
}
userTrackingReInit()
zonalTrafficReInit()
Simon Pastor
committed
zoneStatusReInit()
Kevin Di Lallo
committed
// Initialize SBI
sbiCfg := sbi.SbiCfg{
SandboxName: sandboxName,
RedisAddr: redisAddr,
UserInfoCb: updateUserInfo,
ZoneInfoCb: updateZoneInfo,
ApInfoCb: updateAccessPointInfo,
ScenarioNameCb: updateStoreName,
CleanUpCb: cleanUp,
}
err = sbi.Init(sbiCfg)
if err != nil {
log.Error("Failed initialize SBI. Error: ", err)
return err
}
log.Info("SBI Initialized")
//register using MEC011
if appEnablementSupport {
//delay startup on purpose to give time for appEnablement pod to come up (if all coming up at the same time)
time.Sleep(2 * time.Second)
retryAppEnablementTicker = time.NewTicker(time.Second)
go func() {
for range retryAppEnablementTicker.C {
if serviceAppInstanceId == "" {
serviceAppInstanceId = getAppInstanceId(serviceAppName, serviceAppVersion)
}
if serviceAppInstanceId != "" {
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
//sending app is ready
if !mecAppReadySent {
err := appEnablementMecAppReady(serviceAppInstanceId)
if err != nil {
log.Error("Failure when sending the MecAppReady message, keep trying. Error: ", err)
continue
} else {
mecAppReadySent = true
}
}
if !registrationSent {
err := appEnablementRegistration(serviceAppInstanceId, serviceAppName, serviceAppVersion)
if err != nil {
log.Error("Failed to register to appEnablement DB, keep trying. Error: ", err)
continue
} else {
registrationSent = true
}
/* err = appEnablementAppSupportSubscribe(serviceAppInstanceId)
if err != nil {
log.Error("Failed to subscribe to graceful termination. Error: ", err)
}
sendAppTerminationWhenDone = true
*/
}
if mecAppReadySent && registrationSent {
retryAppEnablementTicker.Stop()
}
}
}
}()
}
Kevin Di Lallo
committed
return nil
Kevin Di Lallo
committed
}
Kevin Di Lallo
committed
func Run() (err error) {
Kevin Di Lallo
committed
return sbi.Run()
if appEnablementSupport {
retryAppEnablementTicker.Stop()
if sendAppTerminationWhenDone {
err = appEnablementMecAppTermination(serviceAppInstanceId)
if err != nil {
return err
}
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
}
}
return nil
}
func appEnablementMecAppReady(appInstanceId string) error {
appEnablementAppSupportClientCfg := appSupportClient.NewConfiguration()
appEnablementAppSupportClientCfg.BasePath = appEnablementClientUrl + "/mec_app_support/v1"
appEnablementAppSupportClient = appSupportClient.NewAPIClient(appEnablementAppSupportClientCfg)
if appEnablementAppSupportClient == nil {
log.Error("Failed to create App Enablement App Support REST API client: ", appEnablementAppSupportClientCfg.BasePath)
err := errors.New("Failed to create App Enablement AppSupport REST API client")
return err
}
var appReady appSupportClient.AppReadyConfirmation
//indication
indication := appSupportClient.READY_ReadyIndicationType
appReady.Indication = &indication
_, err := appEnablementAppSupportClient.AppConfirmReadyApi.ApplicationsConfirmReadyPOST(context.TODO(), appReady, appInstanceId)
if err != nil {
log.Error("Failed to send a ready confirm acknowlegement: ", err)
return err
}
return nil
}
func appEnablementMecAppTermination(appInstanceId string) error {
if appEnablementAppSupportClient == nil {
log.Error("App Enablement App Support REST API client should already exist")
err := errors.New("App Enablement App Support REST API client should already exist")
return err
}
var appTermination appSupportClient.AppTerminationConfirmation
//operation action
operationAction := appSupportClient.TERMINATING_OperationActionType
appTermination.OperationAction = &operationAction
_, err := appEnablementAppSupportClient.AppConfirmTerminationApi.ApplicationsConfirmTerminationPOST(context.TODO(), appTermination, appInstanceId)
if err != nil {
log.Error("Failed to send a confirm termination acknowlegement: ", err)
return err
}
return nil
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
func getAppInstanceId(appName string, appVersion string) string {
//var client *appInfoClient.APIClient
appInfoClientCfg := appInfoClient.NewConfiguration()
appInfoClientCfg.BasePath = appEnablementClientUrl + "/app_info/v1"
client := appInfoClient.NewAPIClient(appInfoClientCfg)
if client == nil {
log.Error("Failed to create App Info REST API client: ", appInfoClientCfg.BasePath)
return ""
}
var appInfo appInfoClient.ApplicationInfo
appInfo.AppName = appName
appInfo.Version = appVersion
state := appInfoClient.INACTIVE_ApplicationState
appInfo.State = &state
appInfoResponse, _, err := client.AppsApi.ApplicationsPOST(context.TODO(), appInfo)
if err != nil {
log.Error("Failed to communicate with app enablement service: ", err)
return ""
}
return appInfoResponse.AppInstanceId
}
func appEnablementRegistration(appInstanceId string, appName string, appVersion string) error {
appEnablementSrvMgmtClientCfg := srvMgmtClient.NewConfiguration()
appEnablementSrvMgmtClientCfg.BasePath = appEnablementClientUrl + "/mec_service_mgmt/v1"
appEnablementSrvMgmtClient = srvMgmtClient.NewAPIClient(appEnablementSrvMgmtClientCfg)
if appEnablementSrvMgmtClient == nil {
log.Error("Failed to create App Enablement Srv Mgmt REST API client: ", appEnablementSrvMgmtClientCfg.BasePath)
err := errors.New("Failed to create App Enablement Srv Mgmt REST API client")
return err
}
var srvInfo srvMgmtClient.ServiceInfoPost
//serName
srvInfo.SerName = appName
//version
srvInfo.Version = appVersion
//state
state := srvMgmtClient.ACTIVE_ServiceState
srvInfo.State = &state
//serializer
serializer := srvMgmtClient.JSON_SerializerType
srvInfo.Serializer = &serializer
//transportInfo
var transportInfo srvMgmtClient.TransportInfo
transportInfo.Id = "transport"
transportInfo.Name = "REST"
transportType := srvMgmtClient.REST_HTTP_TransportType
transportInfo.Type_ = &transportType
transportInfo.Protocol = "HTTP"
transportInfo.Version = "2.0"
var endpoint srvMgmtClient.OneOfTransportInfoEndpoint
endpointPath := hostUrl.String() + basePath
endpoint.Uris = append(endpoint.Uris, endpointPath)
transportInfo.Endpoint = &endpoint
srvInfo.TransportInfo = &transportInfo
//serCategory
var category srvMgmtClient.CategoryRef
category.Href = "catalogueHref"
category.Id = "locationId"
category.Name = "Location"
category.Version = "v2"
srvInfo.SerCategory = &category
//scopeOfLocality
scopeOfLocality := srvMgmtClient.MEC_SYSTEM_LocalityType
srvInfo.ScopeOfLocality = &scopeOfLocality
//consumedLocalOnly
srvInfo.ConsumedLocalOnly = false
appServicesPostResponse, _, err := appEnablementSrvMgmtClient.AppServicesApi.AppServicesPOST(context.TODO(), srvInfo, appInstanceId)
if err != nil {
log.Error("Failed to register the service to app enablement registry: ", err)
return err
}
log.Info("Application Enablement Service instance Id: ", appServicesPostResponse.SerInstanceId)
return nil
}
/*
func appEnablementAppSupportSubscribe(appInstanceId string) error {
if appEnablementAppSupportClient == nil {
log.Error("App Enablement App Support REST API client should already exist")
err := errors.New("App Enablement App Support REST API client should already exist")
return err
}
var appTerminationNotificationSubscription appSupportClient.AppTerminationNotificationSubscription
//operation action
appTerminationNotificationSubscription.SubscriptionType = "AppTerminationNotificationSubscription"
appTerminationNotificationSubscription.AppInstanceId = appInstanceId
appTerminationNotificationSubscription.CallbackReference = hostUrl.String() + basePath
_, _, err := appEnablementAppSupportClient.AppSubscriptionsApi.ApplicationsSubscriptionsPOST(context.TODO(), appTerminationNotificationSubscription, appInstanceId)
if err != nil {
log.Error("Failed to register to App Support subscription: ", err)
return err
}
return nil
}
*/
Simon Pastor
committed
func deregisterZoneStatus(subsIdStr string) {
if err != nil {
log.Error(err)
}
Simon Pastor
committed
}
func registerZoneStatus(zoneId string, nbOfUsersZoneThreshold int32, nbOfUsersAPThreshold int32, opStatus []OperationStatus, subsIdStr string) {
Simon Pastor
committed
if err != nil {
log.Error(err)
}
Simon Pastor
committed
var zoneStatus ZoneStatusCheck
if opStatus != nil {
for i := 0; i < len(opStatus); i++ {
switch opStatus[i] {
case SERVICEABLE:
zoneStatus.Serviceable = true
case UNSERVICEABLE:
zoneStatus.Unserviceable = true
case OPSTATUS_UNKNOWN:
zoneStatus.Unknown = true
default:
}
}
}
zoneStatus.NbUsersInZoneThreshold = nbOfUsersZoneThreshold
zoneStatus.NbUsersInAPThreshold = nbOfUsersAPThreshold
Simon Pastor
committed
zoneStatus.ZoneId = zoneId
Simon Pastor
committed
zoneStatusSubscriptionMap[subsId] = &zoneStatus
}
func deregisterZonal(subsIdStr string) {
subsId, err := strconv.Atoi(subsIdStr)
if err != nil {
log.Error(err)
}
zonalSubscriptionMap[subsId] = ""
zonalSubscriptionEnteringMap[subsId] = ""
zonalSubscriptionLeavingMap[subsId] = ""
zonalSubscriptionTransferringMap[subsId] = ""
func registerZonal(zoneId string, event []UserEventType, subsIdStr string) {
if err != nil {
log.Error(err)
}
if event != nil {
for i := 0; i < len(event); i++ {
switch event[i] {
zonalSubscriptionEnteringMap[subsId] = zoneId
zonalSubscriptionLeavingMap[subsId] = zoneId
zonalSubscriptionTransferringMap[subsId] = zoneId
default:
}
}
} else {
zonalSubscriptionEnteringMap[subsId] = zoneId
zonalSubscriptionLeavingMap[subsId] = zoneId
zonalSubscriptionTransferringMap[subsId] = zoneId
}
zonalSubscriptionMap[subsId] = zoneId
}
func deregisterUser(subsIdStr string) {
if err != nil {
log.Error(err)
}
userSubscriptionMap[subsId] = ""
userSubscriptionEnteringMap[subsId] = ""
userSubscriptionLeavingMap[subsId] = ""
userSubscriptionTransferringMap[subsId] = ""
func registerUser(userAddress string, event []UserEventType, subsIdStr string) {
if err != nil {
log.Error(err)
}
if event != nil {
for i := 0; i < len(event); i++ {
switch event[i] {
userSubscriptionEnteringMap[subsId] = userAddress
userSubscriptionLeavingMap[subsId] = userAddress
userSubscriptionTransferringMap[subsId] = userAddress
default:
}
}
} else {
userSubscriptionEnteringMap[subsId] = userAddress
userSubscriptionLeavingMap[subsId] = userAddress
userSubscriptionTransferringMap[subsId] = userAddress
}
userSubscriptionMap[subsId] = userAddress
}
func updateNotificationAreaCirclePeriodicTrigger() {
//only check if there is at least one subscription
mutex.Lock()
defer mutex.Unlock()
for _, areaCircleCheck := range areaCircleSubscriptionMap {
if areaCircleCheck != nil {
if areaCircleCheck.NextTts != 0 {
areaCircleCheck.NextTts--
}
if areaCircleCheck.NextTts == 0 {
areaCircleCheck.NotificationCheckReady = true
} else {
areaCircleCheck.NotificationCheckReady = false
}
}
}
}
func checkNotificationDistancePeriodicTrigger() {
//only check if there is at least one subscription
mutex.Lock()
defer mutex.Unlock()
//check all that applies
for subsId, distanceCheck := range distanceSubscriptionMap {
if distanceCheck != nil && distanceCheck.Subscription != nil {
if distanceCheck.Subscription.Count == 0 || (distanceCheck.Subscription.Count != 0 && distanceCheck.NbNotificationsSent < distanceCheck.Subscription.Count) {
if distanceCheck.NextTts != 0 {
distanceCheck.NextTts--
}
if distanceCheck.NextTts == 0 {
distanceCheck.NotificationCheckReady = true
} else {
distanceCheck.NotificationCheckReady = false
}
if !distanceCheck.NotificationCheckReady {
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
//loop through every reference address
returnAddr := make(map[string]*gisClient.Distance)
skipThisSubscription := false
//if reference address is specified, reference addresses are checked agains each monitored address
//if reference address is nil, each pair of the monitored address should be checked
//creating address pairs to check
//e.g. refAddr = A, B ; monitoredAddr = C, D, E ; resultingPairs {A,C - A,D - A,E - B,C - B,D - B-E}
//e.g. monitoredAddr = A, B, C ; resultingPairs {A,B - B,A - A,C - C,A - B,C - C,B}
var addressPairs []Pair
if distanceCheck.Subscription.ReferenceAddress != nil {
for _, refAddr := range distanceCheck.Subscription.ReferenceAddress {
//loop through every monitored address
for _, monitoredAddr := range distanceCheck.Subscription.MonitoredAddress {
pair := Pair{addr1: refAddr, addr2: monitoredAddr}
addressPairs = append(addressPairs, pair)
}
}
} else {
nbIndex := len(distanceCheck.Subscription.MonitoredAddress)
for i := 0; i < nbIndex-1; i++ {
for j := i + 1; j < nbIndex; j++ {
pair := Pair{addr1: distanceCheck.Subscription.MonitoredAddress[i], addr2: distanceCheck.Subscription.MonitoredAddress[j]}
addressPairs = append(addressPairs, pair)
//need pair to be symmetrical so that each is used as reference point and monitored address
pair = Pair{addr1: distanceCheck.Subscription.MonitoredAddress[j], addr2: distanceCheck.Subscription.MonitoredAddress[i]}
addressPairs = append(addressPairs, pair)
}
for _, pair := range addressPairs {
refAddr := pair.addr1
monitoredAddr := pair.addr2
//check if one of the address if both addresses are connected, if not, disregard this pair
if !addressConnectedMap[refAddr] || !addressConnectedMap[monitoredAddr] {
//ignore that pair and continue processing
continue
}
var distParam gisClient.TargetPoint
distParam.AssetName = monitoredAddr
distResp, httpResp, err := gisAppClient.GeospatialDataApi.GetDistanceGeoDataByName(context.TODO(), refAddr, distParam)
if err != nil {
//getting distance of an element that is not in the DB (not in scenario, not connected) returns error code 400 (bad parameters) in the API. Using that error code to track that request made it to GIS but no good result, so ignore that address (monitored or ref)
//ignore that pair and continue processing
continue
} else {
log.Error("Failed to communicate with gis engine: ", err)
return
}
}
switch *distanceCheck.Subscription.Criteria {
case ALL_WITHIN_DISTANCE:
if float32(distance) < distanceCheck.Subscription.Distance {
returnAddr[monitoredAddr] = &distResp
} else {
skipThisSubscription = true
}
case ALL_BEYOND_DISTANCE:
if float32(distance) > distanceCheck.Subscription.Distance {
returnAddr[monitoredAddr] = &distResp
} else {
skipThisSubscription = true
}
case ANY_WITHIN_DISTANCE:
if float32(distance) < distanceCheck.Subscription.Distance {
returnAddr[monitoredAddr] = &distResp
}
case ANY_BEYOND_DISTANCE:
if float32(distance) > distanceCheck.Subscription.Distance {
returnAddr[monitoredAddr] = &distResp
}
default:
if len(returnAddr) > 0 {
//update nb of notification sent anch check if valid
subsIdStr := strconv.Itoa(subsId)
var distanceNotif SubscriptionNotification
distanceNotif.DistanceCriteria = distanceCheck.Subscription.Criteria
distanceNotif.IsFinalNotification = false
distanceNotif.Link = distanceCheck.Subscription.Link
var terminalLocationList []TerminalLocation
for terminalAddr, distanceInfo := range returnAddr {
var terminalLocation TerminalLocation
terminalLocation.Address = terminalAddr
var locationInfo LocationInfo
locationInfo.Latitude = nil
locationInfo.Latitude = append(locationInfo.Latitude, distanceInfo.DstLatitude)
locationInfo.Longitude = append(locationInfo.Longitude, distanceInfo.DstLongitude)
locationInfo.Shape = 2
seconds := time.Now().Unix()
var timestamp TimeStamp
timestamp.Seconds = int32(seconds)
locationInfo.Timestamp = ×tamp
terminalLocation.CurrentLocation = &locationInfo
retrievalStatus := RETRIEVED
terminalLocation.LocationRetrievalStatus = &retrievalStatus
terminalLocationList = append(terminalLocationList, terminalLocation)
}
distanceNotif.TerminalLocation = terminalLocationList
distanceNotif.CallbackData = distanceCheck.Subscription.CallbackReference.CallbackData
var inlineDistanceSubscriptionNotification InlineSubscriptionNotification
inlineDistanceSubscriptionNotification.SubscriptionNotification = &distanceNotif
distanceCheck.NbNotificationsSent++
sendSubscriptionNotification(distanceCheck.Subscription.CallbackReference.NotifyURL, inlineDistanceSubscriptionNotification)
log.Info("Distance Notification"+"("+subsIdStr+") For ", returnAddr)
distanceSubscriptionMap[subsId].NextTts = distanceCheck.Subscription.Frequency
distanceSubscriptionMap[subsId].NotificationCheckReady = false
}
}
}
}
}
func checkNotificationAreaCircle(addressToCheck string) {
//only check if there is at least one subscription
mutex.Lock()
defer mutex.Unlock()
//check all that applies
for subsId, areaCircleCheck := range areaCircleSubscriptionMap {
if areaCircleCheck != nil && areaCircleCheck.Subscription != nil {
if areaCircleCheck.Subscription.Count == 0 || (areaCircleCheck.Subscription.Count != 0 && areaCircleCheck.NbNotificationsSent < areaCircleCheck.Subscription.Count) {
//loop through every reference address
for _, addr := range areaCircleCheck.Subscription.Address {
if addr != addressToCheck {
//check if address is already inside the area or not based on the subscription
var withinRangeParam gisClient.TargetRange
withinRangeParam.Latitude = areaCircleCheck.Subscription.Latitude
withinRangeParam.Longitude = areaCircleCheck.Subscription.Longitude
withinRangeParam.Radius = areaCircleCheck.Subscription.Radius
withinRangeResp, httpResp, err := gisAppClient.GeospatialDataApi.GetWithinRangeByName(context.TODO(), addr, withinRangeParam)
if err != nil {
//getting element that is not in the DB (not in scenario, not connected) returns error code 400 (bad parameters) in the API. Using that error code to track that request made it to GIS but no good result, so ignore that address (monitored or ref)
//if the UE was within the zone, continue processing to send a LEAVING notification, otherwise, go to next subscription
if !areaCircleCheck.AddrInArea[addr] {
continue
}
} else {
log.Error("Failed to communicate with gis engine: ", err)
return
}
}
//check if there is a change
var event EnteringLeavingCriteria
if withinRangeResp.Within {
if areaCircleCheck.AddrInArea[addr] {
//no change
continue
} else {
areaCircleCheck.AddrInArea[addr] = true
event = ENTERING_CRITERIA
}
if !areaCircleCheck.AddrInArea[addr] {
//no change
continue
} else {
areaCircleCheck.AddrInArea[addr] = false
event = LEAVING_CRITERIA
}
//no tracking this event, stop looking for this UE
if *areaCircleCheck.Subscription.EnteringLeavingCriteria != event {
subsIdStr := strconv.Itoa(subsId)
var areaCircleNotif SubscriptionNotification
areaCircleNotif.EnteringLeavingCriteria = areaCircleCheck.Subscription.EnteringLeavingCriteria
areaCircleNotif.IsFinalNotification = false
areaCircleNotif.Link = areaCircleCheck.Subscription.Link
var terminalLocationList []TerminalLocation
var terminalLocation TerminalLocation
terminalLocation.Address = addr
var locationInfo LocationInfo
locationInfo.Latitude = nil
locationInfo.Latitude = append(locationInfo.Latitude, withinRangeResp.SrcLatitude)
locationInfo.Longitude = append(locationInfo.Longitude, withinRangeResp.SrcLongitude)
locationInfo.Shape = 2
seconds := time.Now().Unix()
var timestamp TimeStamp
timestamp.Seconds = int32(seconds)
locationInfo.Timestamp = ×tamp
terminalLocation.CurrentLocation = &locationInfo
retrievalStatus := RETRIEVED
terminalLocation.LocationRetrievalStatus = &retrievalStatus
terminalLocationList = append(terminalLocationList, terminalLocation)
areaCircleNotif.TerminalLocation = terminalLocationList
areaCircleNotif.CallbackData = areaCircleCheck.Subscription.CallbackReference.CallbackData
var inlineCircleSubscriptionNotification InlineSubscriptionNotification
inlineCircleSubscriptionNotification.SubscriptionNotification = &areaCircleNotif
areaCircleCheck.NbNotificationsSent++
sendSubscriptionNotification(areaCircleCheck.Subscription.CallbackReference.NotifyURL, inlineCircleSubscriptionNotification)
log.Info("Area Circle Notification" + "(" + subsIdStr + ") For " + addr + " when " + string(*areaCircleCheck.Subscription.EnteringLeavingCriteria) + " area")
areaCircleSubscriptionMap[subsId].NextTts = areaCircleCheck.Subscription.Frequency
areaCircleSubscriptionMap[subsId].NotificationCheckReady = false
func checkNotificationPeriodicTrigger() {
//only check if there is at least one subscription
mutex.Lock()
defer mutex.Unlock()
//check all that applies
for subsId, periodicCheck := range periodicSubscriptionMap {
if periodicCheck != nil && periodicCheck.Subscription != nil {
//decrement the next time to send a message
periodicCheck.NextTts--
if periodicCheck.NextTts > 0 {
continue
} else { //restart the nextTts and continue processing to send notification or not
periodicCheck.NextTts = periodicCheck.Subscription.Frequency
}
//loop through every reference address
var terminalLocationList []TerminalLocation
var periodicNotif SubscriptionNotification
for _, addr := range periodicCheck.Subscription.Address {
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
geoDataInfo, _, err := gisAppClient.GeospatialDataApi.GetGeoDataByName(context.TODO(), addr, nil)
if err != nil {
log.Error("Failed to communicate with gis engine: ", err)
return
}
var terminalLocation TerminalLocation
terminalLocation.Address = addr
var locationInfo LocationInfo
locationInfo.Latitude = nil
locationInfo.Latitude = append(locationInfo.Latitude, geoDataInfo.Location.Coordinates[1])
locationInfo.Longitude = nil
locationInfo.Longitude = append(locationInfo.Longitude, geoDataInfo.Location.Coordinates[0])
locationInfo.Shape = 2
seconds := time.Now().Unix()
var timestamp TimeStamp
timestamp.Seconds = int32(seconds)
locationInfo.Timestamp = ×tamp
terminalLocation.CurrentLocation = &locationInfo
retrievalStatus := RETRIEVED
terminalLocation.LocationRetrievalStatus = &retrievalStatus
terminalLocationList = append(terminalLocationList, terminalLocation)
}
periodicNotif.IsFinalNotification = false
periodicNotif.Link = periodicCheck.Subscription.Link
subsIdStr := strconv.Itoa(subsId)
periodicNotif.CallbackData = periodicCheck.Subscription.CallbackReference.CallbackData
periodicNotif.TerminalLocation = terminalLocationList
var inlinePeriodicSubscriptionNotification InlineSubscriptionNotification
inlinePeriodicSubscriptionNotification.SubscriptionNotification = &periodicNotif
sendSubscriptionNotification(periodicCheck.Subscription.CallbackReference.NotifyURL, inlinePeriodicSubscriptionNotification)
log.Info("Periodic Notification"+"("+subsIdStr+") For ", periodicCheck.Subscription.Address)
}
}
}
func deregisterDistance(subsIdStr string) {
subsId, err := strconv.Atoi(subsIdStr)
if err != nil {
log.Error(err)
}
mutex.Lock()
defer mutex.Unlock()
distanceSubscriptionMap[subsId] = nil
}
func registerDistance(distanceSub *DistanceNotificationSubscription, subsIdStr string) {
subsId, err := strconv.Atoi(subsIdStr)
if err != nil {
log.Error(err)
}
mutex.Lock()
defer mutex.Unlock()
var distanceCheck DistanceCheck
distanceCheck.Subscription = distanceSub
//checkImmediate ignored, will be hit on next check anyway
//if distanceSub.CheckImmediate {
distanceCheck.NextTts = 0 //next time periodic trigger hits, will be forced to trigger
//} else {
// distanceCheck.NextTts = distanceSub.Frequency
// }
distanceSubscriptionMap[subsId] = &distanceCheck
}
func deregisterAreaCircle(subsIdStr string) {
subsId, err := strconv.Atoi(subsIdStr)
if err != nil {
log.Error(err)
}
mutex.Lock()
defer mutex.Unlock()
areaCircleSubscriptionMap[subsId] = nil
}
func registerAreaCircle(areaCircleSub *CircleNotificationSubscription, subsIdStr string) {
subsId, err := strconv.Atoi(subsIdStr)
if err != nil {
log.Error(err)
}
mutex.Lock()