-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathdb.go
444 lines (378 loc) · 13.6 KB
/
db.go
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
// SPDX-FileCopyrightText: 2022-present Intel Corporation
// SPDX-FileCopyrightText: 2021 Open Networking Foundation <[email protected]>
// Copyright 2019 free5GC.org
//
// SPDX-License-Identifier: Apache-2.0
//
package context
import (
"encoding/json"
"fmt"
"net"
"os"
"reflect"
"strconv"
"sync"
"github.com/omec-project/smf/factory"
"github.com/omec-project/smf/logger"
"github.com/omec-project/util/idgenerator"
"github.com/omec-project/util/mongoapi"
"go.mongodb.org/mongo-driver/bson"
)
const (
SmContextDataColl = "smf.data.smContext"
// TransactionDataCol = "smf.data.transaction"
SeidSmContextCol = "smf.data.seidSmContext"
NodeInDBCol = "smf.data.nodeInDB"
// SMPolicyClientCol = "smf.data.smPolicyClient"
RefSeidCol = "smf.data.refToSeid"
SmfCounterCol = "smf.data.smfCount"
)
func SetupSmfCollection() {
dbName := "sdcore_smf"
dbUrl := "mongodb://mongodb-arbiter-headless"
if factory.SmfConfig.Configuration.Mongodb.Url != "" {
dbUrl = factory.SmfConfig.Configuration.Mongodb.Url
}
if factory.SmfConfig.Configuration.SmfDbName != "" {
dbName = factory.SmfConfig.Configuration.SmfDbName
}
logger.CfgLog.Infof("initialising db name [%v] url [%v]", dbName, dbUrl)
// UUID table
mongoapi.ConnectMongo(dbUrl, dbName)
_, err := mongoapi.CommonDBClient.CreateIndex(SmContextDataColl, "ref")
if err != nil {
logger.DataRepoLog.Errorln("create index failed on ref field")
}
// SEID Table
_, err = mongoapi.CommonDBClient.CreateIndex(SeidSmContextCol, "seid")
if err != nil {
logger.DataRepoLog.Errorln("create index failed on TxnId field")
}
smfCount := mongoapi.CommonDBClient.GetUniqueIdentity("smfCount")
logger.DataRepoLog.Infof("unique id - init smfCount %d", smfCount)
// set os env
setEnvErr := os.Setenv("SMF_COUNT", strconv.Itoa(int(smfCount)))
if setEnvErr != nil {
logger.DataRepoLog.Errorln("setting SMF_COUNT env variable is failed")
}
}
// print out sm context
func (smContext *SMContext) String() string {
return fmt.Sprintf("smContext content: Ref:[%v],\nSupi: [%v],\nPei:[%v],\nGpsi:[%v],\nPDUSessionID:[%v],\nDnn:[%v],Snssai: [%v],\nHplmnSnssai: [%v],\nServingNetwork: [%v],\nServingNfId: [%v],\nUpCnxState: [%v],\nAnType: [%v],\nRatType: [%v],\nPDUAddress: [%v],\nSelectedPDUSessionType: [%v],\nSmStatusNotifyUri: [%v],\nSelectedPCFProfile: [%v],\nSMContextState: [%v],\nTunnel: [%v],\nPFCPContext: [%v],\nIdentifier: [%v],\nDNNInfo: [%v],\nSmPolicyData: [%v],\nEstAcceptCause5gSMValue: [%v]\n", smContext.Ref, smContext.Supi, smContext.Pei, smContext.Gpsi, smContext.PDUSessionID, smContext.Dnn, smContext.Snssai, smContext.HplmnSnssai, smContext.ServingNetwork, smContext.ServingNfId, smContext.UpCnxState, smContext.AnType, smContext.RatType, smContext.PDUAddress, smContext.SelectedPDUSessionType, smContext.SmStatusNotifyUri, smContext.SelectedPCFProfile, smContext.SMContextState, smContext.Tunnel, smContext.PFCPContext, smContext.Identifier, smContext.DNNInfo, smContext.SmPolicyData, smContext.EstAcceptCause5gSMValue)
}
// MarshalJSON customized marshaller for sm context
func (smContext *SMContext) MarshalJSON() ([]byte, error) {
type Alias SMContext
dataPathPoolInDBVal := make(map[int64]*DataPathInDB)
var dataPathInDBIf interface{}
var FirstDPNodeIf interface{}
var upTunnelVal UPTunnelInDB
if smContext.Tunnel != nil {
upTunnelVal.ANInformation = smContext.Tunnel.ANInformation
if smContext.Tunnel.DataPathPool != nil {
for key, val := range smContext.Tunnel.DataPathPool {
dataPathInDBIf = val
dataPath := dataPathInDBIf.(*DataPath)
firstDPNode := dataPath.FirstDPNode
FirstDPNodeIf = firstDPNode
dataPathNode := FirstDPNodeIf.(*DataPathNode)
dataPathNodeInDBVal := StoreDataPathNode(dataPathNode)
newDataPathInDB := &DataPathInDB{
Activated: dataPath.Activated,
IsDefaultPath: dataPath.IsDefaultPath,
Destination: dataPath.Destination,
HasBranchingPoint: dataPath.HasBranchingPoint,
FirstDPNode: dataPathNodeInDBVal,
}
dataPathPoolInDBVal[key] = newDataPathInDB
}
upTunnelVal.DataPathPool = dataPathPoolInDBVal
}
}
var pfcpSessionContextInDB PFCPSessionContextInDB
PFCPContextVal := make(PFCPContextInDB)
// store localseid and remoteseid
for key, pfcpCtx := range smContext.PFCPContext {
pfcpSessionContextInDB.NodeID = pfcpCtx.NodeID
pfcpSessionContextInDB.PDRs = pfcpCtx.PDRs
pfcpSessionContextInDB.LocalSEID = SeidConv(pfcpCtx.LocalSEID)
pfcpSessionContextInDB.RemoteSEID = SeidConv(pfcpCtx.RemoteSEID)
PFCPContextVal[key] = pfcpSessionContextInDB
}
return json.Marshal(&struct {
*Alias
PFCPContext PFCPContextInDB `json:"pfcpContext"`
Tunnel UPTunnelInDB `json:"tunnel"`
}{
Alias: (*Alias)(smContext),
PFCPContext: PFCPContextVal,
Tunnel: upTunnelVal,
})
}
// UnmarshalJSON customized unmarshaller for sm context
func (smContext *SMContext) UnmarshalJSON(data []byte) error {
logger.DataRepoLog.Infoln("db - in UnmarshalJSON")
type Alias SMContext
aux := &struct {
*Alias
PFCPContextVal PFCPContextInDB `json:"pfcpContext"`
Tunnel UPTunnelInDB `json:"tunnel"`
}{
Alias: (*Alias)(smContext),
}
if err := json.Unmarshal(data, &aux); err != nil {
logger.DataRepoLog.Errorln("err in customized unMarshall")
return err
}
// recover smContext.PFCPContext
smContext.PFCPContext = make(map[string]*PFCPSessionContext)
for key, pfcpCtxInDB := range aux.PFCPContextVal {
smContext.PFCPContext[key] = &PFCPSessionContext{}
smContext.PFCPContext[key].NodeID = pfcpCtxInDB.NodeID
smContext.PFCPContext[key].PDRs = pfcpCtxInDB.PDRs
localSeid, err := strconv.ParseUint(pfcpCtxInDB.LocalSEID, 16, 64)
if err != nil {
logger.DataRepoLog.Errorf("localSEID unmarshall error: %v", err)
}
smContext.PFCPContext[key].LocalSEID = localSeid
remoteSeid, err := strconv.ParseUint(pfcpCtxInDB.RemoteSEID, 16, 64)
if err != nil {
logger.DataRepoLog.Errorf("remoteSEID unmarshall error: %v", err)
}
smContext.PFCPContext[key].RemoteSEID = remoteSeid
}
var dataPathInDBIf interface{}
var FirstDPNodeIf interface{}
smContext.Tunnel = &UPTunnel{}
if !reflect.DeepEqual(aux.Tunnel, UPTunnelInDB{}) {
smContext.Tunnel.ANInformation = aux.Tunnel.ANInformation
smContext.Tunnel.PathIDGenerator = idgenerator.NewGenerator(1, 2147483647)
smContext.Tunnel.DataPathPool = NewDataPathPool()
for key, val := range aux.Tunnel.DataPathPool {
dataPathInDBIf = val
dataPathInDB := dataPathInDBIf.(*DataPathInDB)
firstDPNode := dataPathInDB.FirstDPNode
FirstDPNodeIf = firstDPNode
dataPathNodeInDBVal := FirstDPNodeIf.(*DataPathNodeInDB)
dataPathNodeVal := RecoverDataPathNode(dataPathNodeInDBVal)
newDataPath := NewDataPath()
newDataPath.Activated = dataPathInDB.Activated
newDataPath.IsDefaultPath = dataPathInDB.IsDefaultPath
newDataPath.Destination = dataPathInDB.Destination
newDataPath.HasBranchingPoint = dataPathInDB.HasBranchingPoint
newDataPath.FirstDPNode = dataPathNodeVal
smContext.Tunnel.DataPathPool[key] = newDataPath
}
}
// recover logs
smContext.initLogTags()
// recover SBIPFCPCommunicationChan
smContext.SBIPFCPCommunicationChan = make(chan PFCPSessionResponseStatus, 1)
return nil
}
func ToBsonMSeidRef(data SeidSmContextRef) (ret bson.M) {
// Marshal data into json format
tmp, err := json.Marshal(data)
if err != nil {
logger.DataRepoLog.Errorf("SMContext marshall error: %v", err)
}
// unmarshal data into bson format
err = json.Unmarshal(tmp, &ret)
if err != nil {
logger.DataRepoLog.Errorf("SMContext unmarshall error: %v", err)
}
return
}
func ToBsonM(data *SMContext) (ret bson.M) {
// Marshal data into json format
logger.DataRepoLog.Infoln("db - in ToBsonM before marshal")
tmp, err := json.Marshal(data)
if err != nil {
logger.DataRepoLog.Errorf("SMContext marshall error: %v", err)
}
// unmarshal data into bson format
err = json.Unmarshal(tmp, &ret)
if err != nil {
logger.DataRepoLog.Errorf("SMContext unmarshall error: %v", err)
}
return
}
// StoreSmContextInDB Store SmContext In DB
func StoreSmContextInDB(smContext *SMContext) {
logger.DataRepoLog.Infoln("db - Store SMContext In DB w ref")
smContext.SMLock.Lock()
defer smContext.SMLock.Unlock()
smContextBsonA := ToBsonM(smContext)
filter := bson.M{"ref": smContext.Ref}
logger.DataRepoLog.Infof("filter: %+v", filter)
_, postErr := mongoapi.CommonDBClient.RestfulAPIPost(SmContextDataColl, filter, smContextBsonA)
if postErr != nil {
logger.DataRepoLog.Warnln(postErr)
}
}
type SeidSmContextRef struct {
Ref string `json:"ref" yaml:"ref" bson:"ref"`
Seid string `json:"seid" yaml:"seid" bson:"seid"`
}
func SeidConv(seid uint64) (seidStr string) {
seidStr = strconv.FormatUint(seid, 16)
return seidStr
}
// StoreSeidContextInDB Store Context by SEID In DB
func StoreSeidContextInDB(seidUint uint64, smContext *SMContext) {
seid := SeidConv(seidUint)
item := SeidSmContextRef{
Ref: smContext.Ref,
Seid: seid,
}
itemBsonA := ToBsonMSeidRef(item)
filter := bson.M{"seid": seid}
logger.DataRepoLog.Infof("filter: %+v", filter)
_, postErr := mongoapi.CommonDBClient.RestfulAPIPost(SeidSmContextCol, filter, itemBsonA)
if postErr != nil {
logger.DataRepoLog.Warnln(postErr)
}
}
// StoreRefToSeidInDB store mapping ref to seid in db
func StoreRefToSeidInDB(seidUint uint64, smContext *SMContext) {
seid := SeidConv(seidUint)
item := SeidSmContextRef{
Ref: smContext.Ref,
Seid: seid,
}
itemBsonA := ToBsonMSeidRef(item)
filter := bson.M{"ref": smContext.Ref}
logger.DataRepoLog.Infof("filter: %+v", filter)
_, postErr := mongoapi.CommonDBClient.RestfulAPIPost(RefSeidCol, filter, itemBsonA)
if postErr != nil {
logger.DataRepoLog.Warnln(postErr)
}
}
func GetSeidByRefInDB(ref string) (seid uint64) {
filter := bson.M{}
filter["ref"] = ref
result, getOneErr := mongoapi.CommonDBClient.RestfulAPIGetOne(RefSeidCol, filter)
if getOneErr != nil {
logger.DataRepoLog.Warnln(getOneErr)
}
seidStr := result["seid"].(string)
seid, err := strconv.ParseUint(seidStr, 16, 64)
if err != nil {
logger.DataRepoLog.Errorf("seid unmarshall error: %v", err)
}
return
}
// GetSMContextByRefInDB GetSMContext By Ref from DB
func GetSMContextByRefInDB(ref string) (smContext *SMContext) {
logger.DataRepoLog.Debugf("GetSMContextByRefInDB: Ref in DB %v", ref)
smContext = &SMContext{}
filter := bson.M{}
filter["ref"] = ref
result, getOneErr := mongoapi.CommonDBClient.RestfulAPIGetOne(SmContextDataColl, filter)
if getOneErr != nil {
logger.DataRepoLog.Warnln(getOneErr)
}
if result != nil {
err := json.Unmarshal(mapToByte(result), smContext)
if err != nil {
logger.DataRepoLog.Errorf("smContext unmarshall error: %v", err)
return nil
}
} else {
logger.DataRepoLog.Warnf("SmContext doesn't exist with ref: %v", ref)
return nil
}
return smContext
}
// GetSMContextBySEIDInDB GetSMContext By SEID from DB
func GetSMContextBySEIDInDB(seidUint uint64) (smContext *SMContext) {
seid := SeidConv(seidUint)
filter := bson.M{}
filter["seid"] = seid
result, getOneErr := mongoapi.CommonDBClient.RestfulAPIGetOne(SeidSmContextCol, filter)
if getOneErr != nil {
logger.DataRepoLog.Warnln(getOneErr)
}
if result != nil {
ref := result["ref"].(string)
logger.DataRepoLog.Debugln("StoreSeidContextInDB, result string:", ref)
return GetSMContext(ref)
} else {
logger.DataRepoLog.Warnf("SmContext doesn't exist with seid: %v", seid)
return nil
}
}
// DeleteSmContextInDBBySEID Delete SMContext By SEID from DB
func DeleteSmContextInDBBySEID(seidUint uint64) {
seid := SeidConv(seidUint)
logger.DataRepoLog.Infoln("db - delete SMContext In DB by seid")
filter := bson.M{"seid": seid}
logger.DataRepoLog.Infof("filter: %+v", filter)
result, getOneErr := mongoapi.CommonDBClient.RestfulAPIGetOne(SeidSmContextCol, filter)
if getOneErr != nil {
logger.DataRepoLog.Warnln(getOneErr)
}
if result != nil {
ref := result["ref"].(string)
delOneErr := mongoapi.CommonDBClient.RestfulAPIDeleteOne(SeidSmContextCol, filter)
if delOneErr != nil {
logger.DataRepoLog.Warnln(delOneErr)
}
DeleteSmContextInDBByRef(ref)
} else {
logger.DataRepoLog.Infof("DB entry doesn't exist with seid: %v", seid)
}
}
// DeleteSmContextInDBByRef Delete SMContext By ref from DB
func DeleteSmContextInDBByRef(ref string) {
logger.DataRepoLog.Infoln("db - delete SMContext In DB w ref")
filter := bson.M{"ref": ref}
logger.DataRepoLog.Infof("filter: %+v", filter)
delOneErr := mongoapi.CommonDBClient.RestfulAPIDeleteOne(SmContextDataColl, filter)
if delOneErr != nil {
logger.DataRepoLog.Warnln(delOneErr)
}
}
// ClearSMContextInMem Delete SMContext in smContextPool and seidSMContextMap, for test
func ClearSMContextInMem(ref string) {
smContext := GetSMContext(ref)
smContextPool.Delete(ref)
seid := GetSeidByRefInDB(ref)
seidSMContextMap.Delete(seid)
canonicalRef.Delete(canonicalName(smContext.Identifier, smContext.PDUSessionID))
}
func mapToByte(data map[string]interface{}) (ret []byte) {
ret, err := json.Marshal(data)
if err != nil {
logger.DataRepoLog.Errorf("map to byte error: %v", err)
}
return
}
func ShowSmContextPool() {
smContextPool.Range(func(k, v interface{}) bool {
logger.DataRepoLog.Infoln("db - iterate:", k, v)
return true
})
}
func GetSmContextPool() *sync.Map {
return &smContextPool
}
func StoreSmContextPool(smContext *SMContext) {
smContextPool.Store(smContext.Ref, smContext)
}
func GetLocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return ""
}