diff options
author | deepikasatheesh <deepika.s84@wipro.com> | 2021-02-04 14:54:53 +0000 |
---|---|---|
committer | deepikasatheesh <deepika.s84@wipro.com> | 2021-02-22 09:08:34 +0000 |
commit | 49f60702c82398abadb0bc28bf9a3b902b1deee7 (patch) | |
tree | 1e0ce351712eb9cd46e4bf90f5373326b298cf04 /ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller | |
parent | 7365105475e82c302bb32094ac3c708ef5c21a72 (diff) |
Refactored & enhanced code check-in RANSim Controller and RANSim GUI
Issue-ID: INT-1849
Signed-off-by: deepikasatheesh <deepika.s84@wipro.com>
Change-Id: I8f92d8eae6eb67708098ccd696dbfff0eaa5f87f
Diffstat (limited to 'ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller')
6 files changed, 1225 insertions, 3107 deletions
diff --git a/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/FileController.java b/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/FileController.java new file mode 100644 index 0000000..5da605c --- /dev/null +++ b/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/FileController.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * Ran Simulator Controller + * ================================================================================ + * Copyright (C) 2020 Wipro Limited. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ +package org.onap.ransim.rest.api.controller; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.Logger; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping("/file") +@CrossOrigin(origins = "*") +@Configuration +@PropertySource(value = "classpath:dumpfileNames.properties") +public class FileController { + + static Logger log = Logger.getLogger(FileController.class.getName()); + + private static final String fileBasePath = "/tmp/ransim-install/config/"; + + @Value("${defaultFiles:}") + List<String> fileList = new ArrayList<>(); + + /** + * Method to upload dump file + * + * @param file + * @return + */ + @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public ResponseEntity<String> uploadToLocalFileSystem(@RequestParam("file") MultipartFile file) { + String fileName = StringUtils.cleanPath(file.getOriginalFilename()); + Path path = Paths.get(fileBasePath + fileName); + try { + Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); + fileList.add(fileName); + log.info("File downloaded in " + fileBasePath + fileName); + } catch (IOException e) { + log.error(e); + } + log.info("Copied in path : " + path); + return ResponseEntity.ok("Uploaded successfully"); + } + + /** + * Method to retrieve list of available dump files + * + * @return + */ + @GetMapping(value = "/dumpfiles", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity<List<String>> getFiles() { + return ResponseEntity.ok(fileList); + } + +} diff --git a/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RANSliceConfigController.java b/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RANSliceConfigController.java new file mode 100644 index 0000000..05de928 --- /dev/null +++ b/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RANSliceConfigController.java @@ -0,0 +1,567 @@ +package org.onap.ransim.rest.api.controller; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PutMapping; + +import org.onap.ransim.rest.api.models.NSSAIConfig; +import org.onap.ransim.rest.api.services.RANSliceConfigService; +import org.onap.ransim.rest.web.mapper.GNBCUCPModel; +import org.onap.ransim.rest.web.mapper.GNBCUUPModel; +import org.onap.ransim.rest.web.mapper.GNBDUModel; +import org.onap.ransim.rest.web.mapper.NRCellCUModel; +import org.onap.ransim.rest.web.mapper.NRCellDUModel; +import org.onap.ransim.rest.web.mapper.NearRTRICModel; +import org.onap.ransim.rest.web.mapper.RANSliceInfoModel; +import org.onap.ransim.rest.web.mapper.RRMPolicyRatioModel; + +@RestController +@RequestMapping(path = "/api/ransim-db/v4") +public class RANSliceConfigController { + private static final Logger logger = LoggerFactory.getLogger(RANSliceConfigController.class); + + @Autowired + private RANSliceConfigService ranSliceConfigService; + + //SDN-R APIs + /** + * This method updates the slice details, config details of CUCP + * + * @param GNBCUCPModel + * @return ResponseEntity<GNBCUCPModel> + */ + @PutMapping(path = "/gNBCUCP") + public ResponseEntity<GNBCUCPModel> updateGNBCUCPFunction(@RequestBody GNBCUCPModel gNBCUCPModel) { + logger.info("Request Received"); + try { + return new ResponseEntity<GNBCUCPModel>(ranSliceConfigService.saveGNBCUCP(gNBCUCPModel), HttpStatus.OK); + } catch (Exception e) { + logger.error("Error while updating GNBCUCP:" + e.getMessage()); + return new ResponseEntity<GNBCUCPModel>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To fetch the CUCP details + * + * @param gNBCUCPName + * @return ResponseEntity<GNBCUCPModel> + */ + @GetMapping(path = "/gNBCUCP/{gNBCUCPName}") + public ResponseEntity<GNBCUCPModel> findGNBCUCPFunction(@PathVariable String gNBCUCPName) { + logger.info("Request Received"); + try { + if(ranSliceConfigService.fetchGNBCUCPData(gNBCUCPName)!=null) { + return new ResponseEntity<GNBCUCPModel>(ranSliceConfigService.fetchGNBCUCPData(gNBCUCPName), HttpStatus.OK); + }else { + return new ResponseEntity<GNBCUCPModel>(ranSliceConfigService.fetchGNBCUCPData(gNBCUCPName), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + logger.error("Error while fetching GNBCUCP:" + e.getMessage()); + return new ResponseEntity<GNBCUCPModel>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * This method updates the slice details, config details of CUUP + * + * @param GNBCUUPModel + * @return ResponseEntity<GNBCUUPModel> + */ + @PutMapping(path = "/gNBCUUP") + public ResponseEntity<GNBCUUPModel> updateGNBCUUPFunction(@RequestBody GNBCUUPModel gNBCUUPModel) { + logger.info("Request Received"); + try { + return new ResponseEntity<GNBCUUPModel>(ranSliceConfigService.saveGNBCUUP(gNBCUUPModel), HttpStatus.OK); + } catch (Exception e) { + logger.error("Error while updating GNBCUUP:" + e.getMessage()); + return new ResponseEntity<GNBCUUPModel>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To fetch the CUCP details + * + * @param gNBCUCPName + * @return ResponseEntity<GNBCUCPModel> + */ + @GetMapping(path = "/gNBCUUP/{gNBCUUPId}") + public ResponseEntity<GNBCUUPModel> findGNBCUUPFunction(@PathVariable Integer gNBCUUPId) { + logger.info("Request Received"); + try { + if(ranSliceConfigService.fetchGNBCUUPData(gNBCUUPId)!=null) { + return new ResponseEntity<GNBCUUPModel>(ranSliceConfigService.fetchGNBCUUPData(gNBCUUPId), HttpStatus.OK); + }else { + return new ResponseEntity<GNBCUUPModel>(ranSliceConfigService.fetchGNBCUUPData(gNBCUUPId), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + logger.error("Error while fetching GNBCUCP:" + e.getMessage()); + return new ResponseEntity<GNBCUUPModel>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * This method updates the slice details, config details of gNBDU + * + * @param GNBDUModel + * @return ResponseEntity<GNBDUModel> + */ + @PutMapping(path = "/gNBDU") + public ResponseEntity<GNBDUModel> updateGNBDUFunction(@RequestBody GNBDUModel gNBDUModel) { + logger.info("Request Received"); + try { + return new ResponseEntity<GNBDUModel>(ranSliceConfigService.saveGNBDU(gNBDUModel), HttpStatus.OK); + } catch (Exception e) { + logger.error("Error while updating GNBDU:" + e.getMessage()); + return new ResponseEntity<GNBDUModel>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To fetch the gNBDU details + * + * @param gNBDUId + * @return ResponseEntity<GNBDUModel> + */ + @GetMapping(path = "/gNBDU/{gNBDUId}") + public ResponseEntity<GNBDUModel> findGNBDUFunction(@PathVariable Integer gNBDUId) { + logger.info("Request Received"); + try { + if(ranSliceConfigService.fetchGNBDUData(gNBDUId)!=null) { + return new ResponseEntity<GNBDUModel>(ranSliceConfigService.fetchGNBDUData(gNBDUId), HttpStatus.OK); + }else { + return new ResponseEntity<GNBDUModel>(ranSliceConfigService.fetchGNBDUData(gNBDUId), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + logger.error("Error while fetching GNBDU:" + e.getMessage()); + return new ResponseEntity<GNBDUModel>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * This method updates the NearRTRIC details + * + * @param nearRTRICModel + * @return ResponseEntity<NearRTRICModel> + */ + @PutMapping(path = "/nearRTRIC") + public ResponseEntity<NearRTRICModel> updateNearRTRIC(@RequestBody NearRTRICModel nearRTRICModel) { + logger.info("Request Received"); + try { + return new ResponseEntity<NearRTRICModel>(ranSliceConfigService.saveNearRTRIC(nearRTRICModel), + HttpStatus.OK); + } catch (Exception e) { + logger.error("Error while updating nearRTRIC:" + e.getMessage()); + return new ResponseEntity<NearRTRICModel>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To fetch the nearRTRIC details + * + * @param nearRTRICId + * @return ResponseEntity<GNBDUModel> + */ + @GetMapping(path = "/nearRTRIC/{nearRTRICId}") + public ResponseEntity<NearRTRICModel> findNearRTRICFunction(@PathVariable Integer nearRTRICId) { + logger.info("Request Received"); + try { + if(ranSliceConfigService.fetchNearRTRICData(nearRTRICId)!=null) { + return new ResponseEntity<NearRTRICModel>(ranSliceConfigService.fetchNearRTRICData(nearRTRICId), + HttpStatus.OK); + }else { + return new ResponseEntity<NearRTRICModel>(ranSliceConfigService.fetchNearRTRICData(nearRTRICId), + HttpStatus.NO_CONTENT); + } + + } catch (Exception e) { + logger.error("Error while fetching nearRTRIC:" + e.getMessage()); + return new ResponseEntity<NearRTRICModel>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To fetch the RRMPolicy of CU/DU + * + * @param resourceType + * @param resourceId + * @return + */ + @GetMapping(path = "/rrmPolicy/{resourceType}/{resourceId}") + public ResponseEntity<RRMPolicyRatioModel> findRRMPolicyOfNE(@PathVariable String resourceType, + @PathVariable String resourceId) { + logger.debug("Request Received"); + try { + if(ranSliceConfigService.fetchRRMPolicyOfNE(resourceType, resourceId)!=null) { + return new ResponseEntity<RRMPolicyRatioModel>( + ranSliceConfigService.fetchRRMPolicyOfNE(resourceType, resourceId), HttpStatus.OK); + }else { + return new ResponseEntity<RRMPolicyRatioModel>( + ranSliceConfigService.fetchRRMPolicyOfNE(resourceType, resourceId), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + logger.error("Error while fetching RRMPolicy:" + e.getMessage()); + return new ResponseEntity<RRMPolicyRatioModel>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * This method updates the RRM policy of a network function + * + * @param nearRTRICModel + * @return ResponseEntity<NearRTRICModel> + */ + @PostMapping(path = "/rrmPolicy") + public ResponseEntity<RRMPolicyRatioModel> updateRRMPolicy(@RequestBody RRMPolicyRatioModel rrmPolicy) { + logger.info("Request Received"); + try { + return new ResponseEntity<RRMPolicyRatioModel>(ranSliceConfigService.updateRRMPolicy(rrmPolicy), HttpStatus.OK); + } catch (Exception e) { + logger.error("Error while updating RRM Policy:" + e.getMessage()); + return new ResponseEntity<RRMPolicyRatioModel>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + + /** + * To find the list of RICs from tracking area + * 1. Find Cells from TA + * 2. find List of RICs of the cells + * + * @param trackingArea + * @return + */ + @GetMapping(path = "/nearrtric-list/{trackingArea}") + public ResponseEntity<List<NearRTRICModel>> findNearRTRICofCellsFromTA(@PathVariable String trackingArea) { + logger.info("Request Received"); + try { + List<String> cellIds = this.findListOfCells(trackingArea).getBody(); + List<Integer> cellIdList =cellIds.stream().map(Integer::parseInt).collect(Collectors.toList()); + if(ranSliceConfigService.findNearRTRICofCells(cellIdList).size()>0) { + return new ResponseEntity<List<NearRTRICModel>>(ranSliceConfigService.findNearRTRICofCells(cellIdList), + HttpStatus.OK); + }else { + return new ResponseEntity<List<NearRTRICModel>>(ranSliceConfigService.findNearRTRICofCells(cellIdList), + HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + logger.error("Error while fetching the RICs:" + e.getMessage()); + return new ResponseEntity<List<NearRTRICModel>>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To find the list of CUs in a tracking area + * + * @param trackingArea + * @return + */ + @GetMapping(path = "/cell-list/{trackingArea}") + public ResponseEntity<List<String>> findListOfCells(@PathVariable String trackingArea) { + logger.info("Request Received"); + try { + if(ranSliceConfigService.fetchCellsofTA(trackingArea).size()>0) { + return new ResponseEntity<List<String>>(ranSliceConfigService.fetchCellsofTA(trackingArea), HttpStatus.OK); + }else { + return new ResponseEntity<List<String>>(ranSliceConfigService.fetchCellsofTA(trackingArea), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + logger.error("Error while fetching the Cells:" + e.getMessage()); + return new ResponseEntity<List<String>>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To find the list of CU-Cells + * + * @param nearRTRICId + * @return + */ + @GetMapping(path = "/cu-cell-list/{nearRTRICId}") + public ResponseEntity<List<NRCellCUModel>> findCUCellsofRIC(@PathVariable Integer nearRTRICId) { + logger.info("Request Received"); + try { + if(ranSliceConfigService.fetchCUCellsofRIC(nearRTRICId).size()>0) { + return new ResponseEntity<List<NRCellCUModel>>(ranSliceConfigService.fetchCUCellsofRIC(nearRTRICId), HttpStatus.OK); + }else { + return new ResponseEntity<List<NRCellCUModel>>(ranSliceConfigService.fetchCUCellsofRIC(nearRTRICId), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + e.printStackTrace(); + logger.error("Error while fetching the Cells-CU:" + e.getMessage()); + return new ResponseEntity<List<NRCellCUModel>>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + + /** + * To find the nearRTRIC of NSSI + * + * This API can be used in Terminate/activate/deactivate to find the RIC from ranNFNSSIId in SO request + * + * @param ranNFNSSIId + * @return List<NearRTRICModel> + */ + @GetMapping(path = "/nearrtric/{ranNFNSSIId}") + public ResponseEntity<List<NearRTRICModel>> findNearRTRICByNSSI(@PathVariable String ranNFNSSIId) { + logger.info("Request Received"); + try { + if(ranSliceConfigService.findNearRTRICByNSSI(ranNFNSSIId).size()>0){ + return new ResponseEntity<List<NearRTRICModel>>(ranSliceConfigService.findNearRTRICByNSSI(ranNFNSSIId), HttpStatus.OK); + }else { + return new ResponseEntity<List<NearRTRICModel>>(ranSliceConfigService.findNearRTRICByNSSI(ranNFNSSIId), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + logger.error("Error while fetching the nearRTRIC by RANNFNSSI:" + e.getMessage()); + return new ResponseEntity<List<NearRTRICModel>>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To find the list of DU-Cells + * + * @param nearRTRICId + * @return + */ + @GetMapping(path = "/du-cell-list/{sNSSAI}") + public ResponseEntity<Map<Integer, List<NRCellDUModel>>> findDUCellsofRIC(@PathVariable String sNSSAI) { + logger.info("Request Received"); + try { + if(ranSliceConfigService.fetchDUCellsofRIC(sNSSAI).size()>0) { + return new ResponseEntity<Map<Integer, List<NRCellDUModel>>>(ranSliceConfigService.fetchDUCellsofRIC(sNSSAI), HttpStatus.OK); + }else { + return new ResponseEntity<Map<Integer, List<NRCellDUModel>>>(ranSliceConfigService.fetchDUCellsofRIC(sNSSAI), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + e.printStackTrace(); + logger.error("Error while fetching the Cells-DU:" + e.getMessage()); + return new ResponseEntity<Map<Integer, List<NRCellDUModel>>>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + //Inventory APIs + /** + * This method updates the RAN slice details + * + * @param ranSliceInfoModel + * @return ResponseEntity<RANSliceInfoModel> + */ + @PutMapping(path = "/ranslice-details") + public ResponseEntity<RANSliceInfoModel> updateRANInventory(@RequestBody RANSliceInfoModel ranSliceInfoModel) { + logger.info("Request Received"); + try { + return new ResponseEntity<RANSliceInfoModel>(ranSliceConfigService.updateRANInventory(ranSliceInfoModel), + HttpStatus.OK); + } catch (Exception e) { + logger.error("Error while updating RAN Inventory:" + e.getMessage()); + return new ResponseEntity<RANSliceInfoModel>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To fetch the RAN slice Details + * + * @param ranNFNSSIId + * @return RANSliceInfoModel + */ + @GetMapping(path = "/ranslice-details/{ranNFNSSIId}") + public ResponseEntity<RANSliceInfoModel> findRANSlice(@PathVariable String ranNFNSSIId) { + logger.info("Request Received"); + try { + if(ranSliceConfigService.fetchRANSlice(ranNFNSSIId)!=null) { + return new ResponseEntity<RANSliceInfoModel>(ranSliceConfigService.fetchRANSlice(ranNFNSSIId), HttpStatus.OK); + }else { + return new ResponseEntity<RANSliceInfoModel>(ranSliceConfigService.fetchRANSlice(ranNFNSSIId), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + logger.error("Error while fetching the RAN slice Details:" + e.getMessage()); + return new ResponseEntity<RANSliceInfoModel>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + //Slice Analysis MS APIs + /** + * To fetch The NearRTRICs serving the sNSSAI + * + * @param sNSSAI + * @return List<NearRTRICModel> + */ + @GetMapping(path = "/nearrtric/snssai/{sNSSAI}") + public ResponseEntity<List<NearRTRICModel>> findRICsofNSSAI(@PathVariable String sNSSAI){ + logger.info("Request Received"); + try { + if(ranSliceConfigService.findRICsByNSSAI(sNSSAI).size()>0) { + return new ResponseEntity<List<NearRTRICModel>>(ranSliceConfigService.findRICsByNSSAI(sNSSAI), HttpStatus.OK); + }else { + return new ResponseEntity<List<NearRTRICModel>>(ranSliceConfigService.findRICsByNSSAI(sNSSAI), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + logger.error("Error while fetching the nearRTRIC by sNSSAI:" + e.getMessage()); + return new ResponseEntity<List<NearRTRICModel>>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To fetch the configuration requested for a slice + * + * @param sNSSAI + * @return + */ + @GetMapping(path="/profile-config/{sNSSAI}") + public ResponseEntity<Map<String,Integer>> fetchSliceProfileConfiguration(@PathVariable String sNSSAI){ + logger.info("Request Received"); + try { + if(ranSliceConfigService.findSliceProfileconfig(sNSSAI).size()>0) { + return new ResponseEntity<Map<String,Integer>>(ranSliceConfigService.findSliceProfileconfig(sNSSAI), HttpStatus.OK); + }else { + return new ResponseEntity<Map<String,Integer>>(ranSliceConfigService.findSliceProfileconfig(sNSSAI), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + logger.error("Error while fetching the Requested Configuration:" + e.getMessage()); + return new ResponseEntity<Map<String,Integer>>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To fetch the configuration of a slice in RIC + * + * @param sNSSAI + * @return + */ + @GetMapping(path="/slice-config/{sNSSAI}") + public ResponseEntity<Map<Integer,NSSAIConfig>> fetchSliceConfiguration(@PathVariable String sNSSAI){ + logger.info("Request Received"); + try { + if(ranSliceConfigService.findSliceConfig(sNSSAI).size()>0) { + return new ResponseEntity<Map<Integer, NSSAIConfig>>(ranSliceConfigService.findSliceConfig(sNSSAI), HttpStatus.OK); + }else { + return new ResponseEntity<Map<Integer, NSSAIConfig>>(ranSliceConfigService.findSliceConfig(sNSSAI), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + e.printStackTrace(); + logger.error("Error while fetching the Configuration of a Slice at RIC:" + e.getMessage()); + return new ResponseEntity<Map<Integer, NSSAIConfig>>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To fetch the DU details + * + * @param + * @return List<GNBDUModel> + */ + @GetMapping(path="/du-list/{sNSSAI}") + public ResponseEntity<List<GNBDUModel>> fetchDUFunctionsOfNSSAI(@PathVariable String sNSSAI){ + logger.info("Request Received::"+sNSSAI); + try { + if(ranSliceConfigService.findDUsofSNssai(sNSSAI).size()>0) { + return new ResponseEntity<List<GNBDUModel>>(ranSliceConfigService.findDUsofSNssai(sNSSAI), HttpStatus.OK); + }else { + return new ResponseEntity<List<GNBDUModel>>(ranSliceConfigService.findDUsofSNssai(sNSSAI), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + e.printStackTrace(); + logger.error("Error while fetching the DU details of NSSAI:" + e.getMessage()); + return new ResponseEntity<List<GNBDUModel>>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To fetch the DU details + * + * @param + * @return List<GNBDUModel> + */ + @GetMapping(path="/cucp-list/{sNSSAI}") + public ResponseEntity<List<GNBCUCPModel>> fetchCUFunctionsOfNSSAI(@PathVariable String sNSSAI){ + logger.info("Request Received::"+sNSSAI); + try { + if(ranSliceConfigService.findDUsofSNssai(sNSSAI).size()>0) { + return new ResponseEntity<List<GNBCUCPModel>>(ranSliceConfigService.findCUsofSNssai(sNSSAI), HttpStatus.OK); + }else { + return new ResponseEntity<List<GNBCUCPModel>>(ranSliceConfigService.findCUsofSNssai(sNSSAI), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + logger.error("Error while fetching the CU details of NSSAI:" + e.getMessage()); + return new ResponseEntity<List<GNBCUCPModel>>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To fetch the Customer Details + * + * @param + * @return Map<String, String> + */ + @GetMapping(path="/subscriber-details/{sNSSAI}") + public ResponseEntity<Map<String, String>> fetchSubsciberDetailsOfNSSAI(@PathVariable String sNSSAI){ + logger.info("Request Received::"+sNSSAI); + try { + if(ranSliceConfigService.getSubscriberDetails(sNSSAI).size()>0) { + return new ResponseEntity<Map<String, String>>(ranSliceConfigService.getSubscriberDetails(sNSSAI), HttpStatus.OK); + }else { + return new ResponseEntity<Map<String, String>>(ranSliceConfigService.getSubscriberDetails(sNSSAI), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + logger.error("Error while fetching the Customer details of NSSAI:" + e.getMessage()); + return new ResponseEntity<Map<String, String>>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To fetch the cu details + * + * @param + * @return List<GNBCUCPModel> + */ + @GetMapping(path="/cucp-list") + public ResponseEntity<List<GNBCUCPModel>> fetchCUCPFunctions(){ + logger.info("Request Received"); + try { + if(ranSliceConfigService.findAllCUCPFunctions().size()>0) { + return new ResponseEntity<List<GNBCUCPModel>>(ranSliceConfigService.findAllCUCPFunctions(), HttpStatus.OK); + }else { + return new ResponseEntity<List<GNBCUCPModel>>(ranSliceConfigService.findAllCUCPFunctions(), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + logger.error("Error while fetching the CU details:" + e.getMessage()); + return new ResponseEntity<List<GNBCUCPModel>>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** + * To fetch the DU details + * + * @param + * @return List<GNBDUModel> + */ + @GetMapping(path="/du-list") + public ResponseEntity<List<GNBDUModel>> fetchDUFunctions(){ + logger.info("Request Received"); + try { + if(ranSliceConfigService.findAllDUFunctions().size()>0) { + return new ResponseEntity<List<GNBDUModel>>(ranSliceConfigService.findAllDUFunctions(), HttpStatus.OK); + }else { + return new ResponseEntity<List<GNBDUModel>>(ranSliceConfigService.findAllDUFunctions(), HttpStatus.NO_CONTENT); + } + } catch (Exception e) { + logger.error("Error while fetching the DU details:" + e.getMessage()); + return new ResponseEntity<List<GNBDUModel>>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + +}
\ No newline at end of file diff --git a/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RansimController.java b/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RansimController.java index 9ea789e..5d15e58 100644 --- a/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RansimController.java +++ b/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RansimController.java @@ -20,1131 +20,742 @@ package org.onap.ransim.rest.api.controller; -import com.google.gson.Gson; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; +import java.util.Arrays; import java.util.List; import java.util.Map; -import java.util.Properties; -import java.util.Random; -import java.util.Set; -import java.util.UUID; +import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.persistence.Query; -import javax.persistence.TypedQuery; -import javax.websocket.Session; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; -import org.onap.ransim.websocket.model.*; -import org.onap.ransim.rest.api.models.CellData; import org.onap.ransim.rest.api.models.CellDetails; import org.onap.ransim.rest.api.models.CellNeighbor; -import org.onap.ransim.rest.api.models.FmAlarmInfo; +import org.onap.ransim.rest.api.models.DeleteACellReq; +import org.onap.ransim.rest.api.models.GetACellDetailReq; import org.onap.ransim.rest.api.models.GetNeighborList; -import org.onap.ransim.rest.api.models.NbrDump; +import org.onap.ransim.rest.api.models.GetNeighborListReq; +import org.onap.ransim.rest.api.models.GetNetconfServerDetailsReq; +import org.onap.ransim.rest.api.models.GetPmDataReq; +import org.onap.ransim.rest.api.models.ModifyACellReq; import org.onap.ransim.rest.api.models.NeighborDetails; -import org.onap.ransim.rest.api.models.NeighborPmDetails; import org.onap.ransim.rest.api.models.NeihborId; import org.onap.ransim.rest.api.models.NetconfServers; import org.onap.ransim.rest.api.models.OperationLog; -import org.onap.ransim.rest.api.models.PmDataDump; -import org.onap.ransim.rest.api.models.PmParameters; -import org.onap.ransim.rest.api.models.TopologyDump; -import org.onap.ransim.rest.client.RestClient; -import org.onap.ransim.websocket.model.FmMessage; -import org.onap.ransim.websocket.model.ModifyNeighbor; -import org.onap.ransim.websocket.model.ModifyPci; -import org.onap.ransim.websocket.model.Neighbor; -import org.onap.ransim.websocket.model.PmMessage; -import org.onap.ransim.websocket.model.SetConfigTopology; -import org.onap.ransim.websocket.model.Topology; -import org.onap.ransim.websocket.model.UpdateCell; -import org.onap.ransim.websocket.server.RansimWebSocketServer; +import org.onap.ransim.rest.api.models.Topology; +import org.onap.ransim.rest.api.models.TACells; +import org.onap.ransim.rest.api.services.RansimControllerServices; +import org.onap.ransim.rest.api.services.RANSliceConfigService; +import org.onap.ransim.rest.api.services.RansimRepositoryService; +import org.onap.ransim.rest.api.controller.RANSliceConfigController; +import org.onap.ransim.rest.api.handler.RansimPciHandler; +import org.onap.ransim.rest.api.handler.RansimSlicingHandler; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.onap.ransim.rest.api.services.SlicingPMDataGenerator; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; + +@RestController +@Api(value = "Ran Simulator Controller Services") +@RequestMapping("/api") +@CrossOrigin(origins = "*") public class RansimController { - static Logger log = Logger.getLogger(RansimController.class - .getName()); - - private static RansimController rsController = null; - Properties netconfConstants = new Properties(); - int gridSize = 10; - boolean collision = false; - String serverIdPrefix = ""; - static int numberOfCellsPerNcServer = 15; - int numberOfMachines = 1; - int numberOfProcessPerMc = 5; - boolean strictValidateRansimAgentsAvailability = false; - static public Map<String, Session> webSocketSessions = new ConcurrentHashMap<String, Session>(); - static Map<String, String> serverIdIpPortMapping = new ConcurrentHashMap<String, String>(); - - static Map<String, String> globalNcServerUuidMap = new ConcurrentHashMap<String, String>(); - static List<String> unassignedServerIds = Collections - .synchronizedList(new ArrayList<String>()); - static Map<String, List<String>> serverIdIpNodeMapping = new ConcurrentHashMap<String, List<String>>(); - int nextServerIdNumber = 1001; - String sdnrServerIp = ""; - int sdnrServerPort = 0; - static String sdnrServerUserid = ""; - static String sdnrServerPassword = ""; - static String dumpFileName = ""; - static long maxPciValueAllowed = 503; - - static RansimPciHandler rsPciHdlr = RansimPciHandler.getRansimPciHandler(); - - private RansimController() { - - } + static Logger log = Logger.getLogger(RansimController.class.getName()); + + private static boolean isPmDataGenerating = false; + private static boolean isIntelligentSlicingPmDataGenerating = false; + + ScheduledExecutorService execService = Executors.newScheduledThreadPool(5); + ScheduledExecutorService execServiceForIntelligentSlicing = Executors.newScheduledThreadPool(5); + ScheduledExecutorService closedLoopExecService; + + @Autowired + RansimRepositoryService ransimRepo; + @Autowired + RansimControllerServices rscServices; + @Autowired + RansimPciHandler rsPciHdlr; + @Autowired + RANSliceConfigController ranSliceConfigController; + @Autowired + RANSliceConfigService ranSliceConfigService; + @Autowired + RansimSlicingHandler ranSliceHandler; + @Autowired + SlicingPMDataGenerator pmDataGenerator; /** - * To accesss variable of this class from another class. + * Start the RAN network simulation. * - * @return returns rscontroller constructor + * @param req gets the necessary details as a request of class type + * StartSimulationReq + * @return returns Http status + * @throws Exception throws exceptions in the functions */ - public static synchronized RansimController getRansimController() { - if (rsController == null) { - rsController = new RansimController(); - new KeepWebsockAliveThread(rsController).start(); + @ApiOperation("Starts the RAN network simulation") + @RequestMapping(value = "/StartSimulation", method = RequestMethod.POST) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot start the simulation") }) + public ResponseEntity<String> startSimulation(@RequestBody Map<String,String> dumpfile) throws Exception { + + List<CellDetails> cellList = ransimRepo.getCellDetailsList(); + if (!cellList.isEmpty()) { + return new ResponseEntity<>("Already simulation is running.", HttpStatus.INTERNAL_SERVER_ERROR); } - return rsController; - } + try { + rscServices.loadProperties(); + RansimControllerServices.dumpFileName = dumpfile.containsKey("dumpfile") ? dumpfile.get("dumpfile"):null; + long startTimeStartSimulation = System.currentTimeMillis(); + rscServices.generateClusterFromFile(); + rscServices.sendInitialConfigAll(); + long endTimeStartSimulation = System.currentTimeMillis(); + log.info("Time taken for start simulation : " + (endTimeStartSimulation - startTimeStartSimulation)); - private String checkIpPortAlreadyExists(String ipPort, - Map<String, String> serverIdIpPortMapping) { - String serverId = null; - for (String key : serverIdIpPortMapping.keySet()) { - String value = serverIdIpPortMapping.get(key); - if (value.equals(ipPort)) { - serverId = key; - break; - } - } - return serverId; - } + return new ResponseEntity<String>(HttpStatus.OK); - /** - * Add web socket sessions. - * - * @param ipPort - * ip address for the session - * @param wsSession - * session details - */ - public synchronized String addWebSocketSessions(String ipPort, - Session wsSession) { - loadProperties(); - if (webSocketSessions.containsKey(ipPort)) { - log.info("addWebSocketSessions: Client session " - + wsSession.getId() + " for " + ipPort - + " already exist. Removing old session."); - webSocketSessions.remove(ipPort); + } catch (Exception eu) { + log.info("/StartSimulation ", eu); + return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); } - log.info("addWebSocketSessions: Adding Client session " - + wsSession.getId() + " for " + ipPort); - webSocketSessions.put(ipPort, wsSession); - String serverId = null; - if (!serverIdIpPortMapping.containsValue(ipPort)) { - if (unassignedServerIds.size() > 0) { - log.info("addWebSocketSessions: No serverIds pending to assign for " - + ipPort); - serverId = checkIpPortAlreadyExists(ipPort, - serverIdIpPortMapping); - if (serverId == null) { - serverId = unassignedServerIds.remove(0); - } else { - if (unassignedServerIds.contains(serverId)) { - unassignedServerIds.remove(serverId); - } - } - log.info("RansCtrller = Available unassigned ServerIds :" - + unassignedServerIds); - log.info("RansCtrller = addWebSocketSessions: Adding serverId " - + serverId + " for " + ipPort); - serverIdIpPortMapping.put(serverId, ipPort); - log.debug("RansCtrller = serverIdIpPortMapping >>>> :" - + serverIdIpPortMapping); - mapServerIdToNodes(serverId); - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - try { - - NetconfServers server = rsDb.getNetconfServer(serverId); - if (server != null) { - server.setIp(ipPort.split(":")[0]); - server.setNetconfPort(ipPort.split(":")[1]); - rsDb.mergeNetconfServers(server); - } + } + + @ApiOperation("Starts the RAN network slice simulation") + @RequestMapping(value = "/StartRanSliceSimulation", method = RequestMethod.POST) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot start the simulation") }) + public ResponseEntity<String> startRanSliceSimulation() throws Exception { + try { + rscServices.loadGNBFunctionProperties(); + long startTimeStartSimulation = System.currentTimeMillis(); + rscServices.sendRanInitialConfigAll(); + long endTimeStartSimulation = System.currentTimeMillis(); + log.info("Time taken for start ran slice simulation : " + (endTimeStartSimulation - startTimeStartSimulation)); + return new ResponseEntity<>("Simulation started.", HttpStatus.OK); - } catch (Exception e1) { - log.info("Exception mapServerIdToNodes :", e1); - } - } else { - log.info("addWebSocketSessions: No serverIds pending to assign for " - + ipPort); - } - } else { - for (String key : serverIdIpPortMapping.keySet()) { - if (serverIdIpPortMapping.get(key).equals(ipPort)) { - log.info("addWebSocketSessions: ServerId " + key + " for " - + ipPort + " is exist already"); - serverId = key; - break; - } - } + } catch (Exception eu) { + log.info("/StartRanSliceSimulation ", eu); + return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); } - return serverId; } /** - * Map server ID to the cells + * The performance Management Data of each cell will be sent to its netconf + * agent at a regular interval. + * + * @param req Contains the details of node ids which will have bad and poor pm + * values + * @return return HTTP status. * - * @param serverId - * Server ID */ - private void mapServerIdToNodes(String serverId) { - dumpSessionDetails(); - if (serverIdIpNodeMapping.containsKey(serverId)) { - // already mapped.RansimController Do nothing. - } else { - List<String> nodeIds = new ArrayList<String>(); - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - try { - List<CellDetails> nodes = rsDb.getCellsWithNoServerIds(); - for (CellDetails cell : nodes) { - cell.setServerId(serverId); - nodeIds.add(cell.getNodeId()); - rsDb.mergeCellDetails(cell); - } - serverIdIpNodeMapping.put(serverId, nodeIds); - } catch (Exception e1) { - log.info("Exception mapServerIdToNodes :", e1); - - } - } - } + @ApiOperation("Generate PM data") + @RequestMapping(value = "/GeneratePmData", method = RequestMethod.POST) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot start the simulation") }) + public ResponseEntity<String> generatePmData(@RequestBody GetPmDataReq req) throws Exception { - /** - * It removes the web socket sessions. - * - * @param ipPort - * ip address of the netconf server - */ - public synchronized void removeWebSocketSessions(String ipPort) { - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - log.info("remove websocket session request received for: " + ipPort); + log.info("Generate PM Data - nodeId_bad: " + req.getNodeIdBad() + ", nodeId_poor: " + req.getNodeIdPoor()); try { - if (webSocketSessions.containsKey(ipPort)) { - String removedServerId = null; - for (String serverId : serverIdIpPortMapping.keySet()) { - String ipPortVal = serverIdIpPortMapping.get(serverId); - if (ipPortVal.equals(ipPort)) { - if (!unassignedServerIds.contains(serverId)) { - unassignedServerIds.add(serverId); - log.info(serverId + "added in unassignedServerIds"); - } - NetconfServers ns = rsDb.getNetconfServer(serverId); - ns.setIp(null); - ns.setNetconfPort(null); - log.info(serverId + " ip and Port set as null "); - rsDb.mergeNetconfServers(ns); - removedServerId = serverId; - break; - } - } - serverIdIpPortMapping.remove(removedServerId); + rsPciHdlr.readPmParameters(); + execService = Executors.newScheduledThreadPool(5); + execService.scheduleAtFixedRate(() -> { + + rsPciHdlr.generatePmData(req.getNodeIdBad(), req.getNodeIdPoor()); + log.info("execService.isTerminated(): " + execService.isTerminated()); + + }, 0, 300, TimeUnit.SECONDS); + + isPmDataGenerating = true; + + return new ResponseEntity<>("Request generated.", HttpStatus.OK); + + } catch (Exception eu) { + log.error("Exception: ", eu); + return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); - Session wsSession = webSocketSessions.remove(ipPort); - log.info("removeWebSocketSessions: Client session " - + wsSession.getId() + " for " + ipPort - + " is removed. Server Id : " + removedServerId); - } else { - log.info("addWebSocketSessions: Client session for " + ipPort - + " not exist"); - } - } catch (Exception e) { - log.info("Exception in removeWebSocketSessions. e: " + e); } } /** - * Checks the number of ransim agents running. - * - * @param cellsToBeSimulated - * number of cells to be simulated - * @return returns true if there are enough ransim agents running + * Terminates the ScheduledExecutorService which sends the PM data at regular + * interval. + * + * @return returns HTTP status + * */ - public boolean hasEnoughRansimAgentsRunning(int cellsToBeSimulated) { + @ApiOperation("stop PM data") + @RequestMapping(value = "/stopPmData", method = RequestMethod.GET) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot start the simulation") }) + public ResponseEntity<String> stopPmData() throws Exception { - log.info("hasEnoughRansimAgentsRunning: numberOfCellsPerNCServer " - + numberOfCellsPerNcServer + " , webSocketSessions.size:" - + webSocketSessions.size() + " , cellsToBeSimulated:" - + cellsToBeSimulated); - log.info(strictValidateRansimAgentsAvailability); + try { + log.info("1. execService.isTerminated(): " + execService.isTerminated()); + if (!execService.isTerminated()) { + execService.shutdown(); + log.info("2. execService.isTerminated(): " + execService.isTerminated()); - if (strictValidateRansimAgentsAvailability) { - if (numberOfCellsPerNcServer * webSocketSessions.size() < cellsToBeSimulated) { - return false; } + isPmDataGenerating = false; + return new ResponseEntity<>("PM data generated.", HttpStatus.OK); + + } catch (Exception eu) { + log.error("Exception: ", eu); + return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); } - return true; + } /** - * It updates the constant values in the properties file. + * Get the status of ScheduledExecutorService, whether active or terminated. + * + * @return return the status + * */ - public void loadProperties() { - InputStream input = null; + @ApiOperation("get PM data status") + @RequestMapping(value = "/GetPmDataStatus", method = RequestMethod.GET) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot get information") }) + public boolean getPmDataStatus() throws Exception { + try { - input = new FileInputStream( - "/tmp/ransim-install/config/ransim.properties"); - netconfConstants.load(input); - serverIdPrefix = netconfConstants.getProperty("serverIdPrefix"); - numberOfCellsPerNcServer = Integer.parseInt(netconfConstants - .getProperty("numberOfCellsPerNCServer")); - numberOfMachines = Integer.parseInt(netconfConstants - .getProperty("numberOfMachines")); - numberOfProcessPerMc = Integer.parseInt(netconfConstants - .getProperty("numberOfProcessPerMc")); - strictValidateRansimAgentsAvailability = Boolean - .parseBoolean(netconfConstants - .getProperty("strictValidateRansimAgentsAvailability")); - sdnrServerIp = netconfConstants.getProperty("sdnrServerIp"); - sdnrServerPort = Integer.parseInt(netconfConstants - .getProperty("sdnrServerPort")); - sdnrServerUserid = netconfConstants.getProperty("sdnrServerUserid"); - sdnrServerPassword = netconfConstants - .getProperty("sdnrServerPassword"); - dumpFileName = netconfConstants.getProperty("dumpFileName"); - maxPciValueAllowed = Long.parseLong(netconfConstants - .getProperty("maxPciValueAllowed")); - - } catch (Exception e) { - log.info("Properties file error", e); - } finally { - try { - if (input != null) { - input.close(); - } - } catch (Exception ex) { - log.info("Properties file error", ex); - } + return isPmDataGenerating; + } catch (Exception eu) { + log.error("Exception: ", eu); + return false; } + } /** - * The function adds the cell(with nodeId passed as an argument) to its - * netconf server list if the netconf server already exists. Else it will - * create a new netconf server in the NetconfServers Table and the cell into - * its list. + * The function retrieves RAN simulation network topology. + * + * @return returns Http status + * @throws Exception throws exceptions in the functions * - * @param nodeId - * node Id of the cell */ - static void setNetconfServers(String nodeId) { + @ApiOperation("Retrieves RAN simulation network topology") + @RequestMapping(value = "/GetTopology", method = RequestMethod.GET) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot retrieve the RAN simulation network topology details") }) + public ResponseEntity<String> getTopology() throws Exception { + log.debug("Inside getTopology..."); + try { + rsPciHdlr.checkCollisionAfterModify(); + List<CellDetails> cds = ransimRepo.getCellDetailsList(); - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - CellDetails currentCell = rsDb.getCellDetail(nodeId); + Topology top = new Topology(); - Set<CellDetails> newList = new HashSet<CellDetails>(); - try { - if (currentCell != null) { - NetconfServers server = rsDb.getNetconfServer(currentCell - .getServerId()); + if (cds != null && cds.size() > 0) { + top.setMinScreenX(cds.get(0).getScreenX()); + top.setMaxScreenX(cds.get(0).getScreenX()); + top.setMinScreenY(cds.get(0).getScreenY()); + top.setMaxScreenY(cds.get(0).getScreenY()); - if (server == null) { + for (int i = 0; i < cds.size(); i++) { + if (cds.get(i).getScreenX() < top.getMinScreenX()) { + top.setMinScreenX(cds.get(i).getScreenX()); + } + if (cds.get(i).getScreenY() < top.getMinScreenY()) { + top.setMinScreenY(cds.get(i).getScreenY()); + } - server = new NetconfServers(); - server.setServerId(currentCell.getServerId()); - } else { - newList.addAll(server.getCells()); + if (cds.get(i).getScreenX() > top.getMaxScreenX()) { + top.setMaxScreenX(cds.get(i).getScreenX()); + } + if (cds.get(i).getScreenY() > top.getMaxScreenY()) { + top.setMaxScreenY(cds.get(i).getScreenY()); + } } + top.setCellTopology(cds); + } + top.setGridSize(rscServices.gridSize); - newList.add(currentCell); - server.setCells(newList); - log.info("setNetconfServers: nodeId: " + nodeId + ", X:" - + currentCell.getGridX() + ", Y:" - + currentCell.getGridY() + ", ip: " + server.getIp() - + ", portNum: " + server.getNetconfPort() - + ", serverId:" + currentCell.getServerId()); - - rsDb.mergeNetconfServers(server); + Gson gson = new Gson(); + String jsonStr = gson.toJson(top); - } + return new ResponseEntity<>(jsonStr, HttpStatus.OK); } catch (Exception eu) { - log.info("/setNetconfServers Function Error", eu); - + log.error("GetTopology", eu); + return new ResponseEntity<>("Failure", HttpStatus.INTERNAL_SERVER_ERROR); } } - private static double degToRadians(double angle) { - double radians = 57.2957795; - return (angle / radians); - } + /** + * The function retrieves the neighbor list details for the cell with the + * mentioned nodeId. + * + * @param req gets the necessary details as a request of class type + * GetNeighborListReq + * @return returns Http status + * @throws Exception throws exceptions in the functions + */ + @ApiOperation("Retrieves the neighbor list details for the cell with the mentioned nodeId") + @RequestMapping(value = "/GetNeighborList", method = RequestMethod.POST) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot Insert the given parameters") }) + public ResponseEntity<String> getNeighborList(@RequestBody GetNeighborListReq req) throws Exception { + log.debug("Inside getNeighborList..."); - private static double metersDeglon(double angle) { + try { + String jsonStr = ""; - double d2r = degToRadians(angle); - return ((111415.13 * Math.cos(d2r)) - (94.55 * Math.cos(3.0 * d2r)) + (0.12 * Math - .cos(5.0 * d2r))); + GetNeighborList message = rsPciHdlr.generateNeighborList(req.getNodeId()); - } + if (message != null) { - private static double metersDeglat(double angle) { + log.info("message.getNodeId(): " + message.getNodeId()); - double d2r = degToRadians(angle); - return (111132.09 - (566.05 * Math.cos(2.0 * d2r)) - + (1.20 * Math.cos(4.0 * d2r)) - (0.002 * Math.cos(6.0 * d2r))); + Gson gson = new Gson(); + jsonStr = gson.toJson(message); + } + return new ResponseEntity<>(jsonStr, HttpStatus.OK); + } catch (Exception eu) { + log.info("/getNeighborList", eu); + return new ResponseEntity<>("Failure", HttpStatus.INTERNAL_SERVER_ERROR); + } } /** - * generateClusterFromFile() - * - * @throws IOException + * The function retrieves the neighbor list for the cell with the mentioned + * nodeId. + * + * @param req gets the necessary details as a request of class type + * GetNeighborListReq + * @return returns Http status + * @throws Exception throws exceptions in the functions */ - static void generateClusterFromFile() throws IOException { - - EntityManagerFactory emfactory = Persistence - .createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - log.info("Inside generateClusterFromFile"); - File dumpFile = null; - String cellDetailsString = ""; + @ApiOperation("Retrieves the neighbor list details for the cell with the mentioned nodeId") + @RequestMapping(value = "/GetNeighborBlacklistDetails", method = RequestMethod.POST) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot Insert the given parameters") }) + public ResponseEntity<String> getNeighborBlacklistDetails(@RequestBody GetNeighborListReq req) throws Exception { + log.debug("Inside getNeighborList..."); - dumpFile = new File(dumpFileName); - - BufferedReader br = null; try { - log.info("Reading dump file"); - br = new BufferedReader(new FileReader(dumpFile)); - - StringBuilder sb = new StringBuilder(); - String line = br.readLine(); - while (line != null) { - sb.append(line); - sb.append("\n"); - line = br.readLine(); - } - cellDetailsString = sb.toString(); - - TopologyDump dumpTopo = new Gson().fromJson(cellDetailsString, - TopologyDump.class); - CellDetails cellsDb = new CellDetails(); - - log.info("dumpTopo.getCellList().size():" - + dumpTopo.getCellList().size()); - for (int i = 0; i < dumpTopo.getCellList().size(); i++) { - Gson g = new Gson(); - String pnt = g.toJson(dumpTopo.getCellList().get(i)); - log.info("Creating Cell:" + pnt); - log.info("Creating Cell:" - + dumpTopo.getCellList().get(i).getCell().getNodeId()); - - cellsDb = new CellDetails(); - entitymanager.getTransaction().begin(); - cellsDb.setNodeId(dumpTopo.getCellList().get(i).getCell() - .getNodeId()); - cellsDb.setPhysicalCellId(dumpTopo.getCellList().get(i) - .getCell().getPhysicalCellId()); - cellsDb.setLongitude(dumpTopo.getCellList().get(i).getCell() - .getLongitude()); - cellsDb.setLatitude(dumpTopo.getCellList().get(i).getCell() - .getLatitude()); - cellsDb.setServerId(dumpTopo.getCellList().get(i).getCell() - .getPnfName()); - if (!unassignedServerIds.contains(cellsDb.getServerId())) { - unassignedServerIds.add(cellsDb.getServerId()); - } - cellsDb.setNetworkId(dumpTopo.getCellList().get(i).getCell() - .getNetworkId()); - - double lon = Float.valueOf(dumpTopo.getCellList().get(i) - .getCell().getLongitude()); - double lat = Float.valueOf(dumpTopo.getCellList().get(i) - .getCell().getLatitude()); - - double xx = (lon - 0) * metersDeglon(0); - double yy = (lat - 0) * metersDeglat(0); - - double rad = Math.sqrt(xx * xx + yy * yy); + String jsonStr = ""; - if (rad > 0) { - double ct = xx / rad; - double st = yy / rad; - xx = rad * ((ct * Math.cos(0)) + (st * Math.sin(0))); - yy = rad * ((st * Math.cos(0)) - (ct * Math.sin(0))); - } - - cellsDb.setScreenX((float) (xx)); - cellsDb.setScreenY((float) (yy)); + CellNeighbor neighborList = ransimRepo.getCellNeighbor(req.getNodeId()); - List<String> attachedNoeds = serverIdIpNodeMapping.get(cellsDb - .getServerId()); - log.info("Attaching Cell:" - + dumpTopo.getCellList().get(i).getCell().getNodeId() - + " to " + cellsDb.getServerId()); - if (attachedNoeds == null) { - attachedNoeds = new ArrayList<String>(); - } - attachedNoeds.add(cellsDb.getNodeId()); - serverIdIpNodeMapping.put(cellsDb.getServerId(), attachedNoeds); - if (attachedNoeds.size() > numberOfCellsPerNcServer) { - log.warn("Attaching Cell:" - + dumpTopo.getCellList().get(i).getCell() - .getNodeId() + " to " - + cellsDb.getServerId() - + ", But it is exceeding numberOfCellsPerNcServer " - + numberOfCellsPerNcServer); - } + Map<String, String> result = new ConcurrentHashMap<String, String>(); - entitymanager.merge(cellsDb); - entitymanager.flush(); - entitymanager.getTransaction().commit(); + for (NeighborDetails nd : neighborList.getNeighborList()) { - setNetconfServers(cellsDb.getNodeId()); + result.put(nd.getNeigbor().getNeighborCell(), "" + nd.isBlacklisted()); } - dumpSessionDetails(); - - try { - - for (int i = 0; i < dumpTopo.getCellList().size(); i++) { - - String cellNodeId = dumpTopo.getCellList().get(i).getCell() - .getNodeId(); - entitymanager.getTransaction().begin(); - - // neighbor list with the corresponding node id - CellNeighbor neighborList = entitymanager.find( - CellNeighbor.class, cellNodeId); - // cell with the corresponding nodeId - CellDetails currentCell = entitymanager.find( - CellDetails.class, cellNodeId); - - Set<NeighborDetails> newCell = new HashSet<NeighborDetails>(); - - if (currentCell != null) { - if (neighborList == null) { - neighborList = new CellNeighbor(); - neighborList.setNodeId(cellNodeId); - } - List<NbrDump> neighboursFromFile = dumpTopo - .getCellList().get(i).getNeighbor(); - log.info("Creating Neighbor for Cell :" + cellNodeId); - for (NbrDump a : neighboursFromFile) { - String id = a.getNodeId().trim(); - boolean noHo = Boolean.parseBoolean(a - .getBlacklisted().trim()); - CellDetails neighborCell = entitymanager.find( - CellDetails.class, id); - NeighborDetails neighborDetails = new NeighborDetails( - new NeihborId(currentCell.getNodeId(), - neighborCell.getNodeId()), noHo); - - newCell.add(neighborDetails); - } - - neighborList.setNeighborList(newCell); - entitymanager.merge(neighborList); - entitymanager.flush(); - - entitymanager.getTransaction().commit(); - - rsPciHdlr.setCollisionConfusionFromFile(cellNodeId); - - } - - } - - } catch (Exception e1) { - log.info("Exception generateClusterFromFile :", e1); - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } + if (result != null) { + Gson gson = new Gson(); + jsonStr = gson.toJson(result); } + return new ResponseEntity<>(jsonStr, HttpStatus.OK); - try { - - long startTimeSectorNumber = System.currentTimeMillis(); - for (int i = 0; i < dumpTopo.getCellList().size(); i++) { - - CellData icellData = dumpTopo.getCellList().get(i); - CellDetails icell = entitymanager.find(CellDetails.class, - icellData.getCell().getNodeId()); - int icount = icell.getSectorNumber(); - if (icount == 0) { - entitymanager.getTransaction().begin(); - log.info("Setting sectorNumber for Cell(i) :" - + icell.getNodeId()); - int jcount = 0; - for (int j = (i + 1); j < dumpTopo.getCellList().size(); j++) { - - CellData jcellData = dumpTopo.getCellList().get(j); - if (icellData.getCell().getLatitude() - .equals(jcellData.getCell().getLatitude())) { - if (icellData - .getCell() - .getLongitude() - .equals(jcellData.getCell() - .getLongitude())) { - - if (icount == 0) { - icount++; - jcount = icount + 1; - } - - CellDetails jcell = entitymanager.find( - CellDetails.class, dumpTopo - .getCellList().get(j) - .getCell().getNodeId()); - - jcell.setSectorNumber(jcount); - log.info("Setting sectorNumber for Cell(j) :" - + jcell.getNodeId() - + " icell: " - + icell.getNodeId() - + " Sector number: " + jcount); - entitymanager.merge(jcell); - jcount++; - if (jcount > 3) { - break; - } - } - } - } - icell.setSectorNumber(icount); - entitymanager.merge(icell); - entitymanager.flush(); - entitymanager.getTransaction().commit(); - } - - } - - long endTimeSectorNumber = System.currentTimeMillis(); - log.info("Time taken for setting sector number: " - + (endTimeSectorNumber - startTimeSectorNumber)); - - } catch (Exception e3) { - log.info("Exception generateClusterFromFile :", e3); - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - } + } catch (Exception eu) { + log.error("/getNeighborList", eu); - } catch (Exception e) { - log.info("Exception generateClusterFromFile :", e); - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - } finally { - br.close(); - entitymanager.close(); - emfactory.close(); + return new ResponseEntity<>("Failure", HttpStatus.INTERNAL_SERVER_ERROR); } } /** - * The function deletes the cell from the database with the nodeId passed in - * the arguments. It removes the cell from its neighbor's neighbor list and - * the netconf server list. + * Changes the pci number or nbr list for the given cell. * - * @param nodeId - * node Id of the cell to be deleted. - * @return returns success or failure message + * @param req gets the necessary details as a request of class type + * ModifyACellReq + * @return returns Http status + * @throws Exception throws exceptions in the functions */ - public static String deleteCellFunction(String nodeId) { - String result = "failure node dosent exist"; - log.info("deleteCellFunction called with nodeId :" + nodeId); - RansimControllerDatabase rsDb = new RansimControllerDatabase(); + @ApiOperation("Changes the pci number or nbr list for the given cell") + @RequestMapping(value = "/ModifyACell", method = RequestMethod.POST) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot update the PCI for the given cell") }) + public ResponseEntity<String> modifyACell(@RequestBody ModifyACellReq req) throws Exception { + log.debug("Inside ModifyCell..."); try { - CellDetails deleteCelldetail = rsDb.getCellDetail(nodeId); - - CellNeighbor deleteCellNeighbor = rsDb.getCellNeighbor(nodeId); - - if (deleteCelldetail != null) { - if (deleteCellNeighbor != null) { - List<CellNeighbor> cellNeighborList = rsDb - .getCellNeighborList(); - for (CellNeighbor cellNeighbors : cellNeighborList) { - Set<NeighborDetails> currentCellNeighbors = new HashSet<NeighborDetails>( - cellNeighbors.getNeighborList()); - - NeihborId deleteNeighborDetail = new NeihborId( - cellNeighbors.getNodeId(), - deleteCelldetail.getNodeId()); - - if (currentCellNeighbors.contains(deleteNeighborDetail)) { - log.info("Deleted Cell is Neighbor of NodeId : " - + cellNeighbors.getNodeId()); - currentCellNeighbors.remove(deleteNeighborDetail); - cellNeighbors.setNeighborList(currentCellNeighbors); - rsDb.mergeCellNeighbor(cellNeighbors); - } - } + long startTimemodifyCell = System.currentTimeMillis(); - deleteCellNeighbor.getNeighborList().clear(); - rsDb.deleteCellNeighbor(deleteCellNeighbor); - } + String nbrsStr = req.getNewNbrs(); + if (req.getNewNbrs() == null) { + nbrsStr = ""; + } + String source = "GUI"; + List<NeighborDetails> nbrsList = new ArrayList<NeighborDetails>(); + String[] newNbrsArr = nbrsStr.split(","); - rsDb.deleteCellDetails(deleteCelldetail); - result = "cell has been deleted from the database"; + for (int i = 0; i < newNbrsArr.length; i++) { + NeighborDetails cell = new NeighborDetails(new NeihborId(req.getNodeId(), newNbrsArr[i].trim()), false); + nbrsList.add(cell); + } + + int result = rsPciHdlr.modifyCellFunction(req.getNodeId(), req.getNewPhysicalCellId(), nbrsList, source); + rscServices.handleModifyPciFromGui(req.getNodeId(), req.getNewPhysicalCellId()); + long endTimemodifyCell = System.currentTimeMillis(); + log.info("Time taken to modify cell : " + (endTimemodifyCell - startTimemodifyCell)); + + if (result == 200) { + return new ResponseEntity<String>(HttpStatus.OK); + } else if (result == 400) { + return new ResponseEntity<String>(HttpStatus.BAD_REQUEST); } else { - log.info("cell id does not exist"); - result = "failure nodeId dosent exist"; - return result; + return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); } - } catch (Exception eu) { - log.info("Exception deleteCellFunction :", eu); - result = "exception in function"; + } catch (Exception eu) { + log.error("Exception in modifyACell", eu); + return new ResponseEntity<>("Cannot update the PCI for the given cell", HttpStatus.INTERNAL_SERVER_ERROR); } - return result; + } /** - * Send configuration details to all the netconf server. + * The function changes the PCI number of the cell for the the mentioned nodeId. + * + * @param req gets the necessary details as a request of class type + * GetACellDetailReq + * @return returns Http status + * @throws Exception throws exceptions in the functions */ - public void sendInitialConfigAll() { - RansimControllerDatabase rsDb = new RansimControllerDatabase(); + @ApiOperation("Changes the pci number of the cell for the the mentioned nodeId") + @PostMapping(value = "/GetACellDetail") + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot retrive the cell details for the given cell") }) + public ResponseEntity<String> getACellDetail(@RequestBody GetACellDetailReq req) throws Exception { + + log.debug("Inside GetACellDetailReq..."); try { - dumpSessionDetails(); - List<NetconfServers> ncServers = rsDb.getNetconfServersList(); - for (NetconfServers netconfServers : ncServers) { - String ipPortKey = serverIdIpPortMapping.get(netconfServers - .getServerId()); - if (ipPortKey == null || ipPortKey.trim().equals("")) { - log.info("No client for " + netconfServers.getServerId()); - for (String ipPortKeyStr : webSocketSessions.keySet()) { - if (!serverIdIpPortMapping.containsValue(ipPortKeyStr)) { - serverIdIpPortMapping.put( - netconfServers.getServerId(), ipPortKeyStr); - ipPortKey = ipPortKeyStr; - break; - } - } - } - if (ipPortKey != null && !ipPortKey.trim().equals("")) { - Session clSess = webSocketSessions.get(ipPortKey); - if (clSess != null) { - sendInitialConfig(netconfServers.getServerId()); - try { - String[] agentDetails = ipPortKey.split(":"); - new RestClient().sendMountRequestToSdnr( - netconfServers.getServerId(), sdnrServerIp, - sdnrServerPort, agentDetails[0], - agentDetails[1], sdnrServerUserid, - sdnrServerPassword); - } catch (Exception ex1) { - log.info("Ignoring exception", ex1); - } - - } else { - log.info("No session for " + ipPortKey); - } - } + String jsonStr = null; + + CellDetails cd = ransimRepo.getCellDetail(req.getNodeId()); + if (cd != null) { + Gson gson = new Gson(); + jsonStr = gson.toJson(cd); } + return new ResponseEntity<>(jsonStr, HttpStatus.OK); + } catch (Exception eu) { - log.info("Exception:", eu); + log.error("Exception in getACellDetail : {} ", eu); + return new ResponseEntity<>("Cannot update the PCI for the given cell", HttpStatus.INTERNAL_SERVER_ERROR); } } /** - * Sends initial configuration details of the cells for a new netconf server - * that has been started. + * The function deletes a cell with the mentioned nodeId. * - * @param ipPortKey - * ip address details of the netconf server + * @param req gets the necessary details as a request of class type + * DeleteACellReq + * @return returns Http status + * @throws Exception throws exceptions in the functions */ - public void sendInitialConfigForNewAgent(String ipPortKey, String serverId) { + @ApiOperation("Deletes a cell with the mentioned nodeId") + @RequestMapping(value = "/DeleteACell", method = RequestMethod.POST) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot delete the given cell") }) + public ResponseEntity<String> deleteACell(@RequestBody DeleteACellReq req) throws Exception { + log.debug("Inside delete cell..."); + try { - dumpSessionDetails(); - if (ipPortKey != null && !ipPortKey.trim().equals("")) { - if (serverId != null && !serverId.trim().equals("")) { - Session clSess = webSocketSessions.get(ipPortKey); - if (clSess != null) { - String[] agentDetails = ipPortKey.split(":"); - sendInitialConfig(serverId); - new RestClient().sendMountRequestToSdnr(serverId, - sdnrServerIp, sdnrServerPort, agentDetails[0], - agentDetails[1], sdnrServerUserid, - sdnrServerPassword); - } else { - log.info("No session for " + ipPortKey); - } - } else { - log.info("No serverid for " + ipPortKey); - } - } else { - log.info("Invalid ipPortKey " + ipPortKey); - } + long startTimeDeleteCell = System.currentTimeMillis(); + String result = rscServices.deleteCellFunction(req.getNodeId()); + long endTimeDeleteCell = System.currentTimeMillis(); + log.info("Time taken to delete cell : " + (endTimeDeleteCell - startTimeDeleteCell)); + return new ResponseEntity<String>(HttpStatus.OK); + } catch (Exception eu) { - log.info("Exception:", eu); + log.error("Exception in deleteACell", eu); + return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); } } /** - * To send the initial configration to the netconf server. + * The function stops RAN network simulation and deletes all the cell data from + * the database. * - * @param serverId - * ip address details of the netconf server + * @return returns Http status + * @throws Exception throws exceptions in the functions */ - public void sendInitialConfig(String serverId) { + @ApiOperation("Stops RAN network simulation and deletes all the cell data from the database") + @RequestMapping(value = "/StopSimulation", method = RequestMethod.DELETE) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot stop simulation") }) + public ResponseEntity<String> stopSimulation() throws Exception { + log.debug("Inside stopSimulation..."); + + if (ransimRepo.getCellDetailsList().isEmpty()) { + return new ResponseEntity<>("No simulation is running.", HttpStatus.INTERNAL_SERVER_ERROR); + } - RansimControllerDatabase rsDb = new RansimControllerDatabase(); try { - NetconfServers server = rsDb.getNetconfServer(serverId); - log.info("sendInitialConfig: serverId:" + serverId + ", server:" - + server); - if (server == null) { - return; - } - - String ipPortKey = serverIdIpPortMapping.get(serverId); - - log.info("sendInitialConfig: ipPortKey:" + ipPortKey); - - List<CellDetails> cellList = new ArrayList<CellDetails>( - server.getCells()); - - List<Topology> config = new ArrayList<Topology>(); - - for (int i = 0; i < server.getCells().size(); i++) { - Topology cell = new Topology(); - CellDetails currentCell = rsDb.getCellDetail(cellList.get(i) - .getNodeId()); - CellNeighbor neighbor = rsDb.getCellNeighbor(cellList.get(i) - .getNodeId()); - - cell.setCellId("" + currentCell.getNodeId()); - cell.setPciId(currentCell.getPhysicalCellId()); - cell.setPnfName(serverId); - - List<Neighbor> nbrList = new ArrayList<Neighbor>(); - Set<NeighborDetails> nbrsDet = neighbor.getNeighborList(); - for (NeighborDetails cellDetails : nbrsDet) { - Neighbor nbr = new Neighbor(); - CellDetails nbrCell = rsDb.getCellDetail(cellDetails - .getNeigbor().getNeighborCell()); - nbr.setNodeId(nbrCell.getNodeId()); - nbr.setPhysicalCellId(nbrCell.getPhysicalCellId()); - nbr.setPnfName(nbrCell.getServerId()); - nbr.setServerId(nbrCell.getServerId()); - nbr.setPlmnId(nbrCell.getNetworkId()); - nbr.setBlacklisted(cellDetails.isBlacklisted()); - nbrList.add(nbr); - } - cell.setNeighborList(nbrList); - config.add(i, cell); - } - - SetConfigTopology topo = new SetConfigTopology(); + long startTimStopSimulation = System.currentTimeMillis(); + ransimRepo.deleteNetconfServers(); + ransimRepo.deleteCellNeighbors(); + log.info("Stop simulation : " + (startTimStopSimulation)); + ransimRepo.deleteAllCellDetails(); + String result = rscServices.stopAllSimulation(); + log.info("All cell simulation are stopped...." + result); + long endTimStopSimulation = System.currentTimeMillis(); + log.info("Time taken for stopping simulation : " + (endTimStopSimulation - startTimStopSimulation)); + return new ResponseEntity<>("Success", HttpStatus.OK); - topo.setServerId(server.getServerId()); - String uuid = globalNcServerUuidMap.get(server.getServerId()); - if (uuid == null) { - uuid = getUuid(); - globalNcServerUuidMap.put(server.getServerId(), uuid); - } - topo.setUuid(uuid); + } catch (Exception eu) { + log.error("Exception in stopSimulation", eu); + return new ResponseEntity<>("Failure", HttpStatus.INTERNAL_SERVER_ERROR); + } - topo.setTopology(config); + } + + @ApiOperation("Stops RAN Slicing network simulation and deletes all the data from the database") + @RequestMapping(value = "/StopRanSliceSimulation", method = RequestMethod.DELETE) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot stop simulation") }) + public ResponseEntity<String> stopRanSliceSimulation() throws Exception { + log.debug("Inside stopSimulation..."); + if (ransimRepo.getCellDetailsList().isEmpty()) { + return new ResponseEntity<>("No simulation is running.", HttpStatus.INTERNAL_SERVER_ERROR); + } - Gson gson = new Gson(); - String jsonStr = gson.toJson(topo); - log.info("ConfigTopologyMessage: " + jsonStr); - Session clSess = webSocketSessions.get(ipPortKey); - RansimWebSocketServer.sendSetConfigTopologyMessage(jsonStr, clSess); + try { + long startTimStopSimulation = System.currentTimeMillis(); + ransimRepo.deleteNetconfServers(); + log.info("Stop simulation : " + (startTimStopSimulation)); + String result = rscServices.stopAllSimulation(); + log.info("All cell simulation are stopped...." + result); + long endTimStopSimulation = System.currentTimeMillis(); + log.info("Time taken for stopping simulation : " + (endTimStopSimulation - startTimStopSimulation)); + return new ResponseEntity<>("Simulation stopped", HttpStatus.OK); } catch (Exception eu) { - log.info("Exception:", eu); + log.error("Exception in stopRanSliceSimulation", eu); + return new ResponseEntity<>("Failure", HttpStatus.INTERNAL_SERVER_ERROR); } } - private static String getUuid() { - return UUID.randomUUID().toString(); - } - /** - * The function alters the database information based on the modifications - * made in the SDNR. + * The function returns the details of a Netconf server for the mentioned server + * id. * - * @param message - * message received from the SDNR - * @param session - * sends the session details - * @param ipPort - * ip address of the netconf server + * @param req gets the necessary details as a request of class type + * GetNetconfServerDetailsReq + * @return returns Http status + * @throws Exception throws exceptions in the functions */ - public void handleModifyPciFromSdnr(String message, Session session, - String ipPort) { - log.info("handleModifyPciFromSDNR: message:" + message + " session:" - + session + " ipPort:" + ipPort); - RansimControllerDatabase rcDb = new RansimControllerDatabase(); - ModifyPci modifyPci = new Gson().fromJson(message, ModifyPci.class); - log.info("handleModifyPciFromSDNR: modifyPci:" + modifyPci.getCellId() - + "; pci: " + modifyPci.getPciId()); - String source = "Netconf"; - - CellDetails cd = rcDb.getCellDetail(modifyPci.getCellId()); - long pci = cd.getPhysicalCellId(); - cd.setPhysicalCellId(modifyPci.getPciId()); - rcDb.mergeCellDetails(cd); - rsPciHdlr.updatePciOperationsTable(modifyPci.getCellId(), source, pci, - modifyPci.getPciId()); - } + @ApiOperation("Returns the details of a Netconf server for the mentioned server id") + @RequestMapping(value = "/GetNetconfServerDetails", method = RequestMethod.POST) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Failure in GetNetconfServerDetails API") }) + public ResponseEntity<String> getNetconfServerDetails(@RequestBody GetNetconfServerDetailsReq req) + throws Exception { - /** - * The function alters the database information based on the modifications - * made in the SDNR. - * - * @param message - * message received from the SDNR - * @param session - * sends the session details - * @param ipPort - * ip address of the netconf server - */ - public void handleModifyNeighborFromSdnr(String message, Session session, - String ipPort) { - log.info("handleModifyAnrFromSDNR: message:" + message + " session:" - + session + " ipPort:" + ipPort); - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - ModifyNeighbor modifyNeighbor = new Gson().fromJson(message, - ModifyNeighbor.class); - log.info("handleModifyAnrFromSDNR: modifyPci:" - + modifyNeighbor.getCellId()); - CellDetails currentCell = rsDb - .getCellDetail(modifyNeighbor.getCellId()); - List<NeighborDetails> neighborList = new ArrayList<NeighborDetails>(); - List<String> cellList = new ArrayList<String>(); - cellList.add(modifyNeighbor.getCellId()); - String nbrsAdd = ""; - String nbrsDel = ""; - String source = "Netconf"; - - for (int i = 0; i < modifyNeighbor.getNeighborList().size(); i++) { - if (modifyNeighbor.getNeighborList().get(i).isBlacklisted()) { - NeighborDetails nd = new NeighborDetails(new NeihborId( - modifyNeighbor.getCellId(), modifyNeighbor - .getNeighborList().get(i).getNodeId()), true); - rsDb.mergeNeighborDetails(nd); - cellList.add(modifyNeighbor.getNeighborList().get(i) - .getNodeId()); - if (nbrsAdd.equals("")) { - nbrsDel = modifyNeighbor.getNeighborList().get(i) - .getNodeId(); + try { + log.debug("Inside GetNetconfServerDetails API..."); + String result = ""; + String input = req.getServerId(); + if (input.startsWith("Chn")) { + CellDetails cds = ransimRepo.getCellDetail(input); + if (cds != null) { + Gson gson = new Gson(); + String jsonStr = gson.toJson(cds); + result = "{\"serverId\":\"any\",\"cells\":[" + jsonStr + "]}"; } else { - nbrsDel += "," - + modifyNeighbor.getNeighborList().get(i) - .getNodeId(); + result = ("Cell Id does not exist"); } } else { - NeighborDetails nd = new NeighborDetails(new NeihborId( - modifyNeighbor.getCellId(), modifyNeighbor - .getNeighborList().get(i).getNodeId()), false); - rsDb.mergeNeighborDetails(nd); - cellList.add(modifyNeighbor.getNeighborList().get(i) - .getNodeId()); - if (nbrsDel.equals("")) { - nbrsAdd = modifyNeighbor.getNeighborList().get(i) - .getNodeId(); + NetconfServers ns = ransimRepo.getNetconfServer(input); + if (ns != null) { + Gson gson = new Gson(); + String jsonStr = gson.toJson(ns); + result = jsonStr; } else { - nbrsAdd += "," - + modifyNeighbor.getNeighborList().get(i) - .getNodeId(); + result = ("Server Id does not exist"); } } + return new ResponseEntity<>(result, HttpStatus.OK); + } catch (Exception eu) { + log.error("/GetNetconfServers", eu); + return new ResponseEntity<>("Failure in GetNetconfServerDetails API", HttpStatus.INTERNAL_SERVER_ERROR); } - - for (String cl : cellList) { - RansimPciHandler.setCollisionConfusionFromFile(cl); - } - - log.info("neighbor list: " + neighborList); - - rsPciHdlr.updateNbrsOperationsTable(modifyNeighbor.getCellId(), source, - nbrsAdd, nbrsDel); } - /** - * The function sends the modification made in the GUI to the netconf - * server. - * - * @param cellId - * node Id of the cell which was modified - * @param pciId - * PCI number of the cell which was modified - */ - public void handleModifyPciFromGui(String cellId, long pciId) { - log.info("handleModifyPciFromGUI: cellId:" + cellId + " pciId:" + pciId); - RansimControllerDatabase rsDb = new RansimControllerDatabase(); + @ApiOperation("Returns the connection status of all netconf servers") + @RequestMapping(value = "/GetNetconfStatus", method = RequestMethod.GET) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Failure in GetNetconfServerDetails API") }) + public ResponseEntity<String> GetNetconfStatus() throws Exception { try { - CellDetails currentCell = rsDb.getCellDetail(cellId); - CellNeighbor neighborList = rsDb.getCellNeighbor(cellId); - List<Neighbor> nbrList = new ArrayList<Neighbor>(); - Iterator<NeighborDetails> iter = neighborList.getNeighborList() - .iterator(); - while (iter.hasNext()) { - NeighborDetails nbCell = iter.next(); - Neighbor nbr = new Neighbor(); - CellDetails nbrCell = rsDb.getCellDetail(nbCell.getNeigbor() - .getNeighborCell()); - - nbr.setNodeId(nbrCell.getNodeId()); - nbr.setPhysicalCellId(nbrCell.getPhysicalCellId()); - nbr.setPnfName(nbrCell.getNodeName()); - nbr.setServerId(nbrCell.getServerId()); - nbr.setPlmnId(nbrCell.getNetworkId()); - nbrList.add(nbr); + log.debug("Inside GetNetconfServerDetails API..."); + String result = ""; + + List<NetconfServers> ns = ransimRepo.getNetconfServersList(); + if (ns != null) { + GsonBuilder gsonBuilder = new GsonBuilder(); + gsonBuilder.serializeNulls(); + Gson gson = gsonBuilder.create(); + String jsonStr = gson.toJson(ns); + result = jsonStr; + } else { + result = ("Server Id does not exist"); } - String pnfName = currentCell.getServerId(); - String ipPort = serverIdIpPortMapping.get(pnfName); - log.info("handleModifyPciFromGui:ipPort >>>>>>> " + ipPort); - - if (ipPort != null && !ipPort.trim().equals("")) { - - String[] ipPortArr = ipPort.split(":"); - Topology oneCell = new Topology(pnfName, pciId, cellId, nbrList); - UpdateCell updatedPci = new UpdateCell( - currentCell.getServerId(), ipPortArr[0], ipPortArr[1], - oneCell); - Gson gson = new Gson(); - String jsonStr = gson.toJson(updatedPci); - if (ipPort != null && !ipPort.trim().equals("")) { - Session clSess = webSocketSessions.get(ipPort); - if (clSess != null) { - RansimWebSocketServer.sendUpdateCellMessage(jsonStr, - clSess); - log.info("handleModifyPciFromGui, message: " + jsonStr); - } else { - log.info("No client session for " + ipPort); - } - } else { - log.info("No client for " + currentCell.getServerId()); - } - } + return new ResponseEntity<>(result, HttpStatus.OK); } catch (Exception eu) { - - log.info("Exception:", eu); + log.error("/GetNetconfServers", eu); + return new ResponseEntity<>("Failure in GetNetconfServerDetails API", HttpStatus.INTERNAL_SERVER_ERROR); } } /** - * The function unmounts the connection with SDNR. + * The function retrieves RAN simulation network topology. + * + * @return returns Http status + * @throws Exception throws exceptions in the functions * - * @return returns null value */ - public String stopAllCells() { - RansimControllerDatabase rcDb = new RansimControllerDatabase(); + @ApiOperation("Retrieves operations log - Modify/Delete operations performed") + @GetMapping(value = "/GetOperationLog") + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot retrieve the Operation Logs") }) + public ResponseEntity<String> getOperationLog() throws Exception { + log.debug("Inside getOperationLog..."); try { - List<NetconfServers> ncServers = rcDb.getNetconfServersList(); - for (NetconfServers netconfServers : ncServers) { - try { - log.info("Unmount " + netconfServers.getServerId()); - new RestClient().sendUnmountRequestToSdnr( - netconfServers.getServerId(), sdnrServerIp, - sdnrServerPort, sdnrServerUserid, - sdnrServerPassword); - } catch (Exception e) { - log.info("Ignore Exception:", e); - } - serverIdIpNodeMapping.clear(); + List<OperationLog> ols = ransimRepo.getOperationLogList(); + if (ols != null && ols.size() > 0) { + Gson gson = new Gson(); + String jsonStr = gson.toJson(ols); + return new ResponseEntity<>(jsonStr, HttpStatus.OK); + } else { + return new ResponseEntity<>("", HttpStatus.OK); } - return "Netconf servers unmounted."; } catch (Exception eu) { - - log.info("Exception:", eu); - return "Error"; - } - - } - - /** - * Used to dump session details. - */ - synchronized public static void dumpSessionDetails() { - - try { - - log.info("serverIdIpPortMapping.size:" - + serverIdIpPortMapping.size() + "webSocketSessions.size" - + webSocketSessions.size()); - for (String key : serverIdIpPortMapping.keySet()) { - String val = serverIdIpPortMapping.get(key); - Session sess = webSocketSessions.get(val); - log.info("ServerId:" + key + " IpPort:" + val + " Session:" - + sess); - } - for (String serverId : unassignedServerIds) { - log.info("Unassigned ServerId:" + serverId); - } - for (String serverId : serverIdIpPortMapping.keySet()) { - List<String> attachedNoeds = serverIdIpNodeMapping - .get(serverId); - if (attachedNoeds != null) { - log.info("ServerId:" + serverId + " attachedNoeds.size:" - + attachedNoeds.size() + " nodes:" - + attachedNoeds.toArray()); - } else { - log.info("ServerId:" + serverId + " attachedNoeds:" + null); - } - } - } catch (Exception e) { - log.info("Exception:", e); + log.error("/GetOperationLog", eu); + return new ResponseEntity<>("Failure", HttpStatus.INTERNAL_SERVER_ERROR); } } -} - -class KeepWebsockAliveThread extends Thread { - static Logger log = Logger - .getLogger(KeepWebsockAliveThread.class.getName()); - RansimController rsCtrlr = null; - KeepWebsockAliveThread(RansimController ctrlr) { - rsCtrlr = ctrlr; - } - - @Override - public void run() { - log.info("Inside KeepWebsockAliveThread run method"); - while (true) { - for (String ipPort : rsCtrlr.webSocketSessions.keySet()) { - try { - Session sess = rsCtrlr.webSocketSessions.get(ipPort); - RansimWebSocketServer.sendPingMessage(sess); - log.debug("Sent ping message to Client ipPort:" + ipPort); - } catch (Exception ex1) { - } - } - try { - Thread.sleep(10000); - } catch (Exception ex) { - } - } - } + @ApiOperation("Generate IntelligentSlicing PM data") + @RequestMapping(value = "/GenerateIntelligentSlicingPmData", method = RequestMethod.POST) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot t the simulation") }) + public ResponseEntity<String> generateIntelligentSlicingPmData(){ + log.info("******************Request to generate***************************"); + + try { + long startTime = (System.currentTimeMillis()); + Iterable<TACells> tacellList = ranSliceConfigService.fetchAllTA(); + HashMap<String,List<String>> taCells = new HashMap<>(); + for(TACells ta : tacellList) + { + String[] cells = ta.getCellsList().split(","); + List<String> cellList = new ArrayList<String>(Arrays.asList(cells)); + taCells.put(ta.getTrackingArea(),cellList); + } + execServiceForIntelligentSlicing = Executors.newScheduledThreadPool(5); + execServiceForIntelligentSlicing.scheduleAtFixedRate( + () -> { + + ranSliceHandler.generateIntelligentSlicingPmData(startTime,taCells); + log.info("execServiceforIntelligentSlicing.isTerminated(): " + execServiceForIntelligentSlicing.isTerminated()); + + }, 0, 10, TimeUnit.SECONDS); + + isIntelligentSlicingPmDataGenerating = true; + + + + } catch (Exception eu) { + log.info("Exception: ", eu); + return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); + + } + return new ResponseEntity<>("IntelligentSlicing PM data generated.", HttpStatus.OK); + } + + @ApiOperation("Stop IntelligentSlicing PM data") + @RequestMapping(value = "/stopIntelligentSlicingPmData", method = RequestMethod.POST) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot start the simulation") }) + public ResponseEntity<String> stopIntelligentSlicingPmData() throws Exception { + + try { + log.info("1. execServiceForIntelligentSlicing.isTerminated(): " + execServiceForIntelligentSlicing.isTerminated()); + if (!execServiceForIntelligentSlicing.isTerminated()) { + execServiceForIntelligentSlicing.shutdown(); + log.info("2. execServiceForIntelligentSlicing.isTerminated(): " + execServiceForIntelligentSlicing.isTerminated()); + + } + isIntelligentSlicingPmDataGenerating = false; + return new ResponseEntity<>("Stopped PM data generation.", HttpStatus.OK); + + } catch (Exception eu) { + return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); + } + + } + + + /* + *Generate closed loopPM data for DUs + * + */ + @ApiOperation("Generate Closed loop PM data") + @RequestMapping(value = "/generateClosedLoopPmData", method = RequestMethod.POST) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Problem generating closed loop PM data") }) + public ResponseEntity<String> generateClosedLoopPmData() { + long startTime = (System.currentTimeMillis()); + log.info("Closed loop PM Data generation started at " + startTime); + closedLoopExecService = Executors.newScheduledThreadPool(5); + closedLoopExecService.scheduleAtFixedRate(() -> { + pmDataGenerator.generateClosedLoopPmData(startTime); + log.info("closedLoopexecService.isTerminated(): " + execServiceForIntelligentSlicing.isTerminated()); + + }, 0, 10, TimeUnit.SECONDS); + + return new ResponseEntity<>("Generating Closed loop PM data.", HttpStatus.OK); + } + + @ApiOperation("Stop Closed loop PM data") + @RequestMapping(value = "/stopClosedLoopPmData", method = RequestMethod.GET) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), + @ApiResponse(code = 500, message = "Cannot start the simulation") }) + public ResponseEntity<String> stopClosedLoopPmData() throws Exception { + + try { + log.info("1. closedLoopexecService.isTerminated(): " + closedLoopExecService.isTerminated()); + if (!closedLoopExecService.isTerminated()) { + closedLoopExecService.shutdown(); + log.info("2. closedLoopexecService.isTerminated(): " + closedLoopExecService.isTerminated()); + + } + return new ResponseEntity<>("Closed loop PM data generated.", HttpStatus.OK); + + } catch (Exception eu) { + return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); + } + + } } diff --git a/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RansimControllerDatabase.java b/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RansimControllerDatabase.java deleted file mode 100644 index 0d7ea3a..0000000 --- a/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RansimControllerDatabase.java +++ /dev/null @@ -1,409 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Ran Simulator Controller - * ================================================================================ - * Copyright (C) 2020 Wipro Limited. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.ransim.rest.api.controller; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.persistence.Query; -import javax.persistence.TypedQuery; - -import org.apache.log4j.Logger; -import org.onap.ransim.rest.api.models.CellDetails; -import org.onap.ransim.rest.api.models.CellNeighbor; -import org.onap.ransim.rest.api.models.NeighborDetails; -import org.onap.ransim.rest.api.models.NetconfServers; -import org.onap.ransim.rest.api.models.OperationLog; - -public class RansimControllerDatabase { - - static Logger log = Logger.getLogger(RansimControllerDatabase.class - .getName()); - - /** - * Gets the CellDetail from the database. - * - * @param nodeId Node Id of the cell(primary key) - * @return Returns the cell with mentioned node ID. - */ - CellDetails getCellDetail(String nodeId){ - EntityManagerFactory emfactory = Persistence - .createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - CellDetails currentCell = null; - - try{ - currentCell = entitymanager.find(CellDetails.class, nodeId); - }catch(Exception e){ - log.info("Exception in getCellDetail: " + e); - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - } - finally { - entitymanager.close(); - emfactory.close(); - } - - return currentCell; - - } - - /** - * - * @param serverId - * @return - */ - static NetconfServers getNetconfServer(String serverId){ - EntityManagerFactory emfactory = Persistence - .createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - NetconfServers ns = null; - - try{ - ns = entitymanager.find(NetconfServers.class, serverId); - }catch(Exception e){ - log.info("Exception in getCellDetail: " + e); - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - } - finally { - entitymanager.close(); - emfactory.close(); - } - - return ns; - - } - CellNeighbor getCellNeighbor(String nodeId){ - EntityManagerFactory emfactory = Persistence - .createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - CellNeighbor ns = null; - - try{ - ns = entitymanager.find(CellNeighbor.class, nodeId); - }catch(Exception e){ - log.info("Exception in getCellDetail: " + e); - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - } - finally { - entitymanager.close(); - emfactory.close(); - } - - return ns; - - } - - void deleteCellDetails(CellDetails deleteCelldetail){ - EntityManagerFactory emfactory = Persistence - .createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - - - - try{ - if (deleteCelldetail.getServerId() != null) { - entitymanager.getTransaction().begin(); - log.info("inside NetconfServers handling ...."); - NetconfServers ns = entitymanager.find(NetconfServers.class, deleteCelldetail.getServerId()); - ns.getCells().remove(deleteCelldetail); - entitymanager.merge(ns); - entitymanager.flush(); - entitymanager.getTransaction().commit(); - - } - entitymanager.getTransaction().begin(); - CellDetails cd = entitymanager.find(CellDetails.class, deleteCelldetail.getNodeId()); - entitymanager.remove(cd); - entitymanager.flush(); - entitymanager.getTransaction().commit(); - - }catch(Exception e){ - log.info("Exception in getCellDetail: " + e); - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - } - finally { - entitymanager.close(); - emfactory.close(); - } - } - - void deleteCellNeighbor(CellNeighbor deleteCellNeighbor){ - EntityManagerFactory emfactory = Persistence - .createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - - entitymanager.getTransaction().begin(); - - try{ - log.info("inside delete cel neighbor"); - CellNeighbor cn = entitymanager.find(CellNeighbor.class, deleteCellNeighbor.getNodeId()); - entitymanager.remove(cn); - entitymanager.flush(); - entitymanager.getTransaction().commit(); - log.info("removed cell neighbor from database"); - - }catch(Exception e){ - log.info("Exception in deleteCellNeighbor: " + e); - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - } - finally { - entitymanager.close(); - emfactory.close(); - } - } - - static void mergeCellDetails(CellDetails cellDetail){ - EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - try{ - entitymanager.getTransaction().begin(); - entitymanager.merge(cellDetail); - log.info("updated in database...."); - entitymanager.flush(); - entitymanager.getTransaction().commit(); - }catch (Exception eu) { - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - log.info("Exception:", eu); - } finally { - entitymanager.close(); - emfactory.close(); - } - } - - void mergeNeighborDetails(NeighborDetails neighborDetails){ - EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - try{ - entitymanager.getTransaction().begin(); - entitymanager.merge(neighborDetails); - log.info("updated in database...."); - entitymanager.flush(); - entitymanager.getTransaction().commit(); - } catch (Exception eu) { - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - log.info("Exception:", eu); - } finally { - entitymanager.close(); - emfactory.close(); - } - } - - void mergeNetconfServers(NetconfServers netconfServers){ - EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - try{ - entitymanager.getTransaction().begin(); - entitymanager.merge(netconfServers); - log.info("updated in database...."); - entitymanager.flush(); - entitymanager.getTransaction().commit(); - } catch (Exception eu) { - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - log.info("Exception:", eu); - } finally { - entitymanager.close(); - emfactory.close(); - } - } - - void mergeCellNeighbor(CellNeighbor cellNeighbor){ - EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - try{ - entitymanager.getTransaction().begin(); - log.info("updated in database...."); - entitymanager.merge(cellNeighbor); - entitymanager.flush(); - entitymanager.getTransaction().commit(); - } catch (Exception eu) { - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - log.info("Exception:", eu); - } finally { - entitymanager.close(); - emfactory.close(); - } - } - - List<CellDetails> getCellDetailsList(){ - EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - List<CellDetails> cds = new ArrayList<CellDetails>(); - try{ - entitymanager.getTransaction().begin(); - log.info("updated in database...."); - Query query = entitymanager.createQuery("from CellDetails cd", CellDetails.class); - cds = query.getResultList(); - entitymanager.flush(); - entitymanager.getTransaction().commit(); - } catch (Exception eu) { - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - log.info("Exception:", eu); - } finally { - entitymanager.close(); - emfactory.close(); - } - - return cds; - } - - List<CellDetails> getCellsWithNoServerIds(){ - EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - List<CellDetails> cds = new ArrayList<CellDetails>(); - try{ - entitymanager.getTransaction().begin(); - log.info("getCellswithNoServerIds: updated in database...."); - TypedQuery<CellDetails> query = entitymanager.createQuery( - "SELECT n FROM CellDetails WHERE n.serverId is null", CellDetails.class); - cds = query.getResultList(); - entitymanager.flush(); - entitymanager.getTransaction().commit(); - } catch (Exception eu) { - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - log.info("Exception:", eu); - } finally { - entitymanager.close(); - emfactory.close(); - } - - return cds; - } - - List<CellDetails> getCellsWithCollisionOrConfusion(){ - EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - List<CellDetails> cds = new ArrayList<CellDetails>(); - try{ - entitymanager.getTransaction().begin(); - log.info("getCellsWithCollisionOrConfusion: updated in database...."); - Query query = entitymanager - .createQuery( - "from CellDetails cd where cd.pciCollisionDetected=true or cd.pciConfusionDetected=true", - CellDetails.class); - cds = query.getResultList(); - entitymanager.flush(); - entitymanager.getTransaction().commit(); - } catch (Exception eu) { - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - log.info("Exception:", eu); - } finally { - entitymanager.close(); - emfactory.close(); - } - - return cds; - } - - List<OperationLog> getOperationLogList(){ - EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - List<OperationLog> ols = new ArrayList<OperationLog>(); - try{ - entitymanager.getTransaction().begin(); - log.info("updated in database...."); - Query query = entitymanager.createQuery("from OperationLog ol", OperationLog.class); - ols = query.getResultList(); - entitymanager.flush(); - entitymanager.getTransaction().commit(); - } catch (Exception eu) { - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - log.info("Exception:", eu); - } finally { - entitymanager.close(); - emfactory.close(); - } - - return ols; - } - - List<NetconfServers> getNetconfServersList(){ - EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - List<NetconfServers> cnl = new ArrayList<NetconfServers>(); - try{ - log.info("updated in database...."); - Query query = entitymanager.createQuery("from NetconfServers ns", NetconfServers.class); - cnl = query.getResultList(); - } catch (Exception eu) { - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - log.info("Exception:", eu); - } finally { - entitymanager.close(); - emfactory.close(); - } - - return cnl; - } - - List<CellNeighbor> getCellNeighborList() { - EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - List<CellNeighbor> cellNeighborList = new ArrayList<CellNeighbor>(); - try { - entitymanager.getTransaction().begin(); - TypedQuery<CellNeighbor> query = entitymanager.createQuery("from CellNeighbor cn", CellNeighbor.class); - cellNeighborList = query.getResultList(); - entitymanager.flush(); - entitymanager.getTransaction().commit(); - } catch (Exception eu) { - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - log.info("Exception:", eu); - } finally { - entitymanager.close(); - emfactory.close(); - } - return cellNeighborList; - } - -} diff --git a/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RansimControllerServices.java b/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RansimControllerServices.java deleted file mode 100644 index 9fc130c..0000000 --- a/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RansimControllerServices.java +++ /dev/null @@ -1,730 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Ran Simulator Controller - * ================================================================================ - * Copyright (C) 2020 Wipro Limited. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.ransim.rest.api.controller; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.persistence.Query; - -import org.apache.log4j.Logger; -import org.onap.ransim.rest.api.models.CellDetails; -import org.onap.ransim.rest.api.models.CellNeighbor; -import org.onap.ransim.rest.api.models.DeleteACellReq; -import org.onap.ransim.rest.api.models.GetACellDetailReq; -import org.onap.ransim.rest.api.models.GetNeighborList; -import org.onap.ransim.rest.api.models.GetNeighborListReq; -import org.onap.ransim.rest.api.models.GetNetconfServerDetailsReq; -import org.onap.ransim.rest.api.models.GetPmDataReq; -import org.onap.ransim.rest.api.models.ModifyACellReq; -import org.onap.ransim.rest.api.models.NeighborDetails; -import org.onap.ransim.rest.api.models.NeihborId; -import org.onap.ransim.rest.api.models.NetconfServers; -import org.onap.ransim.rest.api.models.OperationLog; -import org.onap.ransim.rest.api.models.Topology; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - -@RestController -@Api(value = "Ran Simulator Controller Services") -@RequestMapping("/") -@CrossOrigin(origins = "*") -public class RansimControllerServices { - - static Logger log = Logger.getLogger(RansimControllerServices.class - .getName()); - - private static boolean isSimulationStarted = false; - private static boolean isPmDataGenerating = false; - - private static RansimControllerServices rscServices = null; - - ScheduledExecutorService execService = Executors.newScheduledThreadPool(5); - - private RansimControllerServices() { - - } - - /** - * To accesss variable of this class from another class. - * - * @return returns rscServices constructor - */ - public static synchronized RansimControllerServices getRansimControllerServices() { - if (rscServices == null) { - rscServices = new RansimControllerServices(); - } - return rscServices; - } - - RansimController rsCtrlr = RansimController.getRansimController(); - RansimPciHandler rsPciHdlr = RansimPciHandler.getRansimPciHandler(); - - /** - * Start the RAN network simulation. - * - * @param req - * gets the necessary details as a request of class type - * StartSimulationReq - * @return returns Http status - * @throws Exception - * throws exceptions in the functions - */ - @ApiOperation("Starts the RAN network simulation") - @RequestMapping(value = "/StartSimulation", method = RequestMethod.POST) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), - @ApiResponse(code = 500, message = "Cannot start the simulation") }) - public ResponseEntity<String> startSimulation() throws Exception { - - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - - List<CellDetails> cellList = rsDb.getCellDetailsList(); - if (!cellList.isEmpty()) { - return new ResponseEntity<>("Already simulation is running.", - HttpStatus.INTERNAL_SERVER_ERROR); - } - - try { - rsCtrlr.loadProperties(); - long startTimeStartSimulation = System.currentTimeMillis(); - rsCtrlr.generateClusterFromFile(); - rsCtrlr.sendInitialConfigAll(); - long endTimeStartSimulation = System.currentTimeMillis(); - log.info("Time taken for start simulation : " - + (endTimeStartSimulation - startTimeStartSimulation)); - - return new ResponseEntity<String>(HttpStatus.OK); - - } catch (Exception eu) { - log.info("/StartSimulation ", eu); - return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); - } - - } - - /** - * The performance Management Data of each cell will be sent to its netconf - * agent at a regular interval. - * - * @param req - * Contains the details of node ids which will have bad and poor - * pm values - * @return return HTTP status. - * - */ - @ApiOperation("Generate PM data") - @RequestMapping(value = "/GeneratePmData", method = RequestMethod.POST) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), - @ApiResponse(code = 500, message = "Cannot start the simulation") }) - public ResponseEntity<String> generatePmData(@RequestBody GetPmDataReq req) - throws Exception { - - log.info("Inside generatePmData..."); - log.info("nodeId_bad: " + req.getNodeIdBad()); - log.info("nodeId_poor: " + req.getNodeIdPoor()); - - try { - rsPciHdlr.readPmParameters(); - execService = Executors.newScheduledThreadPool(5); - execService.scheduleAtFixedRate( - () -> { - - List<String> resp = rsPciHdlr.generatePmData( - req.getNodeIdBad(), req.getNodeIdPoor()); - log.info("execService.isTerminated(): " - + execService.isTerminated()); - - }, 0, 300, TimeUnit.SECONDS); - - isPmDataGenerating = true; - - return new ResponseEntity<>("Request generated.", HttpStatus.OK); - - } catch (Exception eu) { - log.info("Exception: ", eu); - return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); - - } - - } - - /** - * Terminates the ScheduledExecutorService which sends the PM data at - * regular interval. - * - * @return returns HTTP status - * - */ - @ApiOperation("stop PM data") - @RequestMapping(value = "/stopPmData", method = RequestMethod.GET) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), - @ApiResponse(code = 500, message = "Cannot start the simulation") }) - public ResponseEntity<String> stopPmData() throws Exception { - - long startTime = (System.currentTimeMillis() / 1000); - - try { - log.info("1. execService.isTerminated(): " - + execService.isTerminated()); - if (!execService.isTerminated()) { - execService.shutdown(); - log.info("2. execService.isTerminated(): " - + execService.isTerminated()); - - } - isPmDataGenerating = false; - return new ResponseEntity<>("PM data generated.", HttpStatus.OK); - - } catch (Exception eu) { - return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); - } - - } - - /** - * Get the status of ScheduledExecutorService, whether active or terminated. - * - * @return return the status - * - */ - @ApiOperation("get PM data status") - @RequestMapping(value = "/GetPmDataStatus", method = RequestMethod.GET) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), - @ApiResponse(code = 500, message = "Cannot get information") }) - public boolean getPmDataStatus() throws Exception { - - try { - return isPmDataGenerating; - } catch (Exception eu) { - return false; - } - - } - - /** - * The function retrieves RAN simulation network topology. - * - * @return returns Http status - * @throws Exception - * throws exceptions in the functions - * - */ - @ApiOperation("Retrieves RAN simulation network topology") - @RequestMapping(value = "/GetTopology", method = RequestMethod.GET) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Successful"), - @ApiResponse(code = 500, message = "Cannot retrieve the RAN simulation network topology details") }) - public ResponseEntity<String> getTopology() throws Exception { - log.info("Inside getTopology..."); - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - try { - rsPciHdlr.checkCollisionAfterModify(); - List<CellDetails> cds = rsDb.getCellDetailsList(); - - Topology top = new Topology(); - - if (cds != null && cds.size() > 0) { - top.setMinScreenX(cds.get(0).getScreenX()); - top.setMaxScreenX(cds.get(0).getScreenX()); - top.setMinScreenY(cds.get(0).getScreenY()); - top.setMaxScreenY(cds.get(0).getScreenY()); - - for (int i = 0; i < cds.size(); i++) { - if (cds.get(i).getScreenX() < top.getMinScreenX()) { - top.setMinScreenX(cds.get(i).getScreenX()); - } - if (cds.get(i).getScreenY() < top.getMinScreenY()) { - top.setMinScreenY(cds.get(i).getScreenY()); - } - - if (cds.get(i).getScreenX() > top.getMaxScreenX()) { - top.setMaxScreenX(cds.get(i).getScreenX()); - } - if (cds.get(i).getScreenY() > top.getMaxScreenY()) { - top.setMaxScreenY(cds.get(i).getScreenY()); - } - } - top.setCellTopology(cds); - } - top.setGridSize(rsCtrlr.gridSize); - - Gson gson = new Gson(); - String jsonStr = gson.toJson(top); - - return new ResponseEntity<>(jsonStr, HttpStatus.OK); - - } catch (Exception eu) { - log.info("/GetTopology", eu); - return new ResponseEntity<>("Failure", - HttpStatus.INTERNAL_SERVER_ERROR); - } - } - - /** - * The function retrieves the neighbor list details for the cell with the - * mentioned nodeId. - * - * @param req - * gets the necessary details as a request of class type - * GetNeighborListReq - * @return returns Http status - * @throws Exception - * throws exceptions in the functions - */ - @ApiOperation("Retrieves the neighbor list details for the cell with the mentioned nodeId") - @RequestMapping(value = "/GetNeighborList", method = RequestMethod.POST) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Successful"), - @ApiResponse(code = 500, message = "Cannot Insert the given parameters") }) - public ResponseEntity<String> getNeighborList( - @RequestBody GetNeighborListReq req) throws Exception { - log.info("Inside getNeighborList..."); - - try { - String jsonStr = ""; - - GetNeighborList message = rsPciHdlr.generateNeighborList(req - .getNodeId()); - - if (message != null) { - - log.info("message.getNodeId(): " + message.getNodeId()); - - Gson gson = new Gson(); - jsonStr = gson.toJson(message); - } - return new ResponseEntity<>(jsonStr, HttpStatus.OK); - - } catch (Exception eu) { - log.info("/getNeighborList", eu); - - return new ResponseEntity<>("Failure", - HttpStatus.INTERNAL_SERVER_ERROR); - } - } - - /** - * The function retrieves the neighbor list for the cell with the mentioned - * nodeId. - * - * @param req - * gets the necessary details as a request of class type - * GetNeighborListReq - * @return returns Http status - * @throws Exception - * throws exceptions in the functions - */ - @ApiOperation("Retrieves the neighbor list details for the cell with the mentioned nodeId") - @RequestMapping(value = "/GetNeighborBlacklistDetails", method = RequestMethod.POST) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Successful"), - @ApiResponse(code = 500, message = "Cannot Insert the given parameters") }) - public ResponseEntity<String> getNeighborBlacklistDetails( - @RequestBody GetNeighborListReq req) throws Exception { - log.info("Inside getNeighborList..."); - - try { - String jsonStr = ""; - - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - CellNeighbor neighborList = rsDb.getCellNeighbor(req.getNodeId()); - - Map<String, String> result = new ConcurrentHashMap<String, String>(); - - for (NeighborDetails nd : neighborList.getNeighborList()) { - - result.put(nd.getNeigbor().getNeighborCell(), - "" + nd.isBlacklisted()); - } - - if (result != null) { - Gson gson = new Gson(); - jsonStr = gson.toJson(result); - } - return new ResponseEntity<>(jsonStr, HttpStatus.OK); - - } catch (Exception eu) { - log.info("/getNeighborList", eu); - - return new ResponseEntity<>("Failure", - HttpStatus.INTERNAL_SERVER_ERROR); - } - } - - /** - * Changes the pci number or nbr list for the given cell. - * - * @param req - * gets the necessary details as a request of class type - * ModifyACellReq - * @return returns Http status - * @throws Exception - * throws exceptions in the functions - */ - @ApiOperation("Changes the pci number or nbr list for the given cell") - @RequestMapping(value = "/ModifyACell", method = RequestMethod.POST) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Successful"), - @ApiResponse(code = 500, message = "Cannot update the PCI for the given cell") }) - public ResponseEntity<String> modifyACell(@RequestBody ModifyACellReq req) - throws Exception { - log.info("Inside ModifyCell..."); - - try { - long startTimemodifyCell = System.currentTimeMillis(); - - String nbrsStr = req.getNewNbrs(); - if (req.getNewNbrs() == null) { - nbrsStr = ""; - } - String source = "GUI"; - List<NeighborDetails> nbrsList = new ArrayList<NeighborDetails>(); - String[] newNbrsArr = nbrsStr.split(","); - - for (int i = 0; i < newNbrsArr.length; i++) { - NeighborDetails cell = new NeighborDetails(new NeihborId( - req.getNodeId(), newNbrsArr[i].trim()), false); - nbrsList.add(cell); - } - - int result = rsPciHdlr.modifyCellFunction(req.getNodeId(), - req.getNewPhysicalCellId(), nbrsList, source); - log.info("Inside modify cell : " + (startTimemodifyCell)); - log.info("Result:********************" + result); - rsCtrlr.handleModifyPciFromGui(req.getNodeId(), - req.getNewPhysicalCellId()); - long endTimemodifyCell = System.currentTimeMillis(); - log.info("Time taken to modify cell : " - + (endTimemodifyCell - startTimemodifyCell)); - - if (result == 200) { - return new ResponseEntity<String>(HttpStatus.OK); - } else if (result == 400) { - return new ResponseEntity<String>(HttpStatus.BAD_REQUEST); - } else { - return new ResponseEntity<String>( - HttpStatus.INTERNAL_SERVER_ERROR); - } - - } catch (Exception eu) { - log.info("Exception in modifyACell", eu); - - return new ResponseEntity<>( - "Cannot update the PCI for the given cell", - HttpStatus.INTERNAL_SERVER_ERROR); - } - - } - - /** - * The function changes the PCI number of the cell for the the mentioned - * nodeId. - * - * @param req - * gets the necessary details as a request of class type - * GetACellDetailReq - * @return returns Http status - * @throws Exception - * throws exceptions in the functions - */ - @ApiOperation("Changes the pci number of the cell for the the mentioned nodeId") - @RequestMapping(value = "/GetACellDetail", method = RequestMethod.POST) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Successful"), - @ApiResponse(code = 500, message = "Cannot retrive the cell details for the given cell") }) - public ResponseEntity<String> getACellDetail( - @RequestBody GetACellDetailReq req) throws Exception { - log.info("Inside GetACellDetailReq..."); - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - try { - String jsonStr = null; - - CellDetails cd = rsDb.getCellDetail(req.getNodeId()); - - if (cd != null) { - Gson gson = new Gson(); - jsonStr = gson.toJson(cd); - } - return new ResponseEntity<>(jsonStr, HttpStatus.OK); - - } catch (Exception eu) { - log.info("Exception in modifyACell", eu); - return new ResponseEntity<>( - "Cannot update the PCI for the given cell", - HttpStatus.INTERNAL_SERVER_ERROR); - } - } - - /** - * The function deletes a cell with the mentioned nodeId. - * - * @param req - * gets the necessary details as a request of class type - * DeleteACellReq - * @return returns Http status - * @throws Exception - * throws exceptions in the functions - */ - @ApiOperation("Deletes a cell with the mentioned nodeId") - @RequestMapping(value = "/DeleteACell", method = RequestMethod.POST) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), - @ApiResponse(code = 500, message = "Cannot delete the given cell") }) - public ResponseEntity<String> deleteACell(@RequestBody DeleteACellReq req) - throws Exception { - log.info("Inside delete cell..."); - - try { - long startTimeDeleteCell = System.currentTimeMillis(); - String result = rsCtrlr.deleteCellFunction(req.getNodeId()); - log.info("deleted in database...." + result); - long endTimeDeleteCell = System.currentTimeMillis(); - log.info("Time taken to delete cell : " - + (endTimeDeleteCell - startTimeDeleteCell)); - - return new ResponseEntity<String>(HttpStatus.OK); - - } catch (Exception eu) { - log.info("Exception in deleteACell", eu); - return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); - } - } - - /** - * The function stops RAN network simulation and deletes all the cell data - * from the database. - * - * @return returns Http status - * @throws Exception - * throws exceptions in the functions - */ - @ApiOperation("Stops RAN network simulation and deletes all the cell data from the database") - @RequestMapping(value = "/StopSimulation", method = RequestMethod.DELETE) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful"), - @ApiResponse(code = 500, message = "Cannot stop simulation") }) - public ResponseEntity<String> stopSimulation() throws Exception { - log.info("Inside stopSimulation..."); - EntityManagerFactory emfactory = Persistence - .createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - - Query query = entitymanager.createQuery("from CellDetails cd", - CellDetails.class); - if (query.getResultList() == null) { - return new ResponseEntity<>("No simulation is running.", - HttpStatus.INTERNAL_SERVER_ERROR); - } - - try { - entitymanager.getTransaction().begin(); - long startTimStopSimulation = System.currentTimeMillis(); - Query q3 = entitymanager - .createQuery("DELETE FROM NetconfServers ns"); - q3.executeUpdate(); - - Query q2 = entitymanager.createQuery("DELETE FROM CellNeighbor cn"); - q2.executeUpdate(); - - Query q4 = entitymanager - .createQuery("DELETE FROM NeighborDetails cn"); - q4.executeUpdate(); - - log.info("Stop simulation : " + (startTimStopSimulation)); - Query q1 = entitymanager.createQuery("DELETE FROM CellDetails cd"); - q1.executeUpdate(); - - String result = rsCtrlr.stopAllCells(); - log.info("All cell simulation are stopped...." + result); - - entitymanager.flush(); - entitymanager.getTransaction().commit(); - - long endTimStopSimulation = System.currentTimeMillis(); - log.info("Time taken for stopping simulation : " - + (endTimStopSimulation - startTimStopSimulation)); - - isSimulationStarted = false; - return new ResponseEntity<>("Success", HttpStatus.OK); - - } catch (Exception eu) { - log.info("Exception in stopSimulation", eu); - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - return new ResponseEntity<>("Failure", - HttpStatus.INTERNAL_SERVER_ERROR); - } finally { - entitymanager.close(); - emfactory.close(); - } - - } - - /** - * The function returns the details of a Netconf server for the mentioned - * server id. - * - * @param req - * gets the necessary details as a request of class type - * GetNetconfServerDetailsReq - * @return returns Http status - * @throws Exception - * throws exceptions in the functions - */ - @ApiOperation("Returns the details of a Netconf server for the mentioned server id") - @RequestMapping(value = "/GetNetconfServerDetails", method = RequestMethod.POST) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Successful"), - @ApiResponse(code = 500, message = "Failure in GetNetconfServerDetails API") }) - public ResponseEntity<String> getNetconfServerDetails( - @RequestBody GetNetconfServerDetailsReq req) throws Exception { - - EntityManagerFactory emfactory = Persistence - .createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - try { - log.info("Inside GetNetconfServerDetails API..."); - String result = ""; - entitymanager.getTransaction().begin(); - String input = req.getServerId(); - if (input.startsWith("Chn")) { - CellDetails cds = entitymanager.find(CellDetails.class, input); - if (cds != null) { - Gson gson = new Gson(); - String jsonStr = gson.toJson(cds); - result = "{\"serverId\":\"any\",\"cells\":[" + jsonStr - + "]}"; - } else { - result = ("Cell Id does not exist"); - } - } else { - NetconfServers ns = entitymanager.find(NetconfServers.class, - req.getServerId()); - if (ns != null) { - Gson gson = new Gson(); - String jsonStr = gson.toJson(ns); - result = jsonStr; - } else { - result = ("Server Id does not exist"); - } - } - return new ResponseEntity<>(result, HttpStatus.OK); - - } catch (Exception eu) { - log.info("/GetNetconfServers", eu); - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - return new ResponseEntity<>( - "Failure in GetNetconfServerDetails API", - HttpStatus.INTERNAL_SERVER_ERROR); - } finally { - entitymanager.close(); - emfactory.close(); - } - } - - @ApiOperation("Returns the connection status of all netconf servers") - @RequestMapping(value = "/GetNetconfStatus", method = RequestMethod.GET) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Successful"), - @ApiResponse(code = 500, message = "Failure in GetNetconfServerDetails API") }) - public ResponseEntity<String> GetNetconfStatus() throws Exception { - - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - try { - log.info("Inside GetNetconfServerDetails API..."); - String result = ""; - - List<NetconfServers> ns = rsDb.getNetconfServersList(); - if (ns != null) { - GsonBuilder gsonBuilder = new GsonBuilder(); - gsonBuilder.serializeNulls(); - Gson gson = gsonBuilder.create(); - String jsonStr = gson.toJson(ns); - result = jsonStr; - } else { - result = ("Server Id does not exist"); - } - - return new ResponseEntity<>(result, HttpStatus.OK); - - } catch (Exception eu) { - log.info("/GetNetconfServers", eu); - return new ResponseEntity<>( - "Failure in GetNetconfServerDetails API", - HttpStatus.INTERNAL_SERVER_ERROR); - } - } - - /** - * The function retrieves RAN simulation network topology. - * - * @return returns Http status - * @throws Exception - * throws exceptions in the functions - * - */ - @ApiOperation("Retrieves operations log - Modify/Delete operations performed") - @RequestMapping(value = "/GetOperationLog", method = RequestMethod.GET) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Successful"), - @ApiResponse(code = 500, message = "Cannot retrieve the Operation Logs") }) - public ResponseEntity<String> getOperationLog() throws Exception { - log.info("Inside getOperationLog..."); - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - try { - List<OperationLog> ols = rsDb.getOperationLogList(); - if (ols != null && ols.size() > 0) { - Gson gson = new Gson(); - String jsonStr = gson.toJson(ols); - return new ResponseEntity<>(jsonStr, HttpStatus.OK); - } else { - return new ResponseEntity<>("", HttpStatus.OK); - } - } catch (Exception eu) { - log.info("/GetOperationLog", eu); - return new ResponseEntity<>("Failure", - HttpStatus.INTERNAL_SERVER_ERROR); - } - } - -} diff --git a/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RansimPciHandler.java b/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RansimPciHandler.java deleted file mode 100644 index e4796e8..0000000 --- a/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/api/controller/RansimPciHandler.java +++ /dev/null @@ -1,1011 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Ran Simulator Controller - * ================================================================================ - * Copyright (C) 2020 Wipro Limited. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.ransim.rest.api.controller; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.websocket.Session; - -import org.apache.log4j.Logger; -import org.onap.ransim.rest.api.models.CellDetails; -import org.onap.ransim.rest.api.models.CellNeighbor; -import org.onap.ransim.rest.api.models.FmAlarmInfo; -import org.onap.ransim.rest.api.models.GetNeighborList; -import org.onap.ransim.rest.api.models.NeighborDetails; -import org.onap.ransim.rest.api.models.NetconfServers; -import org.onap.ransim.rest.api.models.OperationLog; -import org.onap.ransim.rest.api.models.PmDataDump; -import org.onap.ransim.rest.api.models.PmParameters; -import org.onap.ransim.websocket.model.AdditionalMeasurements; -import org.onap.ransim.websocket.model.CommonEventHeaderFm; -import org.onap.ransim.websocket.model.CommonEventHeaderPm; -import org.onap.ransim.websocket.model.EventFm; -import org.onap.ransim.websocket.model.EventPm; -import org.onap.ransim.websocket.model.FaultFields; -import org.onap.ransim.websocket.model.FmMessage; -import org.onap.ransim.websocket.model.Measurement; -import org.onap.ransim.websocket.model.PmMessage; -import org.onap.ransim.websocket.server.RansimWebSocketServer; - -import com.google.gson.Gson; - -public class RansimPciHandler { - - private static RansimPciHandler rsPciHandler = null; - - private RansimPciHandler() { - - } - - /** - * To accesss variable of this class from another class. - * - * @return returns rscontroller constructor - */ - public static synchronized RansimPciHandler getRansimPciHandler() { - if (rsPciHandler == null) { - rsPciHandler = new RansimPciHandler(); - } - return rsPciHandler; - } - - static Logger log = Logger.getLogger(RansimPciHandler.class - .getName()); - - RansimController rsCtrlr = RansimController.getRansimController(); - - static Map<String, String> globalFmCellIdUuidMap = new ConcurrentHashMap<String, String>(); - static Map<String, String> globalPmCellIdUuidMap = new ConcurrentHashMap<String, String>(); - - Set<String> cellsWithIssues = new HashSet<>(); - - List<PmParameters> pmParameters = new ArrayList<PmParameters>(); - int next = 0; - - static FmAlarmInfo setCollisionConfusionFromFile(String cellNodeId) { - - FmAlarmInfo result = new FmAlarmInfo(); - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - - try { - - boolean collisionDetected = false; - boolean confusionDetected = false; - List<Long> nbrPcis = new ArrayList<Long>(); - List<Long> ConfusionPcis = new ArrayList<Long>(); - int collisionCount = 0; - int confusionCount = 0; - CellDetails currentCell = rsDb.getCellDetail(cellNodeId); - - log.info("Setting confusion/collision for Cell :" + cellNodeId); - - GetNeighborList cellNbrDetails = generateNeighborList(cellNodeId); - - for (CellDetails firstLevelNbr : cellNbrDetails.getCellsWithHo()) { - if (nbrPcis - .contains(new Long(firstLevelNbr.getPhysicalCellId()))) { - confusionDetected = true; - if (ConfusionPcis.contains(firstLevelNbr - .getPhysicalCellId())) { - confusionCount++; - } else { - ConfusionPcis.add(firstLevelNbr.getPhysicalCellId()); - confusionCount = confusionCount + 2; - } - - } else { - nbrPcis.add(new Long(firstLevelNbr.getPhysicalCellId())); - } - - if (currentCell.getPhysicalCellId() == firstLevelNbr - .getPhysicalCellId()) { - collisionDetected = true; - collisionCount++; - } - } - - currentCell.setPciCollisionDetected(collisionDetected); - currentCell.setPciConfusionDetected(confusionDetected); - - if (!currentCell.isPciCollisionDetected() - && !currentCell.isPciConfusionDetected()) { - currentCell.setColor("#BFBFBF"); // GREY - No Issues - result.setProblem("No Issues"); - } else if (currentCell.isPciCollisionDetected() - && currentCell.isPciConfusionDetected()) { - currentCell.setColor("#C30000"); // BROWN - Cell has both - // collision & confusion - result.setProblem("CollisionAndConfusion"); - - } else if (currentCell.isPciCollisionDetected()) { - currentCell.setColor("#FF0000"); // RED - Cell has collision - result.setProblem("Collision"); - - } else if (currentCell.isPciConfusionDetected()) { - currentCell.setColor("#E88B00"); // ORANGE - Cell has confusion - result.setProblem("Confusion"); - - } else { - currentCell.setColor("#BFBFBF"); // GREY - No Issues - result.setProblem("No Issues"); - } - - result.setCollisionCount("" + collisionCount); - result.setConfusionCount("" + confusionCount); - - rsDb.mergeCellDetails(currentCell); - - return result; - - } catch (Exception e2) { - log.info("setCollisionConfusionFromFile :", e2); - - return null; - } - - } - - /** - * Generates separate list of neighbors with and without hand-off for a - * cell. - * - * @param nodeId - * Node Id of cell for which the neighbor list is generated - * @return Returns GetNeighborList object - */ - static GetNeighborList generateNeighborList(String nodeId) { - - EntityManagerFactory emfactory = Persistence - .createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - try { - log.info("inside generateNeighborList for: " + nodeId); - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - CellNeighbor neighborList = entitymanager.find(CellNeighbor.class, - nodeId); - GetNeighborList result = new GetNeighborList(); - - List<CellDetails> cellsWithNoHO = new ArrayList<CellDetails>(); - List<CellDetails> cellsWithHO = new ArrayList<CellDetails>(); - - List<NeighborDetails> nbrList = new ArrayList<NeighborDetails>( - neighborList.getNeighborList()); - long readCellDetail = 0; - long checkBlacklisted = 0; - - for (int i = 0; i < nbrList.size(); i++) { - - CellDetails nbr = entitymanager.find(CellDetails.class, nbrList - .get(i).getNeigbor().getNeighborCell()); - - if (nbrList.get(i).isBlacklisted()) { - cellsWithNoHO.add(nbr); - } else { - cellsWithHO.add(nbr); - } - - } - - result.setNodeId(nodeId); - result.setCellsWithHo(cellsWithHO); - result.setCellsWithNoHo(cellsWithNoHO); - - return result; - - } catch (Exception eu) { - log.info("/getNeighborList", eu); - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - return null; - } finally { - entitymanager.close(); - emfactory.close(); - } - } - - static void checkCollisionAfterModify() { - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - try { - List<CellDetails> checkCollisionConfusion = rsDb - .getCellsWithCollisionOrConfusion(); - - for (int i = 0; i < checkCollisionConfusion.size(); i++) { - log.info(checkCollisionConfusion.get(i).getNodeId()); - setCollisionConfusionFromFile(checkCollisionConfusion.get(i) - .getNodeId()); - } - } catch (Exception eu) { - log.info("checkCollisionAfterModify", eu); - } - } - - /** - * It updates the cell with its new neighbor list and PCI and updates the - * change in a database. - * - * @param nodeId - * node Id of the cell - * @param physicalCellId - * PCI number of the cell - * @param newNbrs - * List of new neighbors for the cell - * @param source - * The source from which cell modification has been triggered - * @return returns success or failure message - */ - public int modifyCellFunction(String nodeId, long physicalCellId, - List<NeighborDetails> newNbrs, String source) { - - int result = 111; - - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - log.info("modifyCellFunction nodeId:" + nodeId + ", physicalCellId:" - + physicalCellId); - CellDetails modifyCell = rsDb.getCellDetail(nodeId); - - if (modifyCell != null) { - if (physicalCellId < 0 - || physicalCellId > rsCtrlr.maxPciValueAllowed) { - log.info("NewPhysicalCellId is empty or invalid"); - result = 400; - } else { - long oldPciId = modifyCell.getPhysicalCellId(); - if (physicalCellId != oldPciId) { - updatePciOperationsTable(nodeId, source, physicalCellId, - oldPciId); - - modifyCell.setPhysicalCellId(physicalCellId); - rsDb.mergeCellDetails(modifyCell); - } - - CellNeighbor neighbors = rsDb.getCellNeighbor(nodeId); - List<NeighborDetails> oldNbrList = new ArrayList<NeighborDetails>( - neighbors.getNeighborList()); - List<NeighborDetails> oldNbrListWithHo = new ArrayList<NeighborDetails>(); - - for (NeighborDetails cell : oldNbrList) { - if (!cell.isBlacklisted()) { - oldNbrListWithHo.add(cell); - } - } - - boolean flag = false; - - List<NeighborDetails> addedNbrs = new ArrayList<NeighborDetails>(); - List<NeighborDetails> deletedNbrs = new ArrayList<NeighborDetails>(); - - String nbrsDel = ""; - - List<String> oldNbrsArr = new ArrayList<String>(); - for (NeighborDetails cell : oldNbrListWithHo) { - oldNbrsArr.add(cell.getNeigbor().getNeighborCell()); - } - - List<String> newNbrsArr = new ArrayList<String>(); - for (NeighborDetails cell : newNbrs) { - newNbrsArr.add(cell.getNeigbor().getNeighborCell()); - } - - for (NeighborDetails cell : oldNbrListWithHo) { - - if (!newNbrsArr.contains(cell.getNeigbor() - .getNeighborCell())) { - if (!flag) { - flag = true; - } - deletedNbrs.add(cell); - if (nbrsDel == "") { - nbrsDel = cell.getNeigbor().getNeighborCell(); - } else { - nbrsDel += "," - + cell.getNeigbor().getNeighborCell(); - } - log.info("deleted cell: " - + cell.getNeigbor().getNeighborCell() - + cell.isBlacklisted()); - - } - } - - String nbrsAdd = ""; - - for (NeighborDetails cell : newNbrs) { - if (cell.isBlacklisted()) { - addedNbrs.add(cell); - } else { - if (!oldNbrsArr.contains(cell.getNeigbor() - .getNeighborCell())) { - addedNbrs.add(cell); - if (nbrsAdd == "") { - nbrsAdd = cell.getNeigbor().getNeighborCell(); - } else { - nbrsAdd += "," - + cell.getNeigbor().getNeighborCell(); - } - log.info("added cell: " - + cell.getNeigbor().getNeighborCell() - + cell.isBlacklisted()); - } - } - - } - List<NeighborDetails> newNeighborList = new ArrayList<NeighborDetails>( - oldNbrList); - for (NeighborDetails cell : deletedNbrs) { - NeighborDetails removeHo = new NeighborDetails( - cell.getNeigbor(), true); - rsDb.mergeNeighborDetails(removeHo); - newNeighborList.add(removeHo); - } - - for (NeighborDetails cell : addedNbrs) { - rsDb.mergeNeighborDetails(cell); - newNeighborList.add(cell); - } - - if (!flag) { - if (newNbrs.size() != oldNbrList.size()) { - flag = true; - } - } - - if (flag) { - updateNbrsOperationsTable(nodeId, source, nbrsAdd, nbrsDel); - } - - if (newNbrs != null) { - neighbors.getNeighborList().clear(); - Set<NeighborDetails> updatedNbrList = new HashSet<NeighborDetails>( - newNeighborList); - neighbors.setNeighborList(updatedNbrList); - rsDb.mergeCellNeighbor(neighbors); - } - - generateFmData(source, modifyCell, newNeighborList); - - result = 200; - } - - - } else { - result = 400; - } - - return result; - } - - public void checkCellsWithIssue() { - - EntityManagerFactory emfactory = Persistence - .createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - try { - - for (String id : cellsWithIssues) { - CellDetails currentCell = entitymanager.find(CellDetails.class, - id); - FmMessage fmDataMessage = new FmMessage(); - List<EventFm> data = new ArrayList<EventFm>(); - - if (!currentCell.isPciCollisionDetected()) { - if (!currentCell.isPciConfusionDetected()) { - - cellsWithIssues.remove(id); - CommonEventHeaderFm commonEventHeader = new CommonEventHeaderFm(); - FaultFields faultFields = new FaultFields(); - - commonEventHeader.setStartEpochMicrosec(System - .currentTimeMillis() * 1000); - commonEventHeader - .setSourceName(currentCell.getNodeId()); - commonEventHeader.setReportingEntityName(currentCell - .getServerId()); - String uuid = globalFmCellIdUuidMap.get(currentCell - .getNodeId()); - commonEventHeader.setSourceUuid(uuid); - - faultFields - .setAlarmCondition("RanPciCollisionConfusionOccurred"); - faultFields.setEventSeverity("NORMAL"); - faultFields.setEventSourceType("other"); - faultFields.setSpecificProblem("Problem Solved"); - - commonEventHeader.setLastEpochMicrosec(System - .currentTimeMillis() * 1000); - - EventFm event = new EventFm(); - event.setCommonEventHeader(commonEventHeader); - event.setFaultFields(faultFields); - - data.add(event); - } - } - - fmDataMessage.setFmEventList(data); - - if (!data.isEmpty()) { - sendFmData(currentCell.getServerId(), fmDataMessage); - } - - } - - } catch (Exception eu) { - if (entitymanager.getTransaction().isActive()) { - entitymanager.getTransaction().rollback(); - } - log.info("Exception:", eu); - } finally { - entitymanager.close(); - emfactory.close(); - } - - } - - void updatePciOperationsTable(String nodeId, String source, long physicalCellId, long oldPciId) { - EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - OperationLog operationLog = new OperationLog(); - - entitymanager.getTransaction().begin(); - operationLog.setNodeId(nodeId); - operationLog.setFieldName("PCID"); - operationLog.setOperation("Modify"); - operationLog.setSource(source); - operationLog.setTime(System.currentTimeMillis()); - operationLog.setMessage("PCID value changed from " + oldPciId + " to " + physicalCellId); - entitymanager.merge(operationLog); - entitymanager.flush(); - entitymanager.getTransaction().commit(); - } - - void updateNbrsOperationsTable(String nodeId, String source, String addedNbrs, String deletedNbrs) { - - EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("ransimctrlrdb"); - EntityManager entitymanager = emfactory.createEntityManager(); - entitymanager.getTransaction().begin(); - OperationLog operationLogNbrChng = new OperationLog(); - operationLogNbrChng.setNodeId(nodeId); - operationLogNbrChng.setFieldName("Neighbors"); - operationLogNbrChng.setOperation("Modify"); - operationLogNbrChng.setSource(source); - - log.info(" Neighbors added " + addedNbrs + "."); - log.info(" Neighbors removed " + deletedNbrs + "."); - String message = ""; - if(!addedNbrs.equals("")){ - message += " Neighbors added " + addedNbrs + "." ; - } - - if(!deletedNbrs.equals("")){ - message += " Neighbors removed " + deletedNbrs + "." ; - } - - operationLogNbrChng.setMessage(message); - operationLogNbrChng.setTime(System.currentTimeMillis()); - entitymanager.merge(operationLogNbrChng); - entitymanager.flush(); - entitymanager.getTransaction().commit(); - - } - - /** - * Sends PM message to the netconf agent through the websocket server. - * - * @param serverId - * Netconf agent - Server ID to which the message is sent. - * @param pmMessage - * PM message to be sent. - */ - void sendPmdata(String serverId, String pmMessage) { - - log.info("Sending PM message to netconf agent"); - - String ipPort = rsCtrlr.serverIdIpPortMapping.get(serverId); - - if (ipPort != null && !ipPort.trim().equals("")) { - - String[] ipPortArr = ipPort.split(":"); - if (ipPort != null && !ipPort.trim().equals("")) { - - Session clSess = rsCtrlr.webSocketSessions.get(ipPort); - log.info("PM message. Netconf agent IP:" + ipPort); - if (clSess != null) { - RansimWebSocketServer.sendPmMessage(pmMessage, clSess); - log.info("Pm Data jsonStr: " + pmMessage); - log.info("PM message sent to netconf agent"); - } else { - log.info("No client session for " + ipPort); - } - } else { - log.info("Pm message not sent, ipPort is null"); - } - } else { - - log.info("Pm message not sent, ipPort is null. Server Id: " - + serverId); - } - - } - - /** - * - * Reads the values PM parameter values from a dump file. - * - */ - public void readPmParameters() { - - File dumpFile = null; - String kpiName = ""; - PmDataDump pmDump = null; - String jsonString = ""; - int next = 0; - dumpFile = new File("PM_Kpi_Data.json"); - - BufferedReader br = null; - - try { - log.info("Reading dump file"); - br = new BufferedReader(new FileReader(dumpFile)); - - StringBuilder sb = new StringBuilder(); - String line = br.readLine(); - - while (line != null) { - sb.append(line); - sb.append("\n"); - line = br.readLine(); - } - jsonString = sb.toString(); - - pmDump = new Gson().fromJson(jsonString, PmDataDump.class); - log.info("Dump value: " - + pmDump.getKpiDump().get(0).getParameter1()); - pmParameters = new ArrayList<PmParameters>(pmDump.getKpiDump()); - - } catch (Exception eu) { - log.info("Exception: ", eu); - } - } - - private static String getUuid() { - return UUID.randomUUID().toString(); - } - - /** - * Sets values for all the parameters in the PM message - * - * @param nodeIdBad - * List of node Ids with bad performance values - * @param nodeIdPoor - * List of node Ids with poor performance values - * @return It returns the pm message - */ - public List<String> generatePmData(String nodeIdBad, String nodeIdPoor) { - - List<String> result = new ArrayList<>(); - RansimControllerDatabase rcDb = new RansimControllerDatabase(); - - String parameter1 = ""; - String successValue1 = ""; - String badValue1 = ""; - String poorValue1 = ""; - String parameter2 = ""; - String successValue2 = ""; - String badValue2 = ""; - String poorValue2 = ""; - - try { - - if (next >= pmParameters.size()) { - next = 0; - log.info("next : " + next); - } - try { - log.info("next : " + next); - parameter1 = pmParameters.get(next).getParameter1(); - successValue1 = pmParameters.get(next).getSuccessValue1(); - badValue1 = pmParameters.get(next).getBadValue1(); - poorValue1 = pmParameters.get(next).getPoorValue1(); - parameter2 = pmParameters.get(next).getParameter2(); - successValue2 = pmParameters.get(next).getSuccessValue2(); - badValue2 = pmParameters.get(next).getBadValue2(); - poorValue2 = pmParameters.get(next).getPoorValue2(); - next++; - } catch (Exception e) { - log.info("Exception: ", e); - } - - List<NetconfServers> cnl = rcDb.getNetconfServersList(); - log.info("obtained data from db"); - String[] cellIdsBad = null; - String[] cellIdsPoor = null; - Set<String> nodeIdsBad = new HashSet<String>(); - Set<String> nodeIdsPoor = new HashSet<String>(); - - if (nodeIdBad != null) { - cellIdsBad = nodeIdBad.split(","); - for (int a = 0; a < cellIdsBad.length; a++) { - nodeIdsBad.add(cellIdsBad[a].trim()); - } - } - if (nodeIdPoor != null) { - cellIdsPoor = nodeIdPoor.split(","); - for (int a = 0; a < cellIdsPoor.length; a++) { - nodeIdsPoor.add(cellIdsPoor[a].trim()); - } - } - - for (int i = 0; i < cnl.size(); i++) { - - long startTime = System.currentTimeMillis(); - List<CellDetails> cellList = new ArrayList<CellDetails>(cnl - .get(i).getCells()); - List<EventPm> data = new ArrayList<EventPm>(); - - for (int j = 0; j < cellList.size(); j++) { - - long startTimeCell = System.currentTimeMillis(); - String nodeId = cellList.get(j).getNodeId(); - EventPm event = new EventPm(); - CommonEventHeaderPm commonEventHeader = new CommonEventHeaderPm(); - commonEventHeader.setSourceName(nodeId); - commonEventHeader.setStartEpochMicrosec(System - .currentTimeMillis() * 1000); - String uuid = globalPmCellIdUuidMap.get(nodeId); - if (uuid == null) { - uuid = getUuid(); - globalPmCellIdUuidMap.put(nodeId, uuid); - } - commonEventHeader.setSourceUuid(uuid); - - Measurement measurement = new Measurement(); - measurement.setMeasurementInterval(180); - - GetNeighborList cellNbrList = generateNeighborList(nodeId); - - long startTimeCheckBadPoor = System.currentTimeMillis(); - - boolean checkBad = false; - boolean checkPoor = false; - int countBad = 0; - int countPoor = 0; - - if (nodeIdsBad.contains(nodeId)) { - checkBad = true; - countBad = (int) (cellNbrList.getCellsWithHo().size() * 0.2); - } - if (nodeIdsPoor.contains(nodeId)) { - checkPoor = true; - countPoor = (int) (cellNbrList.getCellsWithHo().size() * 0.2); - } - - long endTimeCheckBadPoor = System.currentTimeMillis(); - - List<AdditionalMeasurements> additionalMeasurements = new ArrayList<AdditionalMeasurements>(); - if (checkPoor || checkBad) { - - Collections.sort(cellNbrList.getCellsWithHo()); - - for (int k = 0; k < cellNbrList.getCellsWithHo().size(); k++) { - AdditionalMeasurements addMsmnt = new AdditionalMeasurements(); - addMsmnt.setName(cellNbrList.getCellsWithHo() - .get(k).getNodeId()); - Map<String, String> hashMap = new HashMap<String, String>(); - hashMap.put("networkId", cellNbrList - .getCellsWithHo().get(k).getNetworkId()); - - hashMap.put(parameter1, successValue1); - - if (checkBad == true) { - - if (countBad > 0) { - log.info("countBad: " + countBad); - hashMap.put(parameter2, badValue2); - countBad--; - } else { - hashMap.put(parameter2, successValue2); - } - - } else if (checkPoor == true) { - if (countPoor > 0) { - log.info("countBad: " + countPoor); - hashMap.put(parameter2, poorValue2); - countPoor--; - } else { - hashMap.put(parameter2, successValue2); - } - - } - - addMsmnt.setHashMap(hashMap); - - additionalMeasurements.add(addMsmnt); - - } - } else { - for (int k = 0; k < cellNbrList.getCellsWithHo().size(); k++) { - AdditionalMeasurements addMsmnt = new AdditionalMeasurements(); - addMsmnt.setName(cellNbrList.getCellsWithHo() - .get(k).getNodeId()); - Map<String, String> hashMap = new HashMap<String, String>(); - - hashMap.put("networkId", cellNbrList - .getCellsWithHo().get(k).getNetworkId()); - - hashMap.put(parameter1, successValue1); - - hashMap.put(parameter2, successValue2); - - addMsmnt.setHashMap(hashMap); - additionalMeasurements.add(addMsmnt); - } - } - - commonEventHeader.setLastEpochMicrosec(System - .currentTimeMillis() * 1000); - measurement - .setAdditionalMeasurements(additionalMeasurements); - - event.setCommonEventHeader(commonEventHeader); - event.setMeasurement(measurement); - - data.add(event); - long endTimeCell = System.currentTimeMillis(); - } - - long endTime = System.currentTimeMillis(); - log.info("Time taken for generating PM data for " - + cnl.get(i).getServerId() + " : " - + (endTime - startTime)); - PmMessage msg = new PmMessage(); - - if (data.size() > 0) { - msg.setEventPmList(data); - Gson gson = new Gson(); - String jsonStr = gson.toJson(msg); - sendPmdata(cnl.get(i).getServerId(), jsonStr); - - result.add(jsonStr); - } - - } - } catch (Exception e) { - log.info("Exception in string builder", e); - } - - return result; - } - - /** - * Sets the value for all fields in the FM data for individual cell. - * - * @param networkId - * Network Id of the cell - * @param ncServer - * Server Id of the cell - * @param cellId - * Node Id of the cell - * @param issue - * Contains the collision/confusion details of the cess - * @return returns EventFm object, with all the necessary parameters. - */ - public static EventFm setEventFm(String networkId, String ncServer, - String cellId, FmAlarmInfo issue) { - - log.info("Inside generate FmData"); - EventFm event = new EventFm(); - - try { - - CommonEventHeaderFm commonEventHeader = new CommonEventHeaderFm(); - FaultFields faultFields = new FaultFields(); - - commonEventHeader - .setStartEpochMicrosec(System.currentTimeMillis() * 1000); - commonEventHeader.setSourceName(cellId); - commonEventHeader.setReportingEntityName(ncServer); - - String uuid = globalFmCellIdUuidMap.get(cellId); - if (uuid == null) { - uuid = getUuid(); - globalFmCellIdUuidMap.put(cellId, uuid); - } - commonEventHeader.setSourceUuid(uuid); - - if (issue.getProblem().equals("Collision") - || issue.getProblem().equals("Confusion") - || issue.getProblem().equals("CollisionAndConfusion")) { - faultFields - .setAlarmCondition("RanPciCollisionConfusionOccurred"); - faultFields.setEventSeverity("CRITICAL"); - faultFields.setEventSourceType("other"); - faultFields.setSpecificProblem(issue.getProblem()); - - Map<String, String> alarmAdditionalInformation = new HashMap<String, String>(); - alarmAdditionalInformation.put("networkId", networkId); - alarmAdditionalInformation.put("collisions", - issue.getCollisionCount()); - alarmAdditionalInformation.put("confusions", - issue.getConfusionCount()); - - faultFields - .setAlarmAdditionalInformation(alarmAdditionalInformation); - - } - commonEventHeader - .setLastEpochMicrosec(System.currentTimeMillis() * 1000); - - event.setCommonEventHeader(commonEventHeader); - event.setFaultFields(faultFields); - - } catch (Exception e) { - log.info("Exception: ", e); - } - - return event; - - } - - /** - * It checks if the cell or any of its neighbors have collision/confusion - * issue. If there are any issues it generates the FM data for the entire - * cluster - * - * @param source - * The source from which the cell modification has been - * triggered. - * @param cell - * Details of the given cell. - * @param newNeighborList - * Neighbor list of the given cell. - */ - public void generateFmData(String source, CellDetails cell, - List<NeighborDetails> newNeighborList) { - - List<EventFm> listCellIssue = new ArrayList<EventFm>(); - Set<String> ncs = new HashSet<>(); - log.info("Generating Fm data"); - - RansimControllerDatabase rsDb = new RansimControllerDatabase(); - - FmAlarmInfo op1 = setCollisionConfusionFromFile(cell.getNodeId()); - - if (source.equals("GUI")) { - if (op1.getProblem().equals("CollisionAndConfusion") - || op1.getProblem().equals("Collision") - || op1.getProblem().equals("Confusion")) { - log.info("op1: " + op1); - EventFm lci = setEventFm(cell.getNetworkId(), - cell.getServerId(), cell.getNodeId(), op1); - listCellIssue.add(lci); - ncs.add(cell.getServerId()); - log.info("Generating Fm data for: " + cell.getNodeId()); - } - } - - for (NeighborDetails cd : newNeighborList) { - FmAlarmInfo op2 = setCollisionConfusionFromFile(cd.getNeigbor() - .getNeighborCell()); - CellDetails nbrCell = rsDb.getCellDetail(cd.getNeigbor() - .getNeighborCell()); - - if (source.equals("GUI")) { - if (op2.getProblem().equals("CollisionAndConfusion") - || op2.getProblem().equals("Collision") - || op2.getProblem().equals("Confusion")) { - EventFm lci = setEventFm(nbrCell.getNetworkId(), - nbrCell.getServerId(), nbrCell.getNodeId(), op2); - log.info("FmData added:" + nbrCell.getNodeId()); - listCellIssue.add(lci); - ncs.add(nbrCell.getServerId()); - log.info("Generating Fm data for: " + nbrCell.getNodeId()); - } - } - - } - - if (source.equals("GUI")) { - for (String nc : ncs) { - - FmMessage fmDataMessage = new FmMessage(); - List<EventFm> data = new ArrayList<EventFm>(); - log.info("listCellIssue.size(): " + listCellIssue.size()); - for (EventFm cellIssue : listCellIssue) { - if (cellIssue.getCommonEventHeader() - .getReportingEntityName().equals(nc)) { - data.add(cellIssue); - if (!cellsWithIssues.contains(cellIssue - .getCommonEventHeader().getSourceName())) { - cellsWithIssues.add(cellIssue - .getCommonEventHeader().getSourceName()); - } - - } - } - log.info("data.size(): " + data.size()); - - if (data.size() > 0) { - fmDataMessage.setFmEventList(data); - log.info("Sending FM message: "); - sendFmData(nc, fmDataMessage); - } - - } - } - - } - - /** - * Sends the FM data message to the netconf agent through the ransim - * websocket server. - * - * @param serverId - * server id of the netconf agent - * @param fmDataMessage - * FM message to be sent - */ - public void sendFmData(String serverId, FmMessage fmDataMessage) { - - log.info("inside sendFmData"); - Gson gson = new Gson(); - String jsonStr = gson.toJson(fmDataMessage); - - log.info("Fm Data jsonStr: " + jsonStr); - - String ipPort = rsCtrlr.serverIdIpPortMapping.get(serverId); - - if (ipPort != null && !ipPort.trim().equals("")) { - - String[] ipPortArr = ipPort.split(":"); - log.info("Connection estabilished with ip: " + ipPort); - if (ipPort != null && !ipPort.trim().equals("")) { - Session clSess = rsCtrlr.webSocketSessions.get(ipPort); - if (clSess != null) { - log.info("FM message sent."); - RansimWebSocketServer.sendFmMessage(jsonStr, clSess); - } else { - log.info("No client session for " + ipPort); - } - } else { - log.info("No client for " + serverId); - } - } else { - log.info("No client for "); - } - - } - -} |