Code rework
[ric-plt/submgr.git] / pkg / control / sdl.go
1 /*
2 ==================================================================================
3   Copyright (c) 2019 AT&T Intellectual Property.
4   Copyright (c) 2019 Nokia
5
6    Licensed under the Apache License, Version 2.0 (the "License");
7    you may not use this file except in compliance with the License.
8    You may obtain a copy of the License at
9
10        http://www.apache.org/licenses/LICENSE-2.0
11
12    Unless required by applicable law or agreed to in writing, software
13    distributed under the License is distributed on an "AS IS" BASIS,
14    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15    See the License for the specific language governing permissions and
16    limitations under the License.
17 ==================================================================================
18 */
19
20 package control
21
22 import (
23         "encoding/json"
24         "fmt"
25         "gerrit.o-ran-sc.org/r/ric-plt/e2ap/pkg/e2ap"
26         sdl "gerrit.o-ran-sc.org/r/ric-plt/sdlgo"
27         "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/xapp"
28         "strconv"
29 )
30
31 type SubscriptionInfo struct {
32         Valid       bool
33         ReqId       RequestId
34         Meid        xapp.RMRMeid
35         EpList      xapp.RmrEndpointList
36         SubReqMsg   e2ap.E2APSubscriptionRequest
37         SubRespMsg  e2ap.E2APSubscriptionResponse
38         SubFailMsg  e2ap.E2APSubscriptionFailure
39         SubRespRcvd string
40 }
41
42 func CreateSdl() Sdlnterface {
43         return sdl.NewSdlInstance("submgr", sdl.NewDatabase())
44 }
45
46 func (c *Control) WriteSubscriptionToSdl(subId uint32, subs *Subscription) error {
47
48         var subscriptionInfo SubscriptionInfo
49         subscriptionInfo.Valid = subs.valid
50         subscriptionInfo.ReqId = subs.ReqId
51         subscriptionInfo.Meid = *subs.Meid
52         subscriptionInfo.EpList = subs.EpList
53         subscriptionInfo.SubReqMsg = *subs.SubReqMsg
54
55         if typeofSubsMessage(subs.SubRFMsg) == "SubResp" {
56                 subscriptionInfo.SubRespRcvd = "SubResp"
57                 subscriptionInfo.SubRespMsg = *subs.SubRFMsg.(*e2ap.E2APSubscriptionResponse)
58         } else if typeofSubsMessage(subs.SubRFMsg) == "SubFail" {
59                 subscriptionInfo.SubRespRcvd = "SubFail"
60                 subscriptionInfo.SubFailMsg = *subs.SubRFMsg.(*e2ap.E2APSubscriptionFailure)
61         } else {
62                 subscriptionInfo.SubRespRcvd = ""
63         }
64
65         jsonData, err := json.Marshal(subscriptionInfo)
66         if err != nil {
67                 return fmt.Errorf("SDL: WriteSubscriptionToSdl() json.Marshal error: %s", err.Error())
68         }
69
70         if err = c.db.Set(strconv.FormatUint(uint64(subId), 10), jsonData); err != nil {
71                 return fmt.Errorf("SDL: WriteSubscriptionToSdl(): %s", err.Error())
72         } else {
73                 xapp.Logger.Debug("SDL: Subscription written in db. subId = %v", subId)
74         }
75         return nil
76 }
77
78 func (c *Control) ReadSubscriptionFromSdl(subId uint32) (*Subscription, error) {
79
80         // This function is now just for testing purpose
81         key := strconv.FormatUint(uint64(subId), 10)
82         retMap, err := c.db.Get([]string{key})
83         if err != nil {
84                 return nil, fmt.Errorf("SDL: ReadSubscriptionFromSdl(): %s", err.Error())
85         } else {
86                 xapp.Logger.Debug("SDL: Subscription read from db.  subId = %v", subId)
87         }
88
89         subs := &Subscription{}
90         for _, iSubscriptionInfo := range retMap {
91
92                 if iSubscriptionInfo == nil {
93                         return nil, fmt.Errorf("SDL: ReadSubscriptionFromSdl() subscription not found. subId = %v\n", subId)
94                 }
95
96                 subscriptionInfo := &SubscriptionInfo{}
97                 jsonSubscriptionInfo := iSubscriptionInfo.(string)
98
99                 if err := json.Unmarshal([]byte(jsonSubscriptionInfo), subscriptionInfo); err != nil {
100                         return nil, fmt.Errorf("SDL: ReadSubscriptionFromSdl() json.unmarshal error: %s\n", err.Error())
101                 }
102
103                 subs = c.CreateSubscription(subscriptionInfo, &jsonSubscriptionInfo)
104         }
105         return subs, nil
106 }
107
108 func (c *Control) CreateSubscription(subscriptionInfo *SubscriptionInfo, jsonSubscriptionInfo *string) *Subscription {
109
110         subs := &Subscription{}
111         subs.registry = c.registry
112         subs.valid = subscriptionInfo.Valid
113         subs.ReqId = subscriptionInfo.ReqId
114         meid := xapp.RMRMeid{}
115         meid = subscriptionInfo.Meid
116         subs.Meid = &meid
117         subs.EpList = subscriptionInfo.EpList
118         subs.TheTrans = nil
119         subReq := e2ap.E2APSubscriptionRequest{}
120         subReq = subscriptionInfo.SubReqMsg
121         subs.SubReqMsg = &subReq
122
123         if subscriptionInfo.SubRespRcvd == "SubResp" {
124                 subs.SubRespRcvd = true
125                 subResp := e2ap.E2APSubscriptionResponse{}
126                 subResp = subscriptionInfo.SubRespMsg
127                 subs.SubRFMsg = &subResp
128         } else if subscriptionInfo.SubRespRcvd == "SubFail" {
129                 subs.SubRespRcvd = false
130                 subFail := e2ap.E2APSubscriptionFailure{}
131                 subFail = subscriptionInfo.SubFailMsg
132                 subs.SubRFMsg = &subFail
133         } else {
134                 subs.SubRespRcvd = false
135                 subs.SubRFMsg = nil
136                 xapp.Logger.Debug("SDL: CreateSubscription() subscriptionInfo.SubRespRcvd == '', InstanceId=%v ", subscriptionInfo.ReqId.InstanceId)
137         }
138         return subs
139 }
140
141 func (c *Control) RemoveSubscriptionFromSdl(subId uint32) error {
142
143         key := strconv.FormatUint(uint64(subId), 10)
144         if err := c.db.Remove([]string{key}); err != nil {
145                 return fmt.Errorf("SDL: RemoveSubscriptionfromSdl(): %s\n", err.Error())
146         } else {
147                 xapp.Logger.Debug("SDL: Subscription removed from db. subId = %v", subId)
148         }
149         return nil
150 }
151
152 func (c *Control) ReadAllSubscriptionsFromSdl() ([]uint32, map[uint32]*Subscription, error) {
153
154         // Read all subscriptionInfos
155         var subIds []uint32
156         var i uint32
157         for i = 1; i < 65535; i++ {
158                 subIds = append(subIds, i)
159         }
160
161         retMap := make(map[uint32]*Subscription)
162         // Get all keys
163         keys, err := c.db.GetAll()
164         if err != nil {
165                 return nil, nil, fmt.Errorf("SDL: ReadAllSubscriptionsFromSdl(), GetAll(). Error while reading keys from DBAAS %s\n", err.Error())
166         }
167
168         if len(keys) == 0 {
169                 return subIds, retMap, nil
170         }
171
172         // Get all subscriptionInfos
173         iSubscriptionMap, err := c.db.Get(keys)
174         if err != nil {
175                 return nil, nil, fmt.Errorf("SDL: ReadAllSubscriptionsFromSdl(), Get():  Error while reading subscriptions from DBAAS %s\n", err.Error())
176         }
177
178         for _, iSubscriptionInfo := range iSubscriptionMap {
179
180                 if iSubscriptionInfo == nil {
181                         return nil, nil, fmt.Errorf("SDL: ReadAllSubscriptionsFromSdl() iSubscriptionInfo = nil\n")
182                 }
183
184                 subscriptionInfo := &SubscriptionInfo{}
185                 jsonSubscriptionInfo := iSubscriptionInfo.(string)
186
187                 if err := json.Unmarshal([]byte(jsonSubscriptionInfo), subscriptionInfo); err != nil {
188                         return nil, nil, fmt.Errorf("SDL: ReadAllSubscriptionsFromSdl() json.unmarshal error: %s\n", err.Error())
189                 }
190
191                 subs := c.CreateSubscription(subscriptionInfo, &jsonSubscriptionInfo)
192
193                 if int(subscriptionInfo.ReqId.InstanceId) >= len(subIds) {
194                         return nil, nil, fmt.Errorf("SDL: ReadAllSubscriptionsFromSdl() index is out of range. Index is %d with slice length %d", subscriptionInfo.ReqId.InstanceId, len(subIds))
195                 }
196                 retMap[subscriptionInfo.ReqId.InstanceId] = subs
197
198                 // Remove subId from free subIds. Original slice is modified here!
199                 subIds, err = removeNumber(subIds, subscriptionInfo.ReqId.InstanceId)
200                 if err != nil {
201                         return nil, nil, fmt.Errorf("SDL: ReadAllSubscriptionsFromSdl() error: %s\n", err.Error())
202                 }
203         }
204         return subIds, retMap, nil
205 }
206
207 func removeNumber(s []uint32, removedNum uint32) ([]uint32, error) {
208         for i, num := range s {
209                 if removedNum == uint32(num) {
210                         s = append(s[:i], s[i+1:]...)
211                         return s[:len(s)], nil
212                 }
213         }
214         return nil, fmt.Errorf("SDL: To be removed number not in the slice. removedNum: %v", removedNum)
215 }
216 func (c *Control) RemoveAllSubscriptionsFromSdl() error {
217
218         if err := c.db.RemoveAll(); err != nil {
219                 return fmt.Errorf("SDL: RemoveAllSubscriptionsFromSdl(): %s\n", err.Error())
220         } else {
221                 xapp.Logger.Debug("SDL: All subscriptions removed from db")
222         }
223         return nil
224 }