Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement PUT for inventory UPF #278

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion backend/webui_service/webui_init.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ func setupAuthenticationFeature(subconfig_router *gin.Engine) {
dbadapter.ConnectMongo(mongodb.WebuiDBUrl, mongodb.WebuiDBName, &dbadapter.WebuiDBClient)
resp, err := dbadapter.WebuiDBClient.CreateIndex(configmodels.UserAccountDataColl, "username")
if !resp || err != nil {
logger.InitLog.Errorf("error initializing webuiDB %v", err)
logger.InitLog.Errorf("error creating userAccount index in webuiDB %v", err)
}
configapi.AddUserAccountService(subconfig_router, jwtSecret)
auth.AddAuthenticationService(subconfig_router, jwtSecret)
Expand All @@ -157,6 +157,15 @@ func (webui *WEBUI) Start() {
dbadapter.ConnectMongo(mongodb.AuthUrl, mongodb.AuthKeysDbName, &dbadapter.AuthDBClient)
}

resp, err := dbadapter.CommonDBClient.CreateIndex(configmodels.GnbDataColl, "name")
if !resp || err != nil {
logger.InitLog.Errorf("error creating gNB index in commonDB %v", err)
}
resp, err = dbadapter.CommonDBClient.CreateIndex(configmodels.UpfDataColl, "hostname")
if !resp || err != nil {
logger.InitLog.Errorf("error creating UPF index in commonDB %v", err)
}

logger.InitLog.Infoln("WebUI server started")

/* First HTTP Server running at port to receive Config from ROC */
Expand Down
2 changes: 1 addition & 1 deletion configapi/api_default.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ func NetworkSliceSliceNameDelete(c *gin.Context) {
// @Failure 401 {object} nil "Authorization failed"
// @Failure 403 {object} nil "Forbidden"
// @Failure 500 {object} nil "Error creating network slice"
// @Router /config/v1/network-slice/{sliceName [post]
// @Router /config/v1/network-slice/{sliceName} [post]
func NetworkSliceSliceNamePost(c *gin.Context) {
logger.ConfigLog.Debugf("Received NetworkSliceSliceNamePost ")
if ret := NetworkSlicePostHandler(c, configmodels.Post_op); ret {
Expand Down
179 changes: 126 additions & 53 deletions configapi/api_inventory.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"

"github.com/gin-gonic/gin"
Expand All @@ -16,11 +17,6 @@ import (
"go.mongodb.org/mongo-driver/bson"
)

const (
gnbDataColl = "webconsoleData.snapshots.gnbData"
upfDataColl = "webconsoleData.snapshots.upfData"
)

func setInventoryCorsHeader(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
Expand All @@ -45,7 +41,7 @@ func GetGnbs(c *gin.Context) {

var gnbs []*configmodels.Gnb
gnbs = make([]*configmodels.Gnb, 0)
rawGnbs, errGetMany := dbadapter.CommonDBClient.RestfulAPIGetMany(gnbDataColl, bson.M{})
rawGnbs, errGetMany := dbadapter.CommonDBClient.RestfulAPIGetMany(configmodels.GnbDataColl, bson.M{})
if errGetMany != nil {
logger.DbLog.Errorln(errGetMany)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve gNBs"})
Expand Down Expand Up @@ -177,7 +173,7 @@ func GetUpfs(c *gin.Context) {

var upfs []*configmodels.Upf
upfs = make([]*configmodels.Upf, 0)
rawUpfs, errGetMany := dbadapter.CommonDBClient.RestfulAPIGetMany(upfDataColl, bson.M{})
rawUpfs, errGetMany := dbadapter.CommonDBClient.RestfulAPIGetMany(configmodels.UpfDataColl, bson.M{})
if errGetMany != nil {
logger.DbLog.Errorln(errGetMany)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve UPFs"})
Expand All @@ -200,21 +196,47 @@ func GetUpfs(c *gin.Context) {
// @Description Create a new UPF
// @Tags UPFs
// @Produce json
// @Param upf-hostname path string true "Name of the UPF"
// @Param port body configmodels.PostUpfRequest true "Port of the UPF"
// @Param upf body configmodels.PostUpfRequest true "Hostname and port of the UPF to create"
// @Security BearerAuth
// @Success 200 {object} nil "UPF created"
// @Failure 400 {object} nil "Failed to create the UPF"
// @Success 201 {object} nil "UPF successfully created"
// @Failure 400 {object} nil "Bad request"
// @Failure 401 {object} nil "Authorization failed"
// @Failure 403 {object} nil "Forbidden"
// @Router /config/v1/inventory/upf/{upf-hostname} [post]
// @Failure 500 {object} nil "Error creating UPF"
// @Router /config/v1/inventory/upf/ [post]
func PostUpf(c *gin.Context) {
setInventoryCorsHeader(c)
if err := handlePostUpf(c); err == nil {
c.JSON(http.StatusOK, gin.H{})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
logger.WebUILog.Infoln("received POST UPF")
var postUpfParams configmodels.PostUpfRequest
err := c.ShouldBindJSON(&postUpfParams)
if err != nil {
logger.ConfigLog.Errorln("invalid UPF POST input parameters. Error:", err)
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON format"})
return
}
if postUpfParams.Hostname == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "UPF hostname must be provided"})
return
}
if _, err := strconv.Atoi(postUpfParams.Port); err != nil {
errorMessage := "UPF port cannot be converted to integer or it was not provided"
logger.WebUILog.Errorln(errorMessage)
c.JSON(http.StatusBadRequest, gin.H{"error": errorMessage})
return
}
filter := bson.M{"hostname": postUpfParams.Hostname}
upfDataBson := configmodels.ToBsonM(postUpfParams)
err = dbadapter.CommonDBClient.RestfulAPIPostMany(configmodels.UpfDataColl, filter, []interface{}{upfDataBson})
if err != nil {
if strings.Contains(err.Error(), "E11000") {
logger.DbLog.Errorln("Duplicate hostname found:", err)
c.JSON(http.StatusBadRequest, gin.H{"error": "UPF already exists"})
return
}
logger.DbLog.Errorln(err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create UPF"})
return
}
c.JSON(http.StatusCreated, gin.H{})
}

// DeleteUpf godoc
Expand All @@ -238,42 +260,6 @@ func DeleteUpf(c *gin.Context) {
}
}

func handlePostUpf(c *gin.Context) error {
upfHostname, exists := c.Params.Get("upf-hostname")
if !exists {
errorMessage := "post UPF request is missing upf-hostname"
logger.ConfigLog.Errorln(errorMessage)
return fmt.Errorf("%s", errorMessage)
}
logger.ConfigLog.Infof("received UPF %v", upfHostname)
if !strings.HasPrefix(c.GetHeader("Content-Type"), "application/json") {
return fmt.Errorf("invalid header")
}
var postUpfRequest configmodels.PostUpfRequest
err := c.ShouldBindJSON(&postUpfRequest)
if err != nil {
logger.ConfigLog.Errorf("err %v", err)
return fmt.Errorf("invalid JSON format")
}
if postUpfRequest.Port == "" {
errorMessage := "post UPF request body is missing port"
logger.ConfigLog.Errorln(errorMessage)
return fmt.Errorf("%s", errorMessage)
}
postUpf := configmodels.Upf{
Hostname: upfHostname,
Port: postUpfRequest.Port,
}
msg := configmodels.ConfigMessage{
MsgType: configmodels.Inventory,
MsgMethod: configmodels.Post_op,
Upf: &postUpf,
}
configChannel <- &msg
logger.ConfigLog.Infof("successfully added UPF [%v] to config channel", upfHostname)
return nil
}

func handleDeleteUpf(c *gin.Context) error {
upfHostname, exists := c.Params.Get("upf-hostname")
if !exists {
Expand All @@ -291,3 +277,90 @@ func handleDeleteUpf(c *gin.Context) error {
logger.ConfigLog.Infof("successfully added UPF [%v] with delete_op to config channel", upfHostname)
return nil
}

// PutUpf godoc
//
// @Description Create or update a UPF
// @Tags UPFs
// @Produce json
// @Param upf-hostname path string true "Name of the UPF to update"
// @Param port body configmodels.PutUpfRequest true "Port of the UPF to update"
// @Security BearerAuth
// @Success 200 {object} nil "UPF successfully updated"
// @Success 201 {object} nil "UPF successfully created"
// @Failure 400 {object} nil "Bad request"
// @Failure 401 {object} nil "Authorization failed"
// @Failure 403 {object} nil "Forbidden"
// @Failure 500 {object} nil "Error updating UPF"
// @Router /config/v1/inventory/upf/{upf-hostname} [put]
func PutUpf(c *gin.Context) {
logger.WebUILog.Infoln("received PUT UPF")
hostname := c.Param("upf-hostname")
var putUpfParams configmodels.PutUpfRequest
err := c.ShouldBindJSON(&putUpfParams)
if err != nil {
logger.WebUILog.Errorln("invalid UPF PUT input parameters", hostname, "Error:", err)
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON format"})
return
}
if _, err := strconv.Atoi(putUpfParams.Port); err != nil {
errorMessage := "UPF port cannot be converted to integer or it was not provided"
logger.WebUILog.Errorln(errorMessage)
c.JSON(http.StatusBadRequest, gin.H{"error": errorMessage})
return
}
filter := bson.M{"hostname": hostname}
putUpf := configmodels.Upf{
Hostname: hostname,
Port: putUpfParams.Port,
}
upfDataBson := configmodels.ToBsonM(putUpf)
existed, errPut := dbadapter.CommonDBClient.RestfulAPIPutOne(configmodels.UpfDataColl, filter, upfDataBson)
if errPut != nil {
logger.DbLog.Errorln("failed to PUT UPF:", hostname, "Error:", errPut)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create or update UPF"})
return
}
patchJSON := []byte(fmt.Sprintf(`[
{
"op": "replace",
"path": "/site-info/upf",
"value": {
"upf-name": "%s",
"upf-port": "%s"
}
}
]`, putUpf.Hostname, putUpf.Port))
updateNSErr := updateUpfInNetworkSlices(putUpf.Hostname, patchJSON)
if updateNSErr != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create or update Network Slices"})
return
}
if existed {
c.JSON(http.StatusOK, gin.H{})
return
}
c.JSON(http.StatusCreated, gin.H{})
}

func updateUpfInNetworkSlices(hostname string, patchJSON []byte) error {
filterByUpf := bson.M{"site-info.upf.upf-name": hostname}
rawNetworkSlices, errGetMany := dbadapter.CommonDBClient.RestfulAPIGetMany(sliceDataColl, filterByUpf)
if errGetMany != nil {
logger.DbLog.Errorln("failed to fetch network slices:", errGetMany)
return errGetMany
}
for _, rawNetworkSlice := range rawNetworkSlices {
sliceName, ok := rawNetworkSlice["slice-name"].(string)
if !ok {
logger.ConfigLog.Warnln("invalid slice-name in network slice:", rawNetworkSlice)
continue
}
filterBySliceName := bson.M{"slice-name": sliceName}
err := dbadapter.CommonDBClient.RestfulAPIJSONPatch(sliceDataColl, filterBySliceName, patchJSON)
if err != nil {
logger.DbLog.Warnln("failed to update network slice:", sliceName, "Error:", err)
}
}
return nil
}
Loading
Loading