Skip to content

Commit

Permalink
Merge pull request #1 from enable-intelligent-containerized-5g/nwdaf_…
Browse files Browse the repository at this point in the history
…building

Nwdaf building
  • Loading branch information
edierbravo committed Jul 17, 2024
2 parents b96964e + f5a89d0 commit 6c7d733
Show file tree
Hide file tree
Showing 122 changed files with 2,633 additions and 192 deletions.
10 changes: 10 additions & 0 deletions NFs/DAP/AnLF.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from Model import *
import os.path

def AnLF(model,data_num):
if os.path.isfile('model.h5'):
model = load_model('model.h5')
prediction = model.predict(x_test[data_num:data_num+1],batch_size = 1)
print(np.argmax(prediction))
return np.argmax(prediction)

11 changes: 11 additions & 0 deletions NFs/DAP/MTLF.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from Model import *
import os.path

def MTLF(model):
if os.path.isfile('model.h5'):
model = load_model('model.h5')
print("MTLF")
print("xtrain: ", "dim: ", x_train.shape, x_train, "ytrain: ", x_test)
model.fit(x_train, y_train, epochs=2)
model.save('model.h5')
print("trainig finish")
20 changes: 20 additions & 0 deletions NFs/DAP/Model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import tensorflow as tf
import numpy as np
from tensorflow.keras.models import load_model, save_model

mnist = tf.keras.datasets.mnist
print("load data: ", mnist.load_data())

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
Binary file added NFs/DAP/__pycache__/AnLF.cpython-37.pyc
Binary file not shown.
Binary file added NFs/DAP/__pycache__/AnLF.cpython-39.pyc
Binary file not shown.
Binary file added NFs/DAP/__pycache__/MTLF.cpython-37.pyc
Binary file not shown.
Binary file added NFs/DAP/__pycache__/MTLF.cpython-39.pyc
Binary file not shown.
Binary file added NFs/DAP/__pycache__/Model.cpython-37.pyc
Binary file not shown.
Binary file added NFs/DAP/__pycache__/Model.cpython-39.pyc
Binary file not shown.
34 changes: 34 additions & 0 deletions NFs/DAP/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from flask import Flask, request
import json
from MTLF import *
from AnLF import *
from Model import *

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def parser():
data = {}
if request.method == 'POST':
data = request.json
print(data)

if str(data['nfService']) == 'training':
MTLF(model)
data["data"] = "training finish"
elif str(data['nfService']) == 'inference':
inference_result = AnLF(model,int(data['data']))
data["data"] = str(inference_result)
else:
data['data'] = "None (Wrong)"

data['reqNFInstanceID'] = data['reqNFInstanceID'] + 'hi'
data['nfService'] = data['nfService'] + '(reply)'
data['reqTime'] = data['reqTime']


return json.dumps(data)


if __name__ == '__main__':
app.run(port=9538)
Binary file added NFs/DAP/model.h5
Binary file not shown.
3 changes: 3 additions & 0 deletions NFs/DAP/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Tensorflow should be installed first

Run main.py to activate the python module
216 changes: 216 additions & 0 deletions NFs/NEF/consumer/nnrf.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
package consumer

import (
"context"
"fmt"
"net/http"
"strings"
"time"

"github.com/free5gc/openapi"
"github.com/free5gc/openapi/Nnrf_NFManagement"
"github.com/free5gc/openapi/models"
nef_context "nef.com/context"
"nef.com/factory"
"nef.com/logger"
)

func BuildNFInstance(context *nef_context.NEFContext) models.NfProfile {
var profile models.NfProfile
config := factory.NefConfig
profile.NfInstanceId = context.NfId
profile.NfType = models.NfType_NEF
profile.NfStatus = models.NfStatus_REGISTERED
version := config.Info.Version
tmpVersion := strings.Split(version, ".")
versionUri := "v" + tmpVersion[0]
apiPrefix := fmt.Sprintf("%s://%s:%d", context.UriScheme, context.RegisterIPv4, context.SBIPort)
services := []models.NfService{
{
ServiceInstanceId: "inference",
ServiceName: "nnef-inf",
Versions: &[]models.NfServiceVersion{
{
ApiFullVersion: version,
ApiVersionInUri: versionUri,
},
},
Scheme: context.UriScheme,
NfServiceStatus: models.NfServiceStatus_REGISTERED,
ApiPrefix: apiPrefix,
IpEndPoints: &[]models.IpEndPoint{
{
Ipv4Address: context.RegisterIPv4,
Transport: models.TransportProtocol_TCP,
Port: int32(context.SBIPort),
},
},
},
}
profile.NfServices = &services

return profile
}

func SendRegisterNFInstance(nrfUri, nfInstanceId string, profile models.NfProfile) (string, string, error) {
// Set client and set url
configuration := Nnrf_NFManagement.NewConfiguration()
configuration.SetBasePath(nrfUri)
client := Nnrf_NFManagement.NewAPIClient(configuration)
var resouceNrfUri string
var retrieveNfInstanceId string

for {
_, res, err := client.NFInstanceIDDocumentApi.RegisterNFInstance(context.TODO(), nfInstanceId, profile)
if err != nil || res == nil {
// TODO : add log
fmt.Println(fmt.Errorf("NEF register to NRF Error[%s]", err.Error()))
time.Sleep(2 * time.Second)
continue
}
defer func() {
if rspCloseErr := res.Body.Close(); rspCloseErr != nil {
logger.ConsumerLog.Errorf("RegisterNFInstance response body cannot close: %+v", rspCloseErr)
}
}()

status := res.StatusCode
if status == http.StatusOK {
// NFUpdate
return resouceNrfUri, retrieveNfInstanceId, err
} else if status == http.StatusCreated {
// NFRegister
resourceUri := res.Header.Get("Location")
resouceNrfUri = resourceUri[:strings.Index(resourceUri, "/nnrf-nfm/")]
retrieveNfInstanceId = resourceUri[strings.LastIndex(resourceUri, "/")+1:]
return resouceNrfUri, retrieveNfInstanceId, err
} else {
fmt.Println("handler returned wrong status code", status)
fmt.Println("NRF return wrong status code", status)
}
}
}

func SendDeregisterNFInstance() (problemDetails *models.ProblemDetails, err error) {
logger.ConsumerLog.Infof("Send Deregister NFInstance")

nefSelf := nef_context.NEF_Self()
// Set client and set url
configuration := Nnrf_NFManagement.NewConfiguration()
configuration.SetBasePath(nefSelf.NrfUri)
client := Nnrf_NFManagement.NewAPIClient(configuration)

var res *http.Response

res, err = client.NFInstanceIDDocumentApi.DeregisterNFInstance(context.Background(), nefSelf.NfId)
if err == nil {
return
} else if res != nil {
defer func() {
if rspCloseErr := res.Body.Close(); rspCloseErr != nil {
logger.ConsumerLog.Errorf("DeregisterNFInstance response body cannot close: %+v", rspCloseErr)
}
}()

if res.Status != err.Error() {
return
}
problem := err.(openapi.GenericOpenAPIError).Model().(models.ProblemDetails)
problemDetails = &problem
} else {
err = openapi.ReportError("server no response")
}
return
}

// func SendNFRegistration() error {

// // set nfProfile
// profile := models.NfProfile{
// NfInstanceId: nef_context.NEF_Self().NfInstanceID,
// NfType: "NEF",
// NfStatus: models.NfStatus_REGISTERED,
// Ipv4Addresses: []string{nef_context.NEF_Self().RegisterIPv4},
// }
// var rep models.NfProfile
// var res *http.Response
// var err error

// configuration := Nnrf_NFManagement.NewConfiguration()
// configuration.SetBasePath("http://127.0.0.10:8000")
// client := Nnrf_NFManagement.NewAPIClient(configuration)

// // Check data (Use RESTful PUT)
// for {
// rep, res, err = client.
// NFInstanceIDDocumentApi.
// RegisterNFInstance(context.TODO(), nef_context.NEF_Self().NfInstanceID, profile)
// if err != nil || res == nil {
// logger.ConsumerLog.Infof("NEF register to NRF Error[%s]", err.Error())
// time.Sleep(2 * time.Second)
// continue
// }
// defer func() {
// if resCloseErr := res.Body.Close(); resCloseErr != nil {
// logger.ConsumerLog.Errorf("RegisterNFInstance response body cannot close: %+v", resCloseErr)
// }
// }()

// status := res.StatusCode
// if status == http.StatusOK {
// // NFUpdate
// logger.ConsumerLog.Infof("handler returned status code %d", status)
// break
// } else if status == http.StatusCreated {
// // NFRegister
// resourceUri := res.Header.Get("Location")
// // resouceNrfUri := resourceUri[strings.LastIndex(resourceUri, "/"):]
// nef_context.NEF_Self().NfInstanceID = resourceUri[strings.LastIndex(resourceUri, "/")+1:]
// break
// } else {
// logger.ConsumerLog.Infof("handler returned wrong status code %d", status)
// // fmt.Errorf("NRF return wrong status code %d", status)
// }
// }

// logger.InitLog.Infof("NEF Registration to NRF %v", rep)
// return nil
// }

// func RetrySendNFRegistration(MaxRetry int) error {
// retryCount := 0
// for retryCount < MaxRetry {
// err := SendNFRegistration()
// if err == nil {
// return nil
// }
// logger.ConsumerLog.Warnf("Send NFRegistration Failed by %v", err)
// retryCount++
// }

// return fmt.Errorf("[NEF] Retry NF Registration has meet maximum")
// }

// func SendNFDeregistration() error {
// // Check data (Use RESTful DELETE)
// res, localErr := nef_context.NEF_Self().
// NFManagementClient.
// NFInstanceIDDocumentApi.
// DeregisterNFInstance(context.TODO(), nef_context.NEF_Self().NfInstanceID)
// if localErr != nil {
// logger.ConsumerLog.Warnln(localErr)
// return localErr
// }
// defer func() {
// if resCloseErr := res.Body.Close(); resCloseErr != nil {
// logger.ConsumerLog.Errorf("DeregisterNFInstance response body cannot close: %+v", resCloseErr)
// }
// }()
// if res != nil {
// if status := res.StatusCode; status != http.StatusNoContent {
// logger.ConsumerLog.Warnln("handler returned wrong status code ", status)
// return openapi.ReportError("handler returned wrong status code %d", status)
// }
// }
// return nil
// }
9 changes: 9 additions & 0 deletions NFs/NEF/context/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package context

import (
"nef.com/factory"
)

func SetupNEFContext(config *factory.Config) error {
return nil
}
Loading

0 comments on commit 6c7d733

Please sign in to comment.