Skip to content
Snippets Groups Projects
Commit fd4e5397 authored by Christos Tranoris's avatar Christos Tranoris
Browse files

initial commi

parent 95dd6e4e
No related branches found
No related tags found
1 merge request!8Merging 2024Q2_RC into main, creating 2024Q2 Release
Showing
with 2698 additions and 0 deletions
This diff is collapsed.
/*-
* ========================LICENSE_START=================================
* org.etsi.osl.portal.api
* %%
* Copyright (C) 2019 openslice.io
* %%
* 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 portal.api.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.etsi.osl.model.PortalUser;
import org.etsi.osl.model.UserRoleType;
import org.etsi.osl.model.VFImage;
import org.etsi.osl.model.VxFMetadata;
import jakarta.servlet.http.HttpServletRequest;
import portal.api.bus.BusController;
import portal.api.service.PortalPropertiesService;
import portal.api.service.UsersService;
import portal.api.service.VFImageService;
import portal.api.service.VxFService;
import portal.api.util.AttachmentUtil;
/**
* @author ctranoris
*
*/
@RestController
public class PortalRepositoryVFImageAPI {
private static final String VFIMAGESDIR = System.getProperty("user.home") + File.separator + ".vfimages"
+ File.separator ;
private static final transient Log logger = LogFactory.getLog( PortalRepositoryVFImageAPI.class.getName());
@Autowired
PortalPropertiesService propsService;
@Autowired
UsersService usersService;
@Autowired
VxFService vxfService;
@Autowired
VFImageService vfImageService;
@Autowired
ObjectMapper objectMapper;
@Autowired
BusController busController;
/**
*
* Image object API
*/
@GetMapping( value = "/admin/vfimages", produces = "application/json" )
public ResponseEntity<?> getAdminVFImages() {
//
PortalUser u = usersService.findByUsername( SecurityContextHolder.getContext().getAuthentication().getName() );
if (u != null) {
List<VFImage> vfimagess;
if (u.getRoles().contains(UserRoleType.ROLE_ADMIN) || u.getRoles().contains(UserRoleType.ROLE_TESTBED_PROVIDER)) {
vfimagess = vfImageService.getVFImages();
} else {
vfimagess = vfImageService.getVFImagesByUserID((long) u.getId());
}
return ResponseEntity.ok( vfimagess );
} else {
return (ResponseEntity<?>) ResponseEntity.notFound().build();
}
}
@PostMapping( value = "/admin/vfimages" )
public ResponseEntity<?> addVFImage(
final @ModelAttribute("vfimage") String v,
@RequestParam(name = "prodFile", required = false) MultipartFile prodFile,
HttpServletRequest request
) {
//
PortalUser u = usersService.findByUsername( SecurityContextHolder.getContext().getAuthentication().getName() );
if (u == null) {
return (ResponseEntity<?>) ResponseEntity.notFound().build();
}
VFImage vfimg = null;
String emsg = "";
try {
try {
vfimg = objectMapper.readValue( v, VFImage.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Received @POST for VFImage : " + vfimg.getName());
String uuid = UUID.randomUUID().toString();
vfimg.setUuid(uuid);
vfimg.setDateCreated(new Date());
vfimg.setOwner(u);
vfimg = addNewVFImage(vfimg, prodFile, request);
} catch (JsonProcessingException e) {
vfimg = null;
e.printStackTrace();
logger.error( e.getMessage() );
emsg = e.getMessage();
} catch (IOException e) {
vfimg = null;
e.printStackTrace();
logger.error( e.getMessage() );
emsg = e.getMessage();
}
if (vfimg != null) {
busController.newVFImageAdded( vfimg );
return ResponseEntity.ok( vfimg );
} else {
return (ResponseEntity<?>) ResponseEntity.status( HttpStatus.INTERNAL_SERVER_ERROR ).body( "Requested Image cannot be inserted" );
}
}
/**
* @param vfimg
* @param vfimagefile
* @return
* @throws IOException
*/
private VFImage addNewVFImage(VFImage vfimg, MultipartFile vfimagefile, HttpServletRequest request) throws IOException {
logger.info("image name = " + vfimg.getName());
logger.info("shortDescription = " +vfimg.getShortDescription());
String endpointUrl = request.getRequestURI();
String tempDir = VFIMAGESDIR + vfimg.getUuid() + File.separator;
if (vfimagefile != null) {
String imageFileNamePosted = vfimagefile.getOriginalFilename() ; //AttachmentUtil.getFileName(vfimagefile.getHeaders());
logger.info("vfimagefile = " + imageFileNamePosted);
if (!imageFileNamePosted.equals("") && !imageFileNamePosted.equals("unknown")) {
Files.createDirectories(Paths.get(tempDir));
String imgfile = AttachmentUtil.saveFile( vfimagefile, tempDir + imageFileNamePosted);
logger.info("vfimagefile saved to = " + imgfile);
vfimg.setPackageLocation(endpointUrl.toString().replace("http:", "") + "repo/vfimages/image/" + vfimg.getUuid() + "/"
+ imageFileNamePosted);
}
}
VFImage registeredvfimg = vfImageService.saveVFImage( vfimg );
return registeredvfimg;
}
/**
* @param vfimgnew
* @param vfimagefile
* @return
* @throws IOException
*/
private VFImage updateVFImage(VFImage vfimgnew, MultipartFile vfimagefile, HttpServletRequest request) throws IOException {
logger.info("image name = " + vfimgnew.getName());
logger.info("shortDescription = " +vfimgnew.getShortDescription());
String endpointUrl = request.getRequestURI();
String tempDir = VFIMAGESDIR + vfimgnew.getUuid() + File.separator;
VFImage prevfImage = vfImageService.getVFImageByID( vfimgnew.getId() );
if (vfimagefile != null) {
String imageFileNamePosted = vfimagefile.getOriginalFilename() ; //AttachmentUtil.getFileName(vfimagefile.getHeaders());
logger.info("vfimagefile = " + imageFileNamePosted);
if (!imageFileNamePosted.equals("") && !imageFileNamePosted.equals("unknown")) {
Files.createDirectories(Paths.get(tempDir));
String imgfile = AttachmentUtil.saveFile( vfimagefile, tempDir + imageFileNamePosted);
logger.info("vfimagefile saved to = " + imgfile);
prevfImage.setPackageLocation(endpointUrl.toString().replace("http:", "") + "repo/vfimages/image/" + prevfImage.getUuid() + "/"
+ imageFileNamePosted);
}
}
prevfImage.setShortDescription( vfimgnew.getShortDescription() );
prevfImage.setDateUpdated( new Date() );
prevfImage.setPublicURL( vfimgnew.getPublicURL());
prevfImage.setPublished( vfimgnew.isPublished() );
prevfImage.setTermsOfUse( vfimgnew.getTermsOfUse() );
VFImage registeredvfimg = vfImageService.updateVFImageInfo( prevfImage );
return registeredvfimg;
}
@GetMapping( value = "/vfimages/image/{uuid}/{vfimagefile}", produces = "application/gzip" )
public @ResponseBody byte[] downloadVxFPackage(@PathVariable("uuid") String uuid, @PathVariable("vfimagefile") String vfimagefile) throws IOException {
logger.info("vfimagefile: " + vfimagefile);
logger.info("uuid: " + uuid);
String vxfAbsfile = VFIMAGESDIR + uuid + File.separator + vfimagefile;
logger.info("VxF RESOURCE FILE: " + vxfAbsfile);
File file = new File(vxfAbsfile);
InputStream in = new FileInputStream( file );
return IOUtils.toByteArray(in);
}
@PutMapping( value = "/admin/vfimages", produces = "application/json", consumes = "multipart/form-data" )
public ResponseEntity<?> updateVFImage(
final @ModelAttribute("vfimage") String v,
@RequestParam(name = "prodFile", required = false) MultipartFile prodFile,
HttpServletRequest request) throws ForbiddenException {
VFImage vfimg = null;
String emsg = "";
try {
try {
vfimg = objectMapper.readValue( v, VFImage.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if ( !checkUserIDorIsAdmin( -1 ) ){
throw new ForbiddenException("The requested page is forbidden");//return (ResponseEntity<?>) ResponseEntity.status(HttpStatus.FORBIDDEN) ;
}
logger.info("Received @PUT for VFImage : " + vfimg.getName());
vfimg = updateVFImage(vfimg, prodFile, request);
} catch (JsonProcessingException e) {
vfimg = null;
e.printStackTrace();
logger.error( e.getMessage() );
emsg = e.getMessage();
} catch (IOException e) {
vfimg = null;
e.printStackTrace();
logger.error( e.getMessage() );
emsg = e.getMessage();
}
if (vfimg != null) {
busController.aVFImageUpdated( vfimg );
return ResponseEntity.ok( vfimg );
} else {
return (ResponseEntity<?>) ResponseEntity.status( HttpStatus.INTERNAL_SERVER_ERROR ).body( "Requested Image cannot be inserted" );
}
}
@DeleteMapping( value = "/admin/vfimages/{id}")
public ResponseEntity<?> deleteVFImage(@PathVariable("id") int id) throws ForbiddenException {
VFImage sm = vfImageService.getVFImageByID(id);
if ( !checkUserIDorIsAdmin( -1 ) ){
throw new ForbiddenException("The requested page is forbidden");//return (ResponseEntity<?>) ResponseEntity.status(HttpStatus.FORBIDDEN) ;
}
for (VxFMetadata vxf : sm.getUsedByVxFs()) {
vxf.getVfimagesVDU().remove(sm);
vxfService.updateProductInfo(vxf);
}
vfImageService.deleteVFImage( sm );
return ResponseEntity.ok( "{}" );
}
@GetMapping( value = "/admin/vfimages/{id}", produces = "application/json" )
public ResponseEntity<?> getVFImageById(@PathVariable("id") long id) throws ForbiddenException {
VFImage sm = vfImageService.getVFImageByID(id);
if (sm != null) {
if ( !checkUserIDorIsAdmin( -1 ) ){
throw new ForbiddenException("The requested page is forbidden");//return (ResponseEntity<?>) ResponseEntity.status(HttpStatus.FORBIDDEN) ;
}
return ResponseEntity.ok( sm );
} else {
return (ResponseEntity<?>) ResponseEntity.notFound().build();
}
}
@GetMapping( value = "/admin/vfimages/name/{imagename}", produces = "application/json" )
public ResponseEntity<?> getVFImageByName(@PathVariable("imagename") String imagename) throws ForbiddenException {
VFImage sm = vfImageService.getVFImageByName( imagename );
if (sm != null) {
if ( !checkUserIDorIsAdmin( -1 ) ){
throw new ForbiddenException("The requested page is forbidden");//return (ResponseEntity<?>) ResponseEntity.status(HttpStatus.FORBIDDEN) ;
}
return ResponseEntity.ok( sm );
} else {
return (ResponseEntity<?>) ResponseEntity.notFound().build();
}
}
/**
* @param userID
* @return true if user logged is equal to the requested id of owner, or is ROLE_ADMIN
*/
private boolean checkUserIDorIsAdmin(long userID){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
logger.info("principal 1= " + authentication.getAuthorities().contains( new SimpleGrantedAuthority( UserRoleType.ROLE_ADMIN.getValue() ) ));
logger.info("principal 2= " + authentication.getAuthorities().contains( new SimpleGrantedAuthority( UserRoleType.ROLE_TESTBED_PROVIDER.getValue() ) ));
logger.info("principal 2= " + authentication.getAuthorities().contains( new SimpleGrantedAuthority( UserRoleType.ROLE_MENTOR.getValue() ) ));
if ( authentication.getAuthorities().contains( new SimpleGrantedAuthority( UserRoleType.ROLE_ADMIN.getValue() ))){
logger.info("checkUserIDorIsAdmin, authentication role = " + authentication.getAuthorities().contains( new SimpleGrantedAuthority( UserRoleType.ROLE_ADMIN.getValue() ) ));
return true;
}
PortalUser uToFind = usersService.findById( userID );
if ( (uToFind !=null ) && ( uToFind.getUsername() == authentication.getName()) ){
logger.info("checkUserIDorIsAdmin, user is equal with request");
return true;
}
return false;
}
}
/*-
* ========================LICENSE_START=================================
* org.etsi.osl.portal.api
* %%
* Copyright (C) 2019 openslice.io
* %%
* 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 portal.api.mano;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.etsi.osl.centrallog.client.*;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpStatusCodeException;
import portal.api.bus.BusController;
//import portal.api.centrallog.CLevel;
//import portal.api.centrallog.CentralLogger;
import portal.api.service.DeploymentDescriptorService;
import portal.api.service.ManoProviderService;
import portal.api.service.NSDOBDService;
import portal.api.service.NSDService;
import portal.api.service.PortalPropertiesService;
import portal.api.service.VxFOBDService;
import portal.api.service.VxFService;
import org.etsi.osl.model.DeploymentDescriptor;
import org.etsi.osl.model.DeploymentDescriptorStatus;
import org.etsi.osl.model.ExperimentMetadata;
import org.etsi.osl.model.ExperimentOnBoardDescriptor;
import org.etsi.osl.model.MANOprovider;
import org.etsi.osl.model.OnBoardDescriptor;
import org.etsi.osl.model.OnBoardingStatus;
import org.etsi.osl.model.VxFMetadata;
import org.etsi.osl.model.VxFOnBoardedDescriptor;
/**
* @author ctranoris
*
*/
@Configuration
public class MANOController {
/** */
private static final transient Log logger = LogFactory.getLog(MANOController.class.getName());
@Autowired
VxFOBDService vxfOBDService;
@Autowired
VxFService vxfService;
@Autowired
DeploymentDescriptorService deploymentDescriptorService;
@Autowired
ManoProviderService manoProviderService;
@Autowired
NSDService nsdService;
@Autowired
NSDOBDService nsdOBDService;
@Autowired
PortalPropertiesService propsService;
@Autowired
BusController busController;
@Autowired
MANOStatus aMANOStatus;
public MANOController() {
}
@Value("${spring.application.name}")
private String compname;
@Autowired
private CentralLogger centralLogger;
@Bean("aMANOController")
public MANOController aMANOControllerBean() {
return new MANOController();
}
// private static String HTTP_SCHEME = "https:";
// public static void setHTTPSCHEME(String url) {
// logger.info("setHTTPSCHEME url = " + url);
//// if (url.contains("localhost")) {
//// HTTP_SCHEME = "http:";
//// }
// // HTTP_SCHEME = url + ":";
// }
/**
* onBoard a VNF to MANO Provider, as described by this descriptor
*
* @param vxfobds
* @throws Exception
*/
public void onBoardVxFToMANOProvider( long vxfobdid ) throws Exception {
if (vxfOBDService == null) {
throw new Exception("vxfOBDService is NULL. Cannot load VxFOnBoardedDescriptor");
}
VxFOnBoardedDescriptor vxfobd = vxfOBDService.getVxFOnBoardedDescriptorByID(vxfobdid);
// PortalRepository portalRepositoryRef = new PortalRepository();
if (vxfobd == null) {
throw new Exception("vxfobd is NULL. Cannot load VxFOnBoardedDescriptor");
}
if (vxfobd.getVxf() == null) {
throw new Exception("vxfobd.getVxf() is NULL. Cannot load VxFOnBoardedDescriptor");
}
if (vxfobd.getVxf().getName() == null) {
throw new Exception("vxfobd.getVxf() is NULL. Cannot load VxFOnBoardedDescriptor");
}
vxfobd.setOnBoardingStatus(OnBoardingStatus.ONBOARDING);
// This is the Deployment ID for the portal
vxfobd.setDeployId(UUID.randomUUID().toString());
// VxFMetadata vxf = vxfobd.getVxf();
// if (vxf == null) {
// vxf = (VxFMetadata) vxfService.getProductByID(vxfobd.getVxfid());
// }
centralLogger.log( CLevel.INFO, "Onboarding status change of VxF "+vxfobd.getVxf().getName()+" to "+vxfobd.getOnBoardingStatus(), compname);
// Set MANO Provider VxF ID
vxfobd.setVxfMANOProviderID( vxfobd.getVxf().getName());
// Set onBoarding Date
vxfobd.setLastOnboarding(new Date());
VxFOnBoardedDescriptor vxfobds = vxfOBDService.updateVxFOnBoardedDescriptor(vxfobd);
if (vxfobds == null) {
throw new Exception("Cannot load VxFOnBoardedDescriptor");
}
String pLocation = vxfobd.getVxf().getPackageLocation();
logger.info("VxF Package Location: " + pLocation);
if (!pLocation.contains("http")) {
pLocation = propsService.getPropertyByName( "maindomain" ).getValue() + pLocation;
}
// if (!pLocation.contains("http")) {
// pLocation = "http:" + pLocation;
// pLocation = pLocation.replace("\\", "/");
// }
logger.info("PROPER VxF Package Location: " + pLocation);
}
public void checkAndDeleteTerminatedOrFailedDeployments() {
logger.info("Check and Delete Terminated and Failed Deployments");
List<DeploymentDescriptor> DeploymentDescriptorsToDelete = deploymentDescriptorService.getDeploymentsToBeDeleted();
for (DeploymentDescriptor d : DeploymentDescriptorsToDelete) {
// Launch the deployment
logger.info("Send to bus control to delete: " + d.getId());
busController.deleteExperiment(d);
}
}
public void checkAndDeployExperimentToMANOProvider() {
logger.info("This will trigger the check and Deploy Experiments");
// Check the database for a new deployment in the next minutes
// If there is a deployment to be made and the status is Scheduled
List<DeploymentDescriptor> DeploymentDescriptorsToRun = deploymentDescriptorService.getDeploymentsToInstantiate();
// Foreach deployment
for (DeploymentDescriptor d : DeploymentDescriptorsToRun) {
// Launch the deployment
busController.deployExperiment(d );
}
}
public void checkAndTerminateExperimentToMANOProvider() {
logger.info("This will trigger the check and Terminate Deployments");
// Check the database for a deployment to be completed in the next minutes
// If there is a deployment to be made and the status is Scheduled
List<DeploymentDescriptor> DeploymentDescriptorsToComplete = deploymentDescriptorService.getDeploymentsToBeCompleted();
// Foreach deployment
for (DeploymentDescriptor deployment_descriptor_tmp : DeploymentDescriptorsToComplete) {
logger.debug("Deployment with id" + deployment_descriptor_tmp.getName() + " with status " + deployment_descriptor_tmp.getStatus() +" is going to be terminated");
// Terminate the deployment
busController.completeExperiment(deployment_descriptor_tmp );
}
}
public void checkAndUpdateRunningDeploymentDescriptors() {
logger.info("Update Deployment Descriptors");
List<DeploymentDescriptor> runningDeploymentDescriptors = deploymentDescriptorService.getRunningInstantiatingAndTerminatingDeployments();
// For each deployment get the status info and the IPs
for (int i = 0; i < runningDeploymentDescriptors.size(); i++) {
DeploymentDescriptor deployment_tmp = deploymentDescriptorService.getDeploymentByIdEager(runningDeploymentDescriptors.get(i).getId());
try {
// Get the MANO Provider for each deployment
MANOprovider sm = manoProviderService.getMANOproviderByID( getExperimOBD( deployment_tmp ).getObMANOprovider().getId() );
} catch (Exception e) {
logger.error(e.getMessage());
}
}
checkAndDeployExperimentToMANOProvider();
checkAndTerminateExperimentToMANOProvider();
checkAndDeleteTerminatedOrFailedDeployments();
}
private ExperimentOnBoardDescriptor getExperimOBD(DeploymentDescriptor deployment_tmp) {
for (ExperimentOnBoardDescriptor e : deployment_tmp.getExperimentFullDetails().getExperimentOnBoardDescriptors()) {
return e; //return the first one found
}
return null;
}
public void onBoardNSDToMANOProvider( long uexpobdid ) throws Exception {
ExperimentOnBoardDescriptor uexpobd = nsdOBDService.getExperimentOnBoardDescriptorByID(uexpobdid);
if (uexpobd == null) {
throw new Exception("uexpobd is NULL. Cannot load VxFOnBoardedDescriptor");
}
uexpobd.setOnBoardingStatus(OnBoardingStatus.ONBOARDING);
centralLogger.log( CLevel.INFO, "Onboarding status change of Experiment "+uexpobd.getExperiment().getName()+" to "+uexpobd.getOnBoardingStatus(), compname);
// This is the Deployment ID for the portal
uexpobd.setDeployId(UUID.randomUUID().toString());
ExperimentMetadata em = uexpobd.getExperiment();
if (em == null) {
em = (ExperimentMetadata) nsdService.getProductByID(uexpobd.getExperimentid());
}
/**
* The following is not OK. When we submit to OSMClient the createOnBoardPackage
* we just get a response something like response = {"output":
* {"transaction-id": "b2718ef9-4391-4a9e-97ad-826593d5d332"}} which does not
* provide any information. The OSM RIFTIO API says that we could get
* information about onboarding (create or update) jobs see
* https://open.riftio.com/documentation/riftware/4.4/a/api/orchestration/pkt-mgmt/rw-pkg-mgmt-download-jobs.htm
* with /api/operational/download-jobs, but this does not return pending jobs.
* So the only solution is to ask again OSM if something is installed or not, so
* for now the client (the portal ) must check via the
* getVxFOnBoardedDescriptorByIdCheckMANOProvider giving the VNF ID in OSM. OSM
* uses the ID of the yaml description Thus we asume that the vxf name can be
* equal to the VNF ID in the portal, and we use it for now as the OSM ID. Later
* in future, either OSM API provide more usefull response or we extract info
* from the VNFD package
*
*/
//uexpobd.setVxfMANOProviderID(em.getName()); // Possible Error. This probably needs to be
uexpobd.setExperimentMANOProviderID(em.getName());
uexpobd.setLastOnboarding(new Date());
ExperimentOnBoardDescriptor uexpobds = nsdOBDService.updateExperimentOnBoardDescriptor(uexpobd);
if (uexpobds == null) {
throw new Exception("Cannot load NSDOnBoardedDescriptor");
}
String pLocation = em.getPackageLocation();
logger.info("NSD Package Location: " + pLocation);
if (!pLocation.contains("http")) {
pLocation = propsService.getPropertyByName( "maindomain" ).getValue() + pLocation;
}
// if (!pLocation.contains("http")) {
// pLocation = "http:" + pLocation;
// pLocation = pLocation.replace("\\", "/");
// }
}
/**
* offBoard a VNF to MANO Provider, as described by this descriptor
*
* @param c
*/
public ResponseEntity<String> offBoardVxFFromMANOProvider(VxFOnBoardedDescriptor obd)
throws HttpClientErrorException {
// TODO Auto-generated method stub
ResponseEntity<String> response = null;
return response;
}
private void checkVxFStatus(VxFOnBoardedDescriptor obd) throws Exception {
CamelContext tempcontext = new DefaultCamelContext();
MANOController mcontroller = this;
try {
RouteBuilder rb = new RouteBuilder() {
@Override
public void configure() throws Exception {
from("timer://getVNFRepoTimer?delay=2000&period=3000&repeatCount=6&daemon=true")
.log("Will check VNF repo").setBody().constant(obd)
.bean(mcontroller, "getVxFStatusFromOSM2Client");
}
};
tempcontext.addRoutes(rb);
tempcontext.start();
Thread.sleep(30000);
} finally {
tempcontext.stop();
}
}
public ResponseEntity<String> offBoardNSDFromMANOProvider(ExperimentOnBoardDescriptor uexpobd) {
// TODO Auto-generated method stub
ResponseEntity<String> response = null;
// return new ResponseEntity<>("Not found", HttpStatus.NOT_FOUND);
return response;
}
public void deployNSDToMANOProvider(int deploymentdescriptorid) {
DeploymentDescriptor deploymentdescriptor = deploymentDescriptorService.getDeploymentByIdEager(deploymentdescriptorid);
logger.info("deploymentdescriptor.getExperimentFullDetails() = " + getExperimOBD(deploymentdescriptor) );
logger.info("deploymentdescriptor.getExperimentFullDetails() = " + getExperimOBD(deploymentdescriptor).getObMANOprovider());
return;
}
public void terminateNSFromMANOProvider(int deploymentdescriptorid) {
DeploymentDescriptor deploymentdescriptor = deploymentDescriptorService.getDeploymentByIdEager(deploymentdescriptorid);
}
public void deleteNSFromMANOProvider(int deploymentdescriptorid) {
DeploymentDescriptor deploymentdescriptor = deploymentDescriptorService.getDeploymentByIdEager(deploymentdescriptorid);
logger.info("Will delete with deploymentdescriptorid : " + deploymentdescriptorid);
String aMANOplatform = "";
try {
aMANOplatform = getExperimOBD(deploymentdescriptor).getObMANOprovider().getSupportedMANOplatform().getName();
logger.info("MANOplatform: " + aMANOplatform);
}catch (Exception e) {
aMANOplatform = "UNKNOWN";
}
//if this is not a suported OSM then just complete
logger.info("Descriptor targets an older not supported OSM deploymentdescriptorid: " + deploymentdescriptorid);
deploymentdescriptor.setStatus(DeploymentDescriptorStatus.FAILED_OSM_REMOVED);
logger.info( "Status change of deployment " + deploymentdescriptor.getId()+", "+deploymentdescriptor.getName()+" to "+deploymentdescriptor.getStatus());
DeploymentDescriptor deploymentdescriptor_final = deploymentDescriptorService.updateDeploymentDescriptor(deploymentdescriptor);
logger.info("NS status changed is now :" + deploymentdescriptor_final.getStatus());
}
// OSM5 END
}
/*-
* ========================LICENSE_START=================================
* org.etsi.osl.portal.api
* %%
* Copyright (C) 2019 openslice.io
* %%
* 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 portal.api.mano;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* @author ctranoris
*
*/
@Component
@Configuration
public class MANORouteBuilder extends RouteBuilder{
@Autowired
MANOController aMANOController;
public static void main(String[] args) throws Exception {
//new Main().run(args);
CamelContext tempcontext = new DefaultCamelContext();
try {
RouteBuilder rb = new RouteBuilder() {
@Override
public void configure() throws Exception {
from( "timer://getVNFRepoTimer?period=2000&repeatCount=3&daemon=true" )
.log( "Will check VNF repo");
from( "timer://getNSDRepoTimer?period=2000&repeatCount=3&daemon=true" )
.log( "Will check NSD repo");
}
};
tempcontext.addRoutes( rb);
tempcontext.start();
Thread.sleep(30000);
} finally {
tempcontext.stop();
}
}
public void configure() {
/**
* OnBoard New Added VxF
*/
//We get the message here and we need to route it to the proper point.
//If onboarding is successfull we need to send a Bugzilla message
//If it is unsuccessful we need to send another Bugzilla message
//************************************************************************************
// DISABLING THIS TO OFFLOAD THE CALL TO org.etsi.osl.mano
//from("seda:vxf.onboard?multipleConsumers=true")
//.doTry()
//.bean( aMANOController,"onBoardVxFToMANOProvider") //returns exception or nothing
//.log("VNFD Onboarded handled")
//.doCatch(Exception.class)
//.log("VNFD Onboarding failed!");
//
//from("seda:nsd.onboard?multipleConsumers=true")
//.doTry()
//.bean( aMANOController,"onBoardNSDToMANOProvider") //returns exception or nothing
//.log("NSD Onboarded handled")
//.doCatch(Exception.class)
//.log("NSD Onboarding failed!");
//
//************************************************************************************
from("seda:nsd.deploy?multipleConsumers=true")
.doTry()
.bean( aMANOController,"deployNSDToMANOProvider") //returns exception or nothing
.log("NS deployed handled").stop()
.doCatch(Exception.class)
.log("NS deployment failed!").stop();
from("seda:nsd.deployment.complete?multipleConsumers=true")
.doTry()
.bean( aMANOController,"terminateNSFromMANOProvider") //returns exception or nothing
.log("NS completed handled")
.doCatch(Exception.class)
.log("NS completion failed!").stop();
from("seda:nsd.deployment.delete?multipleConsumers=true")
.doTry()
.bean( aMANOController,"deleteNSFromMANOProvider") //returns exception or nothing
.log("NS deleted handled")
.doCatch(Exception.class)
.log("NS deletion failed!").stop();
//from("timer://checkAndDeployTimer?delay=2m&period=120000").bean( aMANOController,"checkAndDeployExperimentToMANOProvider").stop();
//from("timer://checkAndTerminateTimer?delay=2m&period=120000").bean( aMANOController,"checkAndTerminateExperimentToMANOProvider").stop();
//from("timer://checkAndUpdateRunningDeploymentDescriptors?delay=1m&period=60000").bean( aMANOController,"checkAndUpdateRunningDeploymentDescriptors").stop();
}
}
/*-
* ========================LICENSE_START=================================
* org.etsi.osl.portal.api
* %%
* Copyright (C) 2019 openslice.io
* %%
* 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 portal.api.mano;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import org.etsi.osl.model.MANOprovider;
/**
* @author ctranoris
*
*/
public class MANOService {
protected EntityManager em;
public MANOService(EntityManager em)
{
this.em=em;
}
public List<MANOprovider> getAllMANOproviders()
{
TypedQuery<MANOprovider> query = em.createQuery("SELECT mp FROM MANOprovider mp",MANOprovider.class);
return query.getResultList();
}
public List<MANOprovider> getMANOprovidersEnabledForOnboarding()
{
TypedQuery<MANOprovider> query = em.createQuery("SELECT mp FROM MANOprovider mp WHERE mp.enabledForONBOARDING=1",MANOprovider.class);
return query.getResultList();
}
}
/*-
* ========================LICENSE_START=================================
* org.etsi.osl.portal.api
* %%
* Copyright (C) 2019 openslice.io
* %%
* 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 portal.api.mano;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import portal.api.bus.BusController;
/**
* @author ctranoris
*
*/
@Configuration
public class MANOStatus
{
@Autowired
BusController busController;
//1: Active, 0:Failed
private static Status osm4CommunicationStatus = Status.Active;
private static String osm4CommunicationStatusUUID = null;
private static Status osm5CommunicationStatus = Status.Active;
private static String osm5CommunicationStatusUUID = null;
private static String message;
public static enum Status {Failed,Active};
private static java.util.concurrent.locks.ReadWriteLock lock = new java.util.concurrent.locks.ReentrantReadWriteLock();
public static Status getOsm5CommunicationStatus() {
lock.readLock().lock();
try {
return osm5CommunicationStatus;
} finally {
lock.readLock().unlock();
}
}
public static void setOsm5CommunicationStatus(Status osm5CommunicationStatus) {
lock.writeLock().lock();
try {
MANOStatus.osm5CommunicationStatus = osm5CommunicationStatus;
} finally {
lock.writeLock().unlock();
}
}
public static String getOsm5CommunicationStatusUUID() {
lock.readLock().lock();
try {
return osm5CommunicationStatusUUID;
} finally {
lock.readLock().unlock();
}
}
public static void setOsm5CommunicationStatusUUID(String osm5CommunicationStatusUUID) {
lock.writeLock().lock();
try {
MANOStatus.osm5CommunicationStatusUUID = osm5CommunicationStatusUUID;
} finally {
lock.writeLock().unlock();
}
}
public static String getMessage() {
lock.readLock().lock();
try {
return message;
} finally {
lock.readLock().unlock();
}
}
public static void setMessage(String message) {
lock.writeLock().lock();
try {
MANOStatus.message = message;
} finally {
lock.writeLock().unlock();
}
}
public void setOsm5CommunicationStatusFailed(String message) {
lock.writeLock().lock();
try {
if(message == null)
{
message="";
}
if(MANOStatus.osm5CommunicationStatus == Status.Active)
{
MANOStatus.osm5CommunicationStatus = Status.Failed ;
MANOStatus.setMessage("OSM5 communication failed." + message);
MANOStatus.setOsm5CommunicationStatusUUID(UUID.randomUUID().toString());
System.out.println("Inside setOSM5CommunicationStatusFailed. "+MANOStatus.getOsm5CommunicationStatusUUID().toString()+","+MANOStatus.getMessage().toString());
busController.osm5CommunicationFailed(MANOStatus.class);
}
} finally {
lock.writeLock().unlock();
}
}
public void setOsm5CommunicationStatusActive(String message) {
lock.writeLock().lock();
try {
// TODO Auto-generated method stub
if(message == null)
{
message="";
}
if(MANOStatus.osm5CommunicationStatus == Status.Failed)
{
MANOStatus.osm5CommunicationStatus = Status.Active ;
MANOStatus.setMessage("OSM5 communication restored." + message);
busController.osm5CommunicationRestored(MANOStatus.class);
}
} finally {
lock.writeLock().unlock();
}
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment