From 2232aa2aeb19d7d2a52100c137a927e352b74679 Mon Sep 17 00:00:00 2001 From: Christos Tranoris Date: Mon, 6 Nov 2023 13:57:03 +0200 Subject: [PATCH] Initial commit (cherry picked from commit 45cb57de89ae312eb0a32d22012da01225cfb558) --- .gitignore | 4 + Dockerfile.mano | 6 + LICENSE | 201 ++ README.md | 92 +- pom.xml | 242 ++ .../osl/mano/ActiveMQComponentConfig.java | 41 + .../java/org/etsi/osl/mano/AlarmsService.java | 54 + .../java/org/etsi/osl/mano/MANOClient.java | 1316 ++++++++ .../org/etsi/osl/mano/MANOController.java | 2883 +++++++++++++++++ .../org/etsi/osl/mano/MANORouteBuilder.java | 283 ++ .../java/org/etsi/osl/mano/MANOService.java | 54 + .../java/org/etsi/osl/mano/MANOStatus.java | 141 + .../mano/NSCreateInstanceRequestPayload.java | 40 + .../NSInstantiateInstanceRequestPayload.java | 129 + .../org/etsi/osl/mano/OSMClientFactory.java | 79 + .../osl/mano/VIMCreateRequestPayload.java | 118 + src/main/resources/application.yml | 65 + src/main/resources/banner.txt | 11 + src/main/resources/bootstrap.yml | 0 src/main/resources/logback.xml | 60 + src/test/resources/readme.txt | 0 21 files changed, 5728 insertions(+), 91 deletions(-) create mode 100644 .gitignore create mode 100644 Dockerfile.mano create mode 100644 LICENSE create mode 100644 pom.xml create mode 100644 src/main/java/org/etsi/osl/mano/ActiveMQComponentConfig.java create mode 100644 src/main/java/org/etsi/osl/mano/AlarmsService.java create mode 100644 src/main/java/org/etsi/osl/mano/MANOClient.java create mode 100644 src/main/java/org/etsi/osl/mano/MANOController.java create mode 100644 src/main/java/org/etsi/osl/mano/MANORouteBuilder.java create mode 100644 src/main/java/org/etsi/osl/mano/MANOService.java create mode 100644 src/main/java/org/etsi/osl/mano/MANOStatus.java create mode 100644 src/main/java/org/etsi/osl/mano/NSCreateInstanceRequestPayload.java create mode 100644 src/main/java/org/etsi/osl/mano/NSInstantiateInstanceRequestPayload.java create mode 100644 src/main/java/org/etsi/osl/mano/OSMClientFactory.java create mode 100644 src/main/java/org/etsi/osl/mano/VIMCreateRequestPayload.java create mode 100644 src/main/resources/application.yml create mode 100644 src/main/resources/banner.txt create mode 100644 src/main/resources/bootstrap.yml create mode 100644 src/main/resources/logback.xml create mode 100644 src/test/resources/readme.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5601d3b --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/target/ +.project +.classpath +/.settings diff --git a/Dockerfile.mano b/Dockerfile.mano new file mode 100644 index 0000000..a26cd4f --- /dev/null +++ b/Dockerfile.mano @@ -0,0 +1,6 @@ +FROM ibm-semeru-runtimes:open-17.0.7_7-jdk +MAINTAINER openslice.io +RUN mkdir /opt/shareclasses +RUN mkdir -p /opt/openslice/lib/ +COPY target/org.etsi.osl.manoclient-1.2.0-SNAPSHOT.jar /opt/openslice/lib/ +CMD ["java", "-Xshareclasses:cacheDir=/opt/shareclasses","-jar", "/opt/openslice/lib/org.etsi.osl.manoclient-1.2.0-SNAPSHOT.jar"] \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/README.md b/README.md index 64fc532..5cb33d3 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,2 @@ # org.etsi.osl.mano - - - -## Getting started - -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://labs.etsi.org/rep/osl/code/org.etsi.osl.mano.git -git branch -M main -git push -uf origin main -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://labs.etsi.org/rep/osl/code/org.etsi.osl.mano/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +MANO wrapper service diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..4009888 --- /dev/null +++ b/pom.xml @@ -0,0 +1,242 @@ + + 4.0.0 + + org.etsi.osl + org.etsi.osl.main + 1.2.0-SNAPSHOT + ../org.etsi.osl.main + + + org.etsi.osl.manoclient + + org.etsi.osl.manoclient + http://maven.apache.org + + + UTF-8 + UTF-8 + ${spring-boot-version} + + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring.boot-version} + pom + import + + + + org.apache.camel.springboot + camel-spring-boot-dependencies + ${camel.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + org.springframework.boot + spring-boot-starter-cache + + + org.apache.camel.springboot + camel-undertow-starter + + + org.springframework.boot + spring-boot-starter-undertow + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-actuator + + + + + org.springframework.boot + spring-boot-starter-activemq + + + org.apache.activemq + activemq-amqp + test + + + org.apache.qpid + proton-j + + + + + org.messaginghub + pooled-jms + + + + + org.apache.camel.springboot + camel-spring-boot-starter + + + + org.apache.camel.springboot + camel-http-starter + + + org.apache.activemq + activemq-pool + + + org.apache.camel + camel-activemq + + + org.apache.activemq + activemq-broker + + + + + org.apache.camel.springboot + camel-service-starter + + + org.apache.camel + camel-jackson + + + org.apache.camel + camel-stream + + + com.h2database + h2 + + + org.etsi.osl + org.etsi.osl.tmf.api + ${project.version} + + + org.etsi.osl + org.etsi.osl.model + ${project.version} + + + org.etsi.osl + org.etsi.osl.centrallog.client + ${project.version} + + + com.fasterxml.jackson.core + jackson-databind + + + org.etsi.osl.sol005nbi + org.etsi.osl.sol005nbi.osm + 1.2.0-SNAPSHOT + + + org.etsi.osl.sol005nbi + org.etsi.osl.sol005nbi.osm10 + 1.2.0-SNAPSHOT + + + com.fasterxml.jackson.datatype + jackson-datatype-hibernate5-jakarta + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + org.opendaylight.yangtools + yang-common + 6.0.5 + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + + com.jayway.jsonpath + json-path + 2.6.0 + + + + + + org.glassfish.jaxb + jaxb-runtime + + + org.opendaylight.mdsal + yang-binding + 7.0.6 + + + com.google.guava + guava + 29.0-jre + + + + org.opendaylight.yangtools + yang-binding + 0.7.4-Lithium-SR4 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${java.version} + ${java.version} + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-version} + + + + repackage + + + + + + + \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/mano/ActiveMQComponentConfig.java b/src/main/java/org/etsi/osl/mano/ActiveMQComponentConfig.java new file mode 100644 index 0000000..d5443f4 --- /dev/null +++ b/src/main/java/org/etsi/osl/mano/ActiveMQComponentConfig.java @@ -0,0 +1,41 @@ +/*- + * ========================LICENSE_START================================= + * org.etsi.osl.bugzilla + * %% + * 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 org.etsi.osl.mano; + +import jakarta.jms.ConnectionFactory; + +import org.apache.camel.component.activemq.ActiveMQComponent; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author ctranoris + * + */ +@Configuration +public class ActiveMQComponentConfig { + + @Bean(name = "activemq") + public ActiveMQComponent createComponent(ConnectionFactory factory) { + ActiveMQComponent activeMQComponent = new ActiveMQComponent(); + activeMQComponent.setConnectionFactory(factory); + return activeMQComponent; + } +} diff --git a/src/main/java/org/etsi/osl/mano/AlarmsService.java b/src/main/java/org/etsi/osl/mano/AlarmsService.java new file mode 100644 index 0000000..cde4775 --- /dev/null +++ b/src/main/java/org/etsi/osl/mano/AlarmsService.java @@ -0,0 +1,54 @@ +package org.etsi.osl.mano; + +import java.io.IOException; + +import org.apache.camel.CamelContext; +import org.apache.camel.ProducerTemplate; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.etsi.osl.tmf.am642.model.AlarmCreate; + +@Service +public class AlarmsService { + + private static final transient Log logger = LogFactory.getLog(AlarmsService.class.getName()); + + @Autowired + CamelContext contxt; + + @Autowired + ProducerTemplate template; + + @Value("${ALARMS_ADD_ALARM}") + private String ALARMS_ADD_ALARM =""; + + /** + * @param al + * @return a response in string + * @throws IOException + */ + public String createAlarm(AlarmCreate al) throws IOException { + + String body; + body = toJsonString(al); + logger.info("createAlarm body = " + body); + Object response = template.requestBody( ALARMS_ADD_ALARM, body); + return response.toString(); + } + + + + static String toJsonString(Object object) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + return mapper.writeValueAsString(object); + } + +} diff --git a/src/main/java/org/etsi/osl/mano/MANOClient.java b/src/main/java/org/etsi/osl/mano/MANOClient.java new file mode 100644 index 0000000..cf30357 --- /dev/null +++ b/src/main/java/org/etsi/osl/mano/MANOClient.java @@ -0,0 +1,1316 @@ +/*- + * ========================LICENSE_START================================= + * org.etsi.osl.manoclient + * %% + * Copyright (C) 2019 - 2020 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 org.etsi.osl.mano; + +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; + +import org.apache.camel.CamelContext; +import org.apache.camel.FluentProducerTemplate; +import org.apache.camel.ProducerTemplate; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.hibernate5.jakarta.Hibernate5JakartaModule; + +import org.etsi.osl.model.DeploymentDescriptor; +import org.etsi.osl.model.ExperimentMetadata; +import org.etsi.osl.model.ExperimentOnBoardDescriptor; +import org.etsi.osl.model.Infrastructure; +import org.etsi.osl.model.MANOprovider; +import org.etsi.osl.model.PortalUser; +import org.etsi.osl.model.VxFMetadata; +import org.etsi.osl.model.VxFOnBoardedDescriptor; +import org.etsi.osl.tmf.am642.model.AffectedService; +import org.etsi.osl.tmf.am642.model.AlarmCreate; +import org.etsi.osl.tmf.am642.model.AlarmStateType; +import org.etsi.osl.tmf.am642.model.AlarmType; +import org.etsi.osl.tmf.am642.model.Comment; +import org.etsi.osl.tmf.am642.model.PerceivedSeverityType; +import org.etsi.osl.tmf.am642.model.ProbableCauseType; + +import org.springframework.stereotype.Service; + +@Service +public class MANOClient { + + private static final transient Log logger = LogFactory.getLog(MANOClient.class.getName()); + + @Autowired + CamelContext contxt; + +// @Autowired +// public void setActx(CamelContext actx) { +// MANOClient.contxt = actx; +// logger.info( "MANOClient configure() contxt = " + contxt); +// } + + @Autowired + ProducerTemplate template; + + MANOController aMANOController; + + @Autowired + AlarmsService alarmsService; + + @Value("${spring.application.name}") + private String compname; + + @Value("${NFV_CATALOG_NS_LCMCHANGED}") + private String NFV_CATALOG_NS_LCMCHANGED = ""; + + public VxFOnBoardedDescriptor getVxFOnBoardedDescriptorByID(long id) { + String ret = template.requestBody("activemq:queue:getVxFOnBoardedDescriptorByID", id, String.class); + + VxFOnBoardedDescriptor vxf_obd = null; + // Map object to VxFOnBoardedDescriptor + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + vxf_obd = mapper.readValue(ret, new TypeReference() { + }); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return vxf_obd; + } + + // Get the data from the portal api (database) + public List getRunningInstantiatingAndTerminatingDeployments() { + String ret = template.requestBody("activemq:queue:getRunningInstantiatingAndTerminatingDeployments", "", + String.class); + + List nsds = null; + // Map object to DeploymentDescriptor + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + nsds = mapper.readValue(ret, new TypeReference>() { + }); + for (int i = 0; i < nsds.size(); i++) { + logger.info("The detailed status of " + nsds.get(i).getName() + " is " + nsds.get(i).getDetailedStatus()); + } + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return nsds; + } + + public List getInfrastructures() { + String ret = template.requestBody("activemq:queue:getInfrastructures", "", String.class); + + List infrastructures = null; + // Map object to Infrastructure + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + infrastructures = mapper.readValue(ret, new TypeReference>() { + }); + for (int i = 0; i < infrastructures.size(); i++) { + logger.info("Infrastructure " + infrastructures.get(i).getName() + " with VIM id:" + + infrastructures.get(i).getVIMid() + " is loaded"); + } + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return infrastructures; + } + + public List getVnfds() { + String ret = template.requestBody("activemq:queue:getVnfds", "", String.class); + List vxfs = null; + // Map object to Infrastructure + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + vxfs = mapper.readValue(ret, new TypeReference>() { + }); + for (int i = 0; i < vxfs.size(); i++) { + logger.info("VxFMetadata " + vxfs.get(i).getName() + " with VxF id:" + + vxfs.get(i).getUuid() + " is loaded"); + } + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return vxfs; + } + + public List getVxFOnBoardedDescriptors() { + String ret = template.requestBody("activemq:queue:getVxFOnBoardedDescriptorListDataJson", "", String.class); + List vxfobds = null; + // Map object to Infrastructure + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + vxfobds = mapper.readValue(ret, new TypeReference>() { + }); + for (int i = 0; i < vxfobds.size(); i++) { + logger.info("VxFObdDescriptor " + vxfobds.get(i).getId() + " with Deploy id:" + + vxfobds.get(i).getDeployId() +','+ vxfobds.get(i).getDeployId() + " is loaded"); + } + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return vxfobds; + } + + public List getExperimentOnBoardDescriptors() { + String ret = template.requestBody("activemq:queue:getExperimentOnBoardDescriptorsDataJson", "", String.class); + List expobds = null; + // Map object to Infrastructure + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + expobds = mapper.readValue(ret, new TypeReference>() { + }); + for (int i = 0; i < expobds.size(); i++) { + logger.info("ExperimentObdDescriptor " + expobds.get(i).getId() + " with Deploy id:" + + expobds.get(i).getDeployId() +','+ expobds.get(i).getDeployId() + " is loaded"); + } + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return expobds; + } + + public List getExperiments() { + String ret = template.requestBody("activemq:queue:getExperiments", "", String.class); + List experiments = null; + // Map object to Infrastructure + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + experiments = mapper.readValue(ret, new TypeReference>() { + }); + for (int i = 0; i < experiments.size(); i++) { + logger.info("Experiment " + experiments.get(i).getName() + " with Experiment id:" + + experiments.get(i).getUuid() + " is loaded"); + } + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return experiments; + } + + public List getDeploymentsToInstantiate() { + String ret = template.requestBody("activemq:queue:getDeploymentsToInstantiate", "", String.class); + + List DeploymentDescriptorsToRun = null; + // Map object to Infrastructure + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + DeploymentDescriptorsToRun = mapper.readValue(ret, new TypeReference>() { + }); + // Foreach deployment + for (DeploymentDescriptor d : DeploymentDescriptorsToRun) { + // Launch the deployment + logger.info("The deployment with name " + d.getName() + " is going to be instantiated"); + } + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return DeploymentDescriptorsToRun; + } + + public List getDeploymentsToBeCompleted() { + String ret = template.requestBody("activemq:queue:getDeploymentsToBeCompleted", "", String.class); + + List DeploymentDescriptorsToComplete = null; + // Map object to DeploymentDescriptor + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + DeploymentDescriptorsToComplete = mapper.readValue(ret, new TypeReference>() { + }); + for (DeploymentDescriptor d : DeploymentDescriptorsToComplete) { + // Launch the deployment + logger.info("The deployment with name " + d.getName() + " is going to be Completed"); + } + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return DeploymentDescriptorsToComplete; + } + + public List getAllDeployments() { + String ret = template.requestBody("activemq:queue:getAllDeployments", "", String.class); + + List deploymentDescriptors = null; + // Map object to DeploymentDescriptor + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + deploymentDescriptors = mapper.readValue(ret, new TypeReference>() { + }); + for (DeploymentDescriptor d : deploymentDescriptors) { + // Launch the deployment + logger.info("The deployment with name " + d.getName() + " was found."); + } + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return deploymentDescriptors; + } + + public List getDeploymentsToBeDeleted() { + String ret = template.requestBody("activemq:queue:getDeploymentsToBeDeleted", "", String.class); + logger.info("Deployments to be deleted: " + ret); + List DeploymentDescriptorsToDelete = null; + // Map object to DeploymentDescriptor + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + DeploymentDescriptorsToDelete = mapper.readValue(ret, new TypeReference>() { + }); + for (DeploymentDescriptor d : DeploymentDescriptorsToDelete) { + // Launch the deployment + logger.info("The deployment with name " + d.getName() + " is going to be Deleted"); + } + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return DeploymentDescriptorsToDelete; + } + + /** + * @param d + * @return as json + * @throws JsonProcessingException + */ + public String getDeploymentEagerDataJson(DeploymentDescriptor d) throws JsonProcessingException { + + DeploymentDescriptor dd = this.getDeploymentByIdEager(d.getId()); + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new Hibernate5JakartaModule()); + String res = mapper.writeValueAsString(dd); + + return res; + } + + // Get the data from the portal api (database) + public DeploymentDescriptor getDeploymentByIdEager(long Id) { + String ret = template.requestBody("activemq:queue:getDeploymentByIdEager", Id, String.class); + logger.debug("Message Received from AMQ on activemq:queue:getDeploymentByIdEager("+Id+") call:" + ret); + DeploymentDescriptor dd = null; + // Map object to DeploymentDescriptor + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + // Here we need to deserialize the DTO and not DeploymentDescriptor object. + dd = mapper.readValue(ret, DeploymentDescriptor.class); + // Load the DeploymentDescriptor ExperimentMetadata + if (dd.getExperiment() != null) { + // Use the experiment id to load the NSD by the id and load the experiment. + dd.setExperiment(this.getNSDById(dd.getExperiment().getId())); + logger.info("getDeploymentByIdEager: The experiment of the deployment is " + dd.getExperiment().getId()); + } + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return dd; + } + + // Get the data from the portal api (database) + public DeploymentDescriptor getDeploymentByInstanceIdEager(String Id) { + String ret = template.requestBody("activemq:queue:getDeploymentByInstanceIdEager", Id, String.class); + + logger.debug("Message Received from AMQ:" + ret); + DeploymentDescriptor dd = null; + // Map object to DeploymentDescriptor + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + dd = mapper.readValue(ret, DeploymentDescriptor.class); + if (dd.getExperiment() != null) { + //dd.setExperiment(this.getExperimentById(dd.getExperiment().getId())); + dd.setExperiment(this.getNSDById(dd.getExperiment().getId())); + logger.info("getDeploymentByInstanceIdEager: The experiment of the deployment is " + dd.getExperiment().toString()); + } + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return dd; + } + + public VxFMetadata getVxFById(long id) { + logger.info("Trying to get the VxF with id: " + id); + String ret = template.requestBody("activemq:queue:getVxFByID", id, String.class); + logger.debug("Message Received from AMQ:" + ret); + VxFMetadata vxfm = null; + // Map object to VxFMetadata + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + vxfm = mapper.readValue(ret, VxFMetadata.class); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return vxfm; + } + + public VxFMetadata getVxFByUUid(String UUid) + { + String ret = template.requestBody("activemq:queue:getVxFByUUIDDataJson", UUid, String.class); + logger.debug("Message Received from AMQ:" + ret); + VxFMetadata vxfm = null; + // Map object to VxFMetadata + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + vxfm = mapper.readValue(ret, VxFMetadata.class); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return vxfm; + } + + public VxFMetadata getVxFByName(String name) { + String ret = template.requestBody("activemq:queue:getVxFByName", name, String.class); + logger.debug("Message Received from AMQ:" + ret); + VxFMetadata vxfm = null; + // Map object to VxFMetadata + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + vxfm = mapper.readValue(ret, VxFMetadata.class); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return vxfm; + } + + public ExperimentMetadata getNSDById(long id) { + String ret = template.requestBody("activemq:queue:getNSDByID", id, String.class); + logger.debug("Message Received from AMQ on activemq:queue:getNSDByID call for id="+id+" :" + ret); + ExperimentMetadata expm = null; + // Map object to ExperimentMetadata + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + expm = mapper.readValue(ret, ExperimentMetadata.class); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return expm; + } + + // Duplicate of getNSDById + //private ExperimentMetadata getExperimentById(long id) { + // String ret = template.requestBody("activemq:queue:getNSDByID", id, String.class); + // logger.debug("Message Received from AMQ:" + ret); + // ExperimentMetadata em = null; + // // Map object to ExperimentMetadata + // try { + // ObjectMapper mapper = new ObjectMapper(); + // logger.debug("From ActiveMQ:" + ret.toString()); + // em = mapper.readValue(ret, ExperimentMetadata.class); + // } catch (JsonParseException e) { + // // TODO Auto-generated catch block + // e.printStackTrace(); + // logger.error(e.getMessage()); + // } catch (JsonMappingException e1) { + // // TODO Auto-generated catch block + // e1.printStackTrace(); + // logger.error(e1.getMessage()); + // } catch (IOException e11) { + // // TODO Auto-generated catch block + // e11.printStackTrace(); + // logger.error(e11.getMessage()); + // } + // return em; + //} + + public String getVxFOnBoardedDescriptorByVxFAndMP(String id, long mp) + { + String message = id+"##"+mp; + logger.debug("getVxFOnBoardedDescriptorByVxFAndMP:Message Sent to AMQ:" + message); + String ret = template.requestBody("activemq:queue:getVxFOnBoardedDescriptorByVxFAndMP", message, String.class); + logger.debug("Message Received from AMQ:" + ret); + logger.debug("From ActiveMQ:" + ret.toString()); + return ret.toString(); + } + + private VxFOnBoardedDescriptor getVxFOnBoardedDescriptorById(long id) { + String ret = template.requestBody("activemq:queue:getVxFOBDByID", id, String.class); + logger.debug("Message Received from AMQ:" + ret); + VxFOnBoardedDescriptor vxfobd = null; + // Map object to VxFOnBoardedDescriptor + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + vxfobd = mapper.readValue(ret, VxFOnBoardedDescriptor.class); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return vxfobd; + } + + public VxFOnBoardedDescriptor updateVxFOnBoardedDescriptor(VxFOnBoardedDescriptor vxfobd2send) { + // Serialize the received object + ObjectMapper mapper = new ObjectMapper(); + // Registering Hibernate4Module to support lazy objects + // this will fetch all lazy objects of VxF before marshaling + // mapper.registerModule(new Hibernate5Module()); + String vxfobd_serialized = null; + try { + vxfobd_serialized = mapper.writeValueAsString(vxfobd2send); + } catch (JsonProcessingException e2) { + // TODO Auto-generated catch block + logger.error(e2.getMessage()); + } + logger.debug("Sending Message " + vxfobd_serialized + " to updateVxFOnBoardedDescriptor from AMQ:"); + // Send it to activemq endpoint + String ret = template.requestBody("activemq:queue:updateVxFOnBoardedDescriptor", vxfobd_serialized, + String.class); + logger.debug("Message Received for updateVxFOnBoardedDescriptor from AMQ:" + ret); + + // Get the response and Map object to ExperimentMetadata + VxFOnBoardedDescriptor vxfd = null; + try { + // Map object to VxFOnBoardedDescriptor + mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + vxfd = mapper.readValue(ret, VxFOnBoardedDescriptor.class); + // vxfd.setExperiment(this.getExperimentById(vxfd.getExperiment().getId())); + // logger.info("The experiment of the deployment is + // "+vxfd.getExperiment().toString()); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + } + return vxfd; + } + + public Infrastructure addInfrastructure(Infrastructure infrastructure2send) { + // Serialize the received object + ObjectMapper mapper = new ObjectMapper(); + // Registering Hibernate4Module to support lazy objects + // this will fetch all lazy objects of VxF before marshaling + // mapper.registerModule(new Hibernate5Module()); + String infrastructure_serialized = null; + try { + infrastructure_serialized = mapper.writeValueAsString(infrastructure2send); + } catch (JsonProcessingException e2) { + // TODO Auto-generated catch block + logger.error(e2.getMessage()); + } + logger.debug("Sending Message " + infrastructure_serialized + " to addInfrastructure from AMQ:"); + // Send it to activemq endpoint + String ret = template.requestBody("activemq:queue:addInfrastructure", infrastructure_serialized, String.class); + logger.debug("Message Received for addInstrastructure from AMQ:" + ret); + + // Get the response and Map object to ExperimentMetadata + Infrastructure infrastructure = null; + try { + // Map object to VxFOnBoardedDescriptor + mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + infrastructure = mapper.readValue(ret, Infrastructure.class); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + } + return infrastructure; + } + + public Infrastructure updateInfrastructure(Infrastructure infrastructure2send) { + // Serialize the received object + ObjectMapper mapper = new ObjectMapper(); + // Registering Hibernate4Module to support lazy objects + // this will fetch all lazy objects of VxF before marshaling + // mapper.registerModule(new Hibernate5Module()); + String infrastructure_serialized = null; + try { + infrastructure_serialized = mapper.writeValueAsString(infrastructure2send); + } catch (JsonProcessingException e2) { + // TODO Auto-generated catch block + logger.error(e2.getMessage()); + } + logger.debug("Sending Message " + infrastructure_serialized + " to updateInfrastructure from AMQ:"); + // Send it to activemq endpoint + String ret = template.requestBody("activemq:queue:updateInfrastructure", infrastructure_serialized, String.class); + logger.debug("Message Received for addInstrastructure from AMQ:" + ret); + + // Get the response and Map object to ExperimentMetadata + Infrastructure infrastructure = null; + try { + // Map object to VxFOnBoardedDescriptor + mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + infrastructure = mapper.readValue(ret, Infrastructure.class); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + } + return infrastructure; + } + + + public PortalUser getPortalUserByUsername(String username) { + + // Serialize the received object + ObjectMapper mapper = new ObjectMapper(); + + logger.debug("Sending Message " + username + " to getPortalUserByUsername from AMQ:"); + // Send it to activemq endpoint + String ret = template.requestBody("activemq:queue:getPortalUserByUsername", username, String.class); + logger.debug("Message Received for getPortalUserByUsername from AMQ:" + ret); + + PortalUser portaluser = null; + try { + // Map object to PortalUser + mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + portaluser = mapper.readValue(ret, PortalUser.class); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + } + return portaluser; + } + + public VxFMetadata addVxFMetadata(VxFMetadata vxfmetadata2send) { + // Serialize the received object + ObjectMapper mapper = new ObjectMapper(); + // Registering Hibernate4Module to support lazy objects + // this will fetch all lazy objects of VxF before marshaling + // mapper.registerModule(new Hibernate5Module()); + String vxfmetadata_serialized = null; + try { + vxfmetadata_serialized = mapper.writeValueAsString(vxfmetadata2send); + } catch (JsonProcessingException e2) { + // TODO Auto-generated catch block + logger.error(e2.getMessage()); + } + logger.debug("Sending Message " + vxfmetadata_serialized + " to addVxFMetadata from AMQ:"); + // Send it to activemq endpoint + String ret = template.requestBody("activemq:queue:addVxFMetadata", vxfmetadata_serialized, String.class); + logger.debug("Message Received for addVxFMetadata from AMQ:" + ret); + + // Get the response and Map object to ExperimentMetadata + VxFMetadata vxfmetadata = null; + try { + // Map object to VxFOnBoardedDescriptor + mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + vxfmetadata = mapper.readValue(ret, VxFMetadata.class); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + } + return vxfmetadata; + } + + public ExperimentMetadata addExperimentMetadata(ExperimentMetadata experimentmetadata2send) { + // Serialize the received object + ObjectMapper mapper = new ObjectMapper(); + // Registering Hibernate4Module to support lazy objects + // this will fetch all lazy objects of VxF before marshaling + // mapper.registerModule(new Hibernate5Module()); + String experimentmetadata_serialized = null; + try { + experimentmetadata_serialized = mapper.writeValueAsString(experimentmetadata2send); + } catch (JsonProcessingException e2) { + // TODO Auto-generated catch block + logger.error(e2.getMessage()); + } + logger.debug("Sending Message " + experimentmetadata_serialized + " to addExperimentMetadata from AMQ:"); + // Send it to activemq endpoint + String ret = template.requestBody("activemq:queue:addExperimentMetadata", experimentmetadata_serialized, String.class); + logger.debug("Message Received for addExperimentMetadata from AMQ:" + ret); + + // Get the response and Map object to ExperimentMetadata + ExperimentMetadata experimentmetadata = null; + try { + // Map object to VxFOnBoardedDescriptor + mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + experimentmetadata = mapper.readValue(ret, ExperimentMetadata.class); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + } + return experimentmetadata; + } + + public VxFOnBoardedDescriptor addVxFOnBoardedDescriptor(VxFOnBoardedDescriptor vxfonboardeddescriptor2send) { + // Serialize the received object + ObjectMapper mapper = new ObjectMapper(); + // Registering Hibernate4Module to support lazy objects + // this will fetch all lazy objects of VxF before marshaling + // mapper.registerModule(new Hibernate5Module()); + String vxfonboardeddescriptor_serialized = null; + try { + vxfonboardeddescriptor_serialized = mapper.writeValueAsString(vxfonboardeddescriptor2send); + } catch (JsonProcessingException e2) { + // TODO Auto-generated catch block + logger.error(e2.getMessage()); + } + logger.debug("Sending Message " + vxfonboardeddescriptor_serialized + " to addVxFOnBoardedDescriptor from AMQ:"); + // Send it to activemq endpoint + String ret = template.requestBody("activemq:queue:addVxFOnBoardedDescriptor", vxfonboardeddescriptor_serialized, String.class); + logger.debug("Message Received for addVxFOnBoardedDescriptor from AMQ:" + ret); + + // Get the response and Map object to ExperimentMetadata + VxFOnBoardedDescriptor vxfonboardeddescriptor = null; + try { + // Map object to VxFOnBoardedDescriptor + mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + vxfonboardeddescriptor = mapper.readValue(ret, VxFOnBoardedDescriptor.class); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + } + return vxfonboardeddescriptor; + } + + public ExperimentOnBoardDescriptor addExperimentOnBoardedDescriptor(ExperimentOnBoardDescriptor experimentonboardeddescriptor2send) { + // Serialize the received object + ObjectMapper mapper = new ObjectMapper(); + // Registering Hibernate4Module to support lazy objects + // this will fetch all lazy objects of VxF before marshaling + // mapper.registerModule(new Hibernate5Module()); + String experimentonboardeddescriptor_serialized = null; + try { + experimentonboardeddescriptor_serialized = mapper.writeValueAsString(experimentonboardeddescriptor2send); + } catch (JsonProcessingException e2) { + // TODO Auto-generated catch block + logger.error(e2.getMessage()); + } + logger.debug("Sending Message " + experimentonboardeddescriptor_serialized + " to addExperimentOnBoardDescriptor from AMQ:"); + // Send it to activemq endpoint + String ret = template.requestBody("activemq:queue:addExperimentOnBoardedDescriptor", experimentonboardeddescriptor_serialized, String.class); + logger.debug("Message Received for addExperimentOnBoardedDescriptor from AMQ:" + ret); + + // Get the response and Map object to ExperimentMetadata + ExperimentOnBoardDescriptor experimentonboardeddescriptor = null; + try { + // Map object to VxFOnBoardedDescriptor + mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + experimentonboardeddescriptor = mapper.readValue(ret, ExperimentOnBoardDescriptor.class); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + } + return experimentonboardeddescriptor; + } + + public ExperimentOnBoardDescriptor updateExperimentOnBoardDescriptor(ExperimentOnBoardDescriptor expobd2send) { + // Serialize the received object + ObjectMapper mapper = new ObjectMapper(); + // Registering Hibernate4Module to support lazy objects + // this will fetch all lazy objects of VxF before marshaling + // mapper.registerModule(new Hibernate5Module()); + String expobd_serialized = null; + try { + expobd_serialized = mapper.writeValueAsString(expobd2send); + } catch (JsonProcessingException e2) { + // TODO Auto-generated catch block + logger.error(e2.getMessage()); + } + logger.debug("Sending Message " + expobd_serialized + " to updateVxFOnBoardedDescriptor from AMQ:"); + // Send it to activemq endpoint + String ret = template.requestBody("activemq:queue:updateExperimentOnBoardDescriptor", expobd_serialized, + String.class); + logger.debug("Message Received for updateExperimentOnBoardDescriptor from AMQ:" + ret); + + // Get the response and Map object to ExperimentMetadata + ExperimentOnBoardDescriptor experimentobd = null; + try { + // Map object to VxFOnBoardedDescriptor + mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + experimentobd = mapper.readValue(ret, ExperimentOnBoardDescriptor.class); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + } + return experimentobd; + } + + // Update the data in the portal api (database) + public DeploymentDescriptor updateDeploymentDescriptor(DeploymentDescriptor dd2send) { + // Serialize the received object + ObjectMapper mapper = new ObjectMapper(); + // Registering Hibernate4Module to support lazy objects + // this will fetch all lazy objects of VxF before marshaling + // mapper.registerModule(new Hibernate5Module()); + String dd_serialized = null; + try { + dd_serialized = mapper.writeValueAsString(dd2send); + } catch (JsonProcessingException e2) { + // TODO Auto-generated catch block + logger.error(e2.getMessage()); + } + + // Send it to activemq endpoint + String ret = template.requestBody("activemq:queue:updateDeploymentDescriptor", dd_serialized, String.class); + logger.debug("Message Received from AMQ:" + ret); + DeploymentDescriptor dd = null; + // Get the response and Map object to ExperimentMetadata + try { + // Map object to DeploymentDescriptor + mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + dd = mapper.readValue(ret, DeploymentDescriptor.class); + //dd.setExperiment(this.getExperimentById(dd.getExperiment().getId())); + dd.setExperiment(this.getNSDById(dd.getExperiment().getId())); + logger.debug("updateDeploymentDescriptor: The experiment of the deployment is " + dd.getExperiment().getId()); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + } + return dd; + } + + public List getMANOproviders() { + String ret = template.requestBody("activemq:queue:getMANOProviders", "", String.class); + + List mps = null; + // Map object to MANOprovider + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + mps = mapper.readValue(ret, new TypeReference>() { + }); + for (int i = 0; i < mps.size(); i++) { + logger.info("Found EndPoint " + mps.get(i).getApiEndpoint()); + } + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return mps; + } + + public List getMANOprovidersForSync() { + String ret = template.requestBody("activemq:queue:getMANOProvidersForSync", "", String.class); + + List mps = null; + // Map object to MANOprovider + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + mps = mapper.readValue(ret, new TypeReference>() { + }); + for (int i = 0; i < mps.size(); i++) { + logger.info("Found EndPoint " + mps.get(i).getApiEndpoint()); + } + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error(e.getMessage()); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + logger.error(e1.getMessage()); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + logger.error(e11.getMessage()); + } + return mps; + } + + // Update the data from the portal api (database) + public MANOprovider getMANOproviderByID(long id) { + String ret = template.requestBody("activemq:queue:getMANOProviderByID", id, String.class); + // FluentProducerTemplate template = contxt.create + // .createFluentProducerTemplate().to("activemq:queue:getRunningInstantiatingAndTerminatingDeployments?multipleConsumers=true"); + + MANOprovider mp = null; + // Map object to MANOprovider + try { + ObjectMapper mapper = new ObjectMapper(); + logger.debug("From ActiveMQ:" + ret.toString()); + mp = mapper.readValue(ret, MANOprovider.class); + logger.info("The MANOprovider with name " + mp.getName() + " has endpoint " + mp.getApiEndpoint()); + } catch (JsonParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (JsonMappingException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IOException e11) { + // TODO Auto-generated catch block + e11.printStackTrace(); + } + return mp; + } + + public void deleteExperiment(DeploymentDescriptor deploymentdescriptorid) { + FluentProducerTemplate template = contxt.createFluentProducerTemplate() + .to("seda:nsd.deployment.delete?multipleConsumers=true"); + template.withBody(deploymentdescriptorid).asyncSend(); + } + + // seda:nsd.deployment + + public void deploymentInstantiationSucceded(DeploymentDescriptor deploymentdescriptorid) { + FluentProducerTemplate template = contxt.createFluentProducerTemplate() + .to("seda:nsd.deployment.instantiation.success?multipleConsumers=true"); + template.withBody(deploymentdescriptorid).asyncSend(); + } + + public void deploymentInstantiationFailed(DeploymentDescriptor deploymentdescriptorid) { + FluentProducerTemplate template = contxt.createFluentProducerTemplate() + .to("seda:nsd.deployment.instantiation.fail?multipleConsumers=true"); + template.withBody(deploymentdescriptorid).asyncSend(); + } + + public void deploymentTerminationSucceded(DeploymentDescriptor deploymentdescriptorid) { + FluentProducerTemplate template = contxt.createFluentProducerTemplate() + .to("seda:nsd.deployment.termination.success?multipleConsumers=true"); + template.withBody(deploymentdescriptorid).asyncSend(); + } + + public void deploymentTerminationFailed(DeploymentDescriptor deploymentdescriptorid) { + FluentProducerTemplate template = contxt.createFluentProducerTemplate() + .to("seda:nsd.deployment.termination.fail?multipleConsumers=true"); + template.withBody(deploymentdescriptorid).asyncSend(); + } + + // seda:nsd.instance + + public void terminateInstanceSucceded(DeploymentDescriptor deploymentdescriptorid) { + FluentProducerTemplate template = contxt.createFluentProducerTemplate() + .to("seda:nsd.instance.termination.success?multipleConsumers=true"); + template.withBody(deploymentdescriptorid).asyncSend(); + } + + public void terminateInstanceFailed(DeploymentDescriptor deploymentdescriptorid) { + FluentProducerTemplate template = contxt.createFluentProducerTemplate() + .to("seda:nsd.instance.termination.fail?multipleConsumers=true"); + template.withBody(deploymentdescriptorid).asyncSend(); + } + + public void deleteInstanceSucceded(DeploymentDescriptor deploymentdescriptorid) { + FluentProducerTemplate template = contxt.createFluentProducerTemplate() + .to("seda:nsd.instance.deletion.success?multipleConsumers=true"); + template.withBody(deploymentdescriptorid).asyncSend(); + } + + public void deleteInstanceFailed(DeploymentDescriptor deploymentdescriptorid) { + FluentProducerTemplate template = contxt.createFluentProducerTemplate() + .to("seda:nsd.instance.deletion.fail?multipleConsumers=true"); + template.withBody(deploymentdescriptorid).asyncSend(); + } + + /** + * Asynchronously sends to the routing bus + * (seda:vxf.onboard?multipleConsumers=true) to upload a new vxf + * + * @param deployment a {@link VxFMetadata} + */ +// public void onBoardVxFAdded(VxFOnBoardedDescriptor obd) { +// FluentProducerTemplate template = contxt.createFluentProducerTemplate().to("seda:vxf.onboard?multipleConsumers=true"); +// template.withBody( obd ).asyncSend(); +// } + + public void onBoardVxFFailed(VxFOnBoardedDescriptor vxfobds_final) { + FluentProducerTemplate template = contxt.createFluentProducerTemplate() + .to("seda:vxf.onboard.fail?multipleConsumers=true"); + template.withBody(vxfobds_final).asyncSend(); + } + + public void onBoardVxFSucceded(VxFOnBoardedDescriptor vxfobds_final) { + FluentProducerTemplate template = contxt.createFluentProducerTemplate() + .to("seda:vxf.onboard.success?multipleConsumers=true"); + template.withBody(vxfobds_final).asyncSend(); + } + + public void onBoardNSDFailed(ExperimentOnBoardDescriptor experimentobds_final) { + FluentProducerTemplate template = contxt.createFluentProducerTemplate() + .to("seda:nsd.onboard.fail?multipleConsumers=true"); + template.withBody(experimentobds_final).asyncSend(); + } + + public void onBoardNSDSucceded(ExperimentOnBoardDescriptor experimentobds_final) { + FluentProducerTemplate template = contxt.createFluentProducerTemplate() + .to("seda:nsd.onboard.success?multipleConsumers=true"); + template.withBody(experimentobds_final).asyncSend(); + } + + /** + * + * Compare previous last known action with the last one. We ignore any + * intermediate actions + * + * @param deployment_tmp + * @param previous + * @param current + * @return + */ + public String alertOnScaleOpsList(DeploymentDescriptor deployment_tmp, String previous, String current) { + + try { + + JSONObject prevObj = new JSONObject(previous); + + JSONArray array2 = new JSONArray(current); + JSONObject currentLastObj = array2.getJSONObject(array2.length() - 1); + + if (!prevObj.get("id").equals(currentLastObj.get("id"))) { + JSONObject obj2 = currentLastObj; + if ((obj2.get("lcmOperationType").equals("scale")) && (!obj2.get("operationState").equals("FAILED"))) { + + logger.debug( + "Sending An AlertCreate with details the body " + obj2.get("operationParams").toString()); + + try { + AlarmCreate a = new AlarmCreate(); + a.setPerceivedSeverity(PerceivedSeverityType.critical.name()); + a.setState(AlarmStateType.raised.name()); + a.setAckState("unacknowledged"); + a.setAlarmRaisedTime(OffsetDateTime.now(ZoneOffset.UTC).toString()); + a.setSourceSystemId(compname); + a.setAffectedService(new ArrayList<>()); + a.setAlarmType(AlarmType.qualityOfServiceAlarm.name()); + a.setIsRootCause(true); + a.setProbableCause(ProbableCauseType.thresholdCrossed.name()); + String scaletype = ""; + if (obj2.toString().contains("SCALE_IN")) { + scaletype = "SCALE_IN"; + } else { + scaletype = "SCALE_OUT"; + } + a.setAlarmDetails("DeploymentRequestID=" + deployment_tmp.getId() + ";" + "InstanceId=" + + deployment_tmp.getInstanceId() + ";" + "scaletype=" + scaletype); + Comment comment = new Comment(); + comment.setTime(OffsetDateTime.now(ZoneOffset.UTC)); + comment.setSystemId(compname); + + a.setSpecificProblem("action=" + scaletype); + + comment.setComment("Scale Operation " + scaletype + ". " + a.getAlarmDetails()); + a.addCommentItem(comment); + + String response = alarmsService.createAlarm(a); + + logger.debug("Message sent to AlertCreate response=" + response); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + return currentLastObj.toString(); + + } + } catch (JSONException e) { + logger.info("Crashed during alertOnScaleOpsList" + e.getMessage()); + } + return previous; + } + + + + /** + * @param deployment_tmp + * @return + */ + public String notifyOnLCMChanged(DeploymentDescriptor deployment_tmp) { + + + String body; + try { + body = getDeploymentEagerDataJson( deployment_tmp ); + logger.info("notifyOnLCMChanged create body = " + body); + Object response = template.requestBody( NFV_CATALOG_NS_LCMCHANGED, body); + return response.toString(); + } catch (IOException e) { + logger.error("Message failed notifyOnLCMChanged"); + e.printStackTrace(); + } + return null; + } + + static String toJsonString(Object object) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + return mapper.writeValueAsString(object); + } +} diff --git a/src/main/java/org/etsi/osl/mano/MANOController.java b/src/main/java/org/etsi/osl/mano/MANOController.java new file mode 100644 index 0000000..b1ba5c1 --- /dev/null +++ b/src/main/java/org/etsi/osl/mano/MANOController.java @@ -0,0 +1,2883 @@ +/*- + * ========================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 org.etsi.osl.mano; + +import java.io.IOException; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.etsi.osl.centrallog.client.*; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.nsd.Df; +import org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.nsd.df.VnfProfile; +import org.opendaylight.yang.gen.v1.urn.etsi.osm.yang.vnfd.rev170228.vnfd.catalog.Vnfd; +import org.springframework.context.annotation.Configuration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpStatusCodeException; + +import com.fasterxml.jackson.annotation.JsonInclude.Include; +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 com.jayway.jsonpath.JsonPath; + +import org.etsi.osl.model.CompositeExperimentOnBoardDescriptor; +import org.etsi.osl.model.CompositeVxFOnBoardDescriptor; +import org.etsi.osl.model.ConstituentVxF; +import org.etsi.osl.model.DeploymentDescriptor; +import org.etsi.osl.model.DeploymentDescriptorStatus; +import org.etsi.osl.model.DeploymentDescriptorVxFInstanceInfo; +import org.etsi.osl.model.ExperimentMetadata; +import org.etsi.osl.model.ExperimentOnBoardDescriptor; +import org.etsi.osl.model.Infrastructure; +import org.etsi.osl.model.InfrastructureStatus; +import org.etsi.osl.model.MANOprovider; +import org.etsi.osl.model.OnBoardingStatus; +import org.etsi.osl.model.PackagingFormat; +import org.etsi.osl.model.ScaleDescriptor; +import org.etsi.osl.model.VFImage; +import org.etsi.osl.model.ValidationStatus; +import org.etsi.osl.model.VxFMetadata; +import org.etsi.osl.model.VxFOnBoardedDescriptor; +import org.etsi.osl.sol005nbi.OSMClient; +import org.etsi.osl.sol005nbi.ΑNSActionRequestPayload; +import jakarta.transaction.Transactional; +import org.etsi.osl.sol005nbi.ANSScaleRequestPayload; +import OSM10Util.OSM10ArchiveExtractor.OSM10NSExtractor; +import OSM10Util.OSM10ArchiveExtractor.OSM10VNFDExtractor; +import OSM10Util.OSM10NSReq.OSM10NSRequirements; +import OSM10Util.OSM10VNFReq.OSM10VNFRequirements; + +/** + * @author ctranoris, ichatzis + * + */ + +@Configuration +public class MANOController { + + /** */ + private static final transient Log logger = LogFactory.getLog(MANOController.class.getName()); + @Autowired + private MANOClient aMANOClient; + + @Value("${spring.application.name}") + private String compname; + + @Autowired + private CentralLogger centralLogger; + + public void onBoardVxFToMANOProviderByFile() throws Exception { + + } + + /** + * onBoard a VNF to MANO Provider, as described by this descriptor + * + * @param vxfobds + * @throws Exception + */ + public void onBoardVxFToMANOProviderByOBD(VxFOnBoardedDescriptor vxfobd) throws Exception { + + vxfobd.setVxf(aMANOClient.getVxFById(vxfobd.getVxfid())); + // Update the status and update the vxfobd + vxfobd.setOnBoardingStatus(OnBoardingStatus.ONBOARDING); + // This is the Deployment ID for the portal + vxfobd.setDeployId(UUID.randomUUID().toString()); + centralLogger.log(CLevel.INFO, + "Onboarding status change of VxF " + vxfobd.getVxf().getName() + " to " + vxfobd.getOnBoardingStatus(), + compname); + logger.info( + "Onboarding status change of VxF " + vxfobd.getVxf().getName() + " to " + vxfobd.getOnBoardingStatus()); + // Set MANO Provider VxF ID + vxfobd.setVxfMANOProviderID(vxfobd.getVxf().getName()); + // Set onBoarding Date + vxfobd.setLastOnboarding(new Date()); + + VxFOnBoardedDescriptor vxfobds = aMANOClient.updateVxFOnBoardedDescriptor(vxfobd); + if (vxfobds == null) { + throw new Exception("Cannot load VxFOnBoardedDescriptor"); + } + // Reload the vxf for the updated object. + vxfobds.setVxf(aMANOClient.getVxFById(vxfobds.getVxfid())); + + String manoVersion = vxfobds.getObMANOprovider().getSupportedMANOplatform().getVersion(); + OSMClient osmClient = null; + try { + osmClient = OSMClientFactory.getOSMClient(manoVersion, vxfobds.getObMANOprovider().getApiEndpoint(), + vxfobds.getObMANOprovider().getUsername(), vxfobds.getObMANOprovider().getPassword(), + vxfobds.getObMANOprovider().getProject()); + // MANOStatus.setOsm5CommunicationStatusActive(null); + } catch (Exception e) { + logger.error("onBoardNSDFromMANOProvider, " + manoVersion + " fails authentication. Aborting action."); + centralLogger.log(CLevel.ERROR, + "onBoardNSDFromMANOProvider, " + manoVersion + " fails authentication. Aborting action.", compname); + + // MANOStatus.setOsm5CommunicationStatusFailed(" Aborting VxF OnBoarding + // action."); + // Set the reason of the failure + vxfobds.setFeedbackMessage(manoVersion + " communication failed. Aborting VxF OnBoarding action."); + vxfobds.setOnBoardingStatus(OnBoardingStatus.FAILED); + centralLogger.log(CLevel.INFO, "Onboarding status change of VxF " + vxfobds.getVxf().getName() + " to " + + vxfobds.getOnBoardingStatus(), compname); + logger.error("Onboarding status change of VxF " + vxfobds.getVxf().getName() + " to " + + vxfobds.getOnBoardingStatus()); + + // ?? This should change. Either by an activemq call or we should certify upon + // Onboarding success. + // Uncertify if it failed OnBoarding. + vxfobds.getVxf().setCertified(false); + VxFOnBoardedDescriptor vxfobds_final = aMANOClient.updateVxFOnBoardedDescriptor(vxfobds); + + // Send a message for OnBoarding Failure due to osm connection failure + aMANOClient.onBoardVxFFailed(vxfobds_final); + return; + } + + ResponseEntity response = null; + response = osmClient.createVNFDPackage(); + if (response == null || response.getStatusCode().is4xxClientError() + || response.getStatusCode().is5xxServerError()) { + logger.error("VNFD Package Creation failed."); + // Set status + vxfobds.setOnBoardingStatus(OnBoardingStatus.FAILED); + centralLogger.log(CLevel.INFO, "Onboarding status change of VxF " + vxfobds.getVxf().getName() + " to " + + vxfobds.getOnBoardingStatus(), compname); + // Set the reason of the failure + vxfobds.setFeedbackMessage(response.getBody().toString()); + // Uncertify if it failed OnBoarding. + vxfobds.getVxf().setCertified(false); + VxFOnBoardedDescriptor vxfobds_final = aMANOClient.updateVxFOnBoardedDescriptor(vxfobds); + // Send a message for OnBoarding Failure due to osm connection failure + aMANOClient.onBoardVxFFailed(vxfobds_final); + return; + } else { + JSONObject obj = new JSONObject(response.getBody()); + String vnfd_id = obj.getString("id"); + logger.info(response.getStatusCode() + " replied. The new VNFD Package id is :" + vnfd_id); + String pLocation = vxfobd.getVxf().getPackageLocation(); + logger.info("Package location to onboard is :" + pLocation); + response = osmClient.uploadVNFDPackageContent(vnfd_id, pLocation); + if (response == null || response.getStatusCode().is4xxClientError() + || response.getStatusCode().is5xxServerError()) { + logger.error("Upload of VNFD Package Content failed. Deleting VNFD Package."); + // Delete the package from the OSM + osmClient.deleteVNFDPackage(vnfd_id); + // Set status + vxfobds.setOnBoardingStatus(OnBoardingStatus.FAILED); + centralLogger.log(CLevel.INFO, "Onboarding status change of VxF " + vxfobds.getVxf().getName() + " to " + + vxfobds.getOnBoardingStatus(), compname); + // Set the reason of the failure + vxfobds.setFeedbackMessage(response.getBody().toString()); + // Uncertify if it failed OnBoarding. + vxfobds.getVxf().setCertified(false); + VxFOnBoardedDescriptor vxfobds_final = aMANOClient.updateVxFOnBoardedDescriptor(vxfobds); + aMANOClient.onBoardVxFFailed(vxfobds_final); + return; + } + + vxfobds.setOnBoardingStatus(OnBoardingStatus.ONBOARDED); + centralLogger.log(CLevel.INFO, "Onboarding status change of VxF " + vxfobds.getVxf().getName() + " to " + + vxfobds.getOnBoardingStatus(), compname); + + vxfobds.setFeedbackMessage("OnBoarding Succeeded"); + + // We select by design not to Certify upon OnBoarding but only on final version + // is determined. + // vxfobds.getVxf().setCertified(true); + + // The Deploy ID is set as the VNFD Package id in OSMANO4Provider + vxfobds.setDeployId(vnfd_id); + // What should be the vxf Name. Something like cirros_vnfd. + vxfobds.setVxfMANOProviderID(vxfobd.getVxf().getName()); + // Set Onboarding date + vxfobds.setLastOnboarding(new Date()); + // Save the changes to vxfobds + VxFOnBoardedDescriptor vxfobds_final = aMANOClient.updateVxFOnBoardedDescriptor(vxfobds); + aMANOClient.onBoardVxFSucceded(vxfobds_final); + + } + } + + public void onBoardVxFToMANOProviderByCompositeObj(CompositeVxFOnBoardDescriptor compositeobd) throws Exception { + + VxFOnBoardedDescriptor vxfobd = (VxFOnBoardedDescriptor) compositeobd.getObd(); + byte[] allBytes = compositeobd.getAllBytes(); + // Load the related VxFMetadata object + vxfobd.setVxf(aMANOClient.getVxFById(vxfobd.getVxfid())); + // Update the status and update the vxfobd + vxfobd.setOnBoardingStatus(OnBoardingStatus.ONBOARDING); + // This is the Deployment ID for the portal + vxfobd.setDeployId(UUID.randomUUID().toString()); + centralLogger.log(CLevel.INFO, + "Onboarding status change of VxF " + vxfobd.getVxf().getName() + " to " + vxfobd.getOnBoardingStatus(), + compname); + logger.info( + "Onboarding status change of VxF " + vxfobd.getVxf().getName() + " to " + vxfobd.getOnBoardingStatus()); + // Set MANO Provider VxF ID + vxfobd.setVxfMANOProviderID(vxfobd.getVxf().getName()); + // Set onBoarding Date + vxfobd.setLastOnboarding(new Date()); + + VxFOnBoardedDescriptor vxfobds = aMANOClient.updateVxFOnBoardedDescriptor(vxfobd); + if (vxfobds == null) { + throw new Exception("Cannot load VxFOnBoardedDescriptor"); + } + // Reload the vxf for the updated object. + vxfobds.setVxf(aMANOClient.getVxFById(vxfobds.getVxfid())); + + String manoVersion = vxfobds.getObMANOprovider().getSupportedMANOplatform().getVersion(); + OSMClient osmClient = null; + try { + logger.info("manoVersion: " + manoVersion); + osmClient = OSMClientFactory.getOSMClient(manoVersion, vxfobds.getObMANOprovider().getApiEndpoint(), + vxfobds.getObMANOprovider().getUsername(), vxfobds.getObMANOprovider().getPassword(), + vxfobds.getObMANOprovider().getProject()); + // MANOStatus.setOsm5CommunicationStatusActive(null); + if (osmClient == null) { + new Exception("Cannot create osmClient"); + } + } catch (Exception e) { + logger.error("onBoardNSDFromMANOProvider, " + manoVersion + " fails authentication. Aborting action."); + centralLogger.log(CLevel.ERROR, + "onBoardNSDFromMANOProvider, " + manoVersion + " fails authentication. Aborting action.", compname); + + // MANOStatus.setOsm5CommunicationStatusFailed(" Aborting VxF OnBoarding + // action."); + // Set the reason of the failure + vxfobds.setFeedbackMessage(manoVersion + " communication failed. Aborting VxF OnBoarding action."); + vxfobds.setOnBoardingStatus(OnBoardingStatus.FAILED); + centralLogger.log(CLevel.INFO, "Onboarding status change of VxF " + vxfobds.getVxf().getName() + " to " + + vxfobds.getOnBoardingStatus(), compname); + logger.error("Onboarding status change of VxF " + vxfobds.getVxf().getName() + " to " + + vxfobds.getOnBoardingStatus()); + + // ?? This should change. Either by an activemq call or we should certify upon + // Onboarding success. + // Uncertify if it failed OnBoarding. + vxfobds.getVxf().setCertified(false); + VxFOnBoardedDescriptor vxfobds_final = aMANOClient.updateVxFOnBoardedDescriptor(vxfobds); + + // Send a message for OnBoarding Failure due to osm connection failure + aMANOClient.onBoardVxFFailed(vxfobds_final); + return; + } + + ResponseEntity response = null; + response = osmClient.createVNFDPackage(); + if (response == null || response.getStatusCode().is4xxClientError() + || response.getStatusCode().is5xxServerError()) { + logger.error("VNFD Package Creation failed."); + // Set status + vxfobds.setOnBoardingStatus(OnBoardingStatus.FAILED); + centralLogger.log(CLevel.INFO, "Onboarding status change of VxF " + vxfobds.getVxf().getName() + " to " + + vxfobds.getOnBoardingStatus(), compname); + // Set the reason of the failure + vxfobds.setFeedbackMessage(response.getBody().toString()); + // Uncertify if it failed OnBoarding. + vxfobds.getVxf().setCertified(false); + VxFOnBoardedDescriptor vxfobds_final = aMANOClient.updateVxFOnBoardedDescriptor(vxfobds); + // Send a message for OnBoarding Failure due to osm connection failure + aMANOClient.onBoardVxFFailed(vxfobds_final); + return; + } else { + JSONObject obj = new JSONObject(response.getBody()); + String vnfd_id = obj.getString("id"); + logger.info(response.getStatusCode() + " replied. The new VNFD Package id is :" + vnfd_id); + response = osmClient.uploadVNFDPackageContent(vnfd_id, allBytes); + if (response == null || response.getStatusCode().is4xxClientError() + || response.getStatusCode().is5xxServerError()) { + logger.error("Upload of VNFD Package Content failed. Deleting VNFD Package."); + // Delete the package from the OSM + osmClient.deleteVNFDPackage(vnfd_id); + // Set status + vxfobds.setOnBoardingStatus(OnBoardingStatus.FAILED); + centralLogger.log(CLevel.INFO, "Onboarding status change of VxF " + vxfobds.getVxf().getName() + " to " + + vxfobds.getOnBoardingStatus(), compname); + // Set the reason of the failure + vxfobds.setFeedbackMessage(response.getBody().toString()); + // Uncertify if it failed OnBoarding. + vxfobds.getVxf().setCertified(false); + VxFOnBoardedDescriptor vxfobds_final = aMANOClient.updateVxFOnBoardedDescriptor(vxfobds); + aMANOClient.onBoardVxFFailed(vxfobds_final); + return; + } + + vxfobds.setOnBoardingStatus(OnBoardingStatus.ONBOARDED); + centralLogger.log(CLevel.INFO, "Onboarding status change of VxF " + vxfobds.getVxf().getName() + " to " + + vxfobds.getOnBoardingStatus(), compname); + + vxfobds.setFeedbackMessage("OnBoarding Succeeded"); + + // We select by design not to Certify upon OnBoarding but only on final version + // is determined. + // vxfobds.getVxf().setCertified(true); + + // The Deploy ID is set as the VNFD Package id in OSMANO4Provider + vxfobds.setDeployId(vnfd_id); + // What should be the vxf Name. Something like cirros_vnfd. + vxfobds.setVxfMANOProviderID(vxfobd.getVxf().getName()); + // Set Onboarding date + vxfobds.setLastOnboarding(new Date()); + // Save the changes to vxfobds + VxFOnBoardedDescriptor vxfobds_final = aMANOClient.updateVxFOnBoardedDescriptor(vxfobds); + aMANOClient.onBoardVxFSucceded(vxfobds_final); + } + } + + public void onBoardVxFToMANOProvider(VxFOnBoardedDescriptor vxfobd, byte[] allBytes) throws Exception { + + // Load the related VxFMetadata object + vxfobd.setVxf(aMANOClient.getVxFById(vxfobd.getVxfid())); + // Update the status and update the vxfobd + vxfobd.setOnBoardingStatus(OnBoardingStatus.ONBOARDING); + // This is the Deployment ID for the portal + vxfobd.setDeployId(UUID.randomUUID().toString()); + centralLogger.log(CLevel.INFO, + "Onboarding status change of VxF " + vxfobd.getVxf().getName() + " to " + vxfobd.getOnBoardingStatus(), + compname); + logger.info( + "Onboarding status change of VxF " + vxfobd.getVxf().getName() + " to " + vxfobd.getOnBoardingStatus()); + // Set MANO Provider VxF ID + vxfobd.setVxfMANOProviderID(vxfobd.getVxf().getName()); + // Set onBoarding Date + vxfobd.setLastOnboarding(new Date()); + + VxFOnBoardedDescriptor vxfobds = aMANOClient.updateVxFOnBoardedDescriptor(vxfobd); + if (vxfobds == null) { + throw new Exception("Cannot load VxFOnBoardedDescriptor"); + } + // Reload the vxf for the updated object. + vxfobds.setVxf(aMANOClient.getVxFById(vxfobds.getVxfid())); + + String manoVersion = vxfobds.getObMANOprovider().getSupportedMANOplatform().getVersion(); + OSMClient osmClient = null; + try { + osmClient = OSMClientFactory.getOSMClient(manoVersion, vxfobds.getObMANOprovider().getApiEndpoint(), + vxfobds.getObMANOprovider().getUsername(), vxfobds.getObMANOprovider().getPassword(), + vxfobds.getObMANOprovider().getProject()); + // MANOStatus.setOsm5CommunicationStatusActive(null); + } catch (Exception e) { + logger.error("onBoardNSDFromMANOProvider, " + manoVersion + " fails authentication. Aborting action."); + centralLogger.log(CLevel.ERROR, + "onBoardNSDFromMANOProvider, " + manoVersion + " fails authentication. Aborting action.", compname); + + // MANOStatus.setOsm5CommunicationStatusFailed(" Aborting VxF OnBoarding + // action."); + // Set the reason of the failure + vxfobds.setFeedbackMessage(manoVersion + " communication failed. Aborting VxF OnBoarding action."); + vxfobds.setOnBoardingStatus(OnBoardingStatus.FAILED); + centralLogger.log(CLevel.INFO, "Onboarding status change of VxF " + vxfobds.getVxf().getName() + " to " + + vxfobds.getOnBoardingStatus(), compname); + logger.error("Onboarding status change of VxF " + vxfobds.getVxf().getName() + " to " + + vxfobds.getOnBoardingStatus()); + + // ?? This should change. Either by an activemq call or we should certify upon + // Onboarding success. + // Uncertify if it failed OnBoarding. + vxfobds.getVxf().setCertified(false); + VxFOnBoardedDescriptor vxfobds_final = aMANOClient.updateVxFOnBoardedDescriptor(vxfobds); + + // Send a message for OnBoarding Failure due to osm connection failure + aMANOClient.onBoardVxFFailed(vxfobds_final); + return; + } + + ResponseEntity response = null; + response = osmClient.createVNFDPackage(); + if (response == null || response.getStatusCode().is4xxClientError() + || response.getStatusCode().is5xxServerError()) { + logger.error("VNFD Package Creation failed."); + // Set status + vxfobds.setOnBoardingStatus(OnBoardingStatus.FAILED); + centralLogger.log(CLevel.INFO, "Onboarding status change of VxF " + vxfobds.getVxf().getName() + " to " + + vxfobds.getOnBoardingStatus(), compname); + // Set the reason of the failure + vxfobds.setFeedbackMessage(response.getBody().toString()); + // Uncertify if it failed OnBoarding. + vxfobds.getVxf().setCertified(false); + VxFOnBoardedDescriptor vxfobds_final = aMANOClient.updateVxFOnBoardedDescriptor(vxfobds); + // Send a message for OnBoarding Failure due to osm connection failure + aMANOClient.onBoardVxFFailed(vxfobds_final); + return; + } else { + JSONObject obj = new JSONObject(response.getBody()); + String vnfd_id = obj.getString("id"); + logger.info(response.getStatusCode() + " replied. The new VNFD Package id is :" + vnfd_id); + response = osmClient.uploadVNFDPackageContent(vnfd_id, allBytes); + if (response == null || response.getStatusCode().is4xxClientError() + || response.getStatusCode().is5xxServerError()) { + logger.error("Upload of VNFD Package Content failed. Deleting VNFD Package."); + // Delete the package from the OSM + osmClient.deleteVNFDPackage(vnfd_id); + // Set status + vxfobds.setOnBoardingStatus(OnBoardingStatus.FAILED); + centralLogger.log(CLevel.INFO, "Onboarding status change of VxF " + vxfobds.getVxf().getName() + " to " + + vxfobds.getOnBoardingStatus(), compname); + // Set the reason of the failure + vxfobds.setFeedbackMessage(response.getBody().toString()); + // Uncertify if it failed OnBoarding. + vxfobds.getVxf().setCertified(false); + VxFOnBoardedDescriptor vxfobds_final = aMANOClient.updateVxFOnBoardedDescriptor(vxfobds); + aMANOClient.onBoardVxFFailed(vxfobds_final); + return; + } + + vxfobds.setOnBoardingStatus(OnBoardingStatus.ONBOARDED); + centralLogger.log(CLevel.INFO, "Onboarding status change of VxF " + vxfobds.getVxf().getName() + " to " + + vxfobds.getOnBoardingStatus(), compname); + + vxfobds.setFeedbackMessage("OnBoarding Succeeded"); + + // We select by design not to Certify upon OnBoarding but only on final version + // is determined. + // vxfobds.getVxf().setCertified(true); + + // The Deploy ID is set as the VNFD Package id in OSMANO4Provider + vxfobds.setDeployId(vnfd_id); + // What should be the vxf Name. Something like cirros_vnfd. + vxfobds.setVxfMANOProviderID(vxfobd.getVxf().getName()); + // Set Onboarding date + vxfobds.setLastOnboarding(new Date()); + // Save the changes to vxfobds + VxFOnBoardedDescriptor vxfobds_final = aMANOClient.updateVxFOnBoardedDescriptor(vxfobds); + aMANOClient.onBoardVxFSucceded(vxfobds_final); + } + } + + /** + * offBoard a VNF to MANO Provider, as described by this descriptor + * + * @param c + */ + public ResponseEntity offBoardVxFFromMANOProvider(VxFOnBoardedDescriptor obd) + throws HttpClientErrorException { + // TODO Auto-generated method stub + ResponseEntity response = null; + String vnfd_id = obd.getDeployId(); + String manoVersion = obd.getObMANOprovider().getSupportedMANOplatform().getVersion(); + OSMClient osmClient = null; + try { + osmClient = OSMClientFactory.getOSMClient(manoVersion, obd.getObMANOprovider().getApiEndpoint(), + obd.getObMANOprovider().getUsername(), obd.getObMANOprovider().getPassword(), + obd.getObMANOprovider().getProject()); + // MANOStatus.setOsm5CommunicationStatusActive(null); + } catch (HttpStatusCodeException e) { + logger.error("offBoardVxFFromMANOProvider, " + manoVersion + " fails authentication. Aborting action."); + centralLogger.log(CLevel.ERROR, + "offBoardVxFFromMANOProvider, OSM5 fails authentication. Aborting VxF offboarding action.", + compname); + // MANOStatus.setOsm5CommunicationStatusFailed(" Aborting VxF offboarding + // action."); + return ResponseEntity.status(e.getRawStatusCode()).headers(e.getResponseHeaders()) + .body(e.getResponseBodyAsString()); + } + + response = osmClient.deleteVNFDPackage(vnfd_id); + if (obd.getObMANOprovider().getSupportedMANOplatform().getVersion().equals("OSMvTWO")) { + response = new ResponseEntity<>("Not implemented for OSMvTWO", HttpStatus.CREATED); + } + return response; + } + + public void onBoardNSDToMANOProviderByFile() throws Exception { + + } + + public void onBoardNSDToMANOProviderByCompositeObj(CompositeExperimentOnBoardDescriptor compexpobd) + throws Exception { + + ExperimentOnBoardDescriptor uexpobd = compexpobd.getObd(); + byte[] allBytes = compexpobd.getAllBytes(); + + ExperimentMetadata em = uexpobd.getExperiment(); + // if (em == null) { + em = (ExperimentMetadata) aMANOClient.getNSDById(uexpobd.getExperimentid()); + // } + uexpobd.setExperiment(em); + uexpobd.setOnBoardingStatus(OnBoardingStatus.ONBOARDING); + + // This is the Deployment ID for the portal + uexpobd.setDeployId(UUID.randomUUID().toString()); + centralLogger.log(CLevel.INFO, "Onboarding status change of Experiment " + uexpobd.getExperiment().getName() + + " to " + uexpobd.getOnBoardingStatus(), compname); + logger.info("Onboarding status change of Experiment " + uexpobd.getExperiment().getName() + " to " + + uexpobd.getOnBoardingStatus()); + + // uexpobd.setVxfMANOProviderID(em.getName()); // Possible Error. This probably + // needs to be + uexpobd.setExperimentMANOProviderID(em.getName()); + uexpobd.setLastOnboarding(new Date()); + + ExperimentOnBoardDescriptor uexpobds = aMANOClient.updateExperimentOnBoardDescriptor(uexpobd); + if (uexpobds == null) { + throw new Exception("Cannot load NSDOnBoardedDescriptor"); + } + + em = uexpobds.getExperiment(); + if (em == null) { + em = (ExperimentMetadata) aMANOClient.getNSDById(uexpobd.getExperimentid()); + } + uexpobds.setExperiment(em); + uexpobds.setObMANOprovider(uexpobd.getObMANOprovider()); + String manoVersion = uexpobds.getObMANOprovider().getSupportedMANOplatform().getVersion(); + OSMClient osmClient = null; + try { + osmClient = OSMClientFactory.getOSMClient(manoVersion, uexpobds.getObMANOprovider().getApiEndpoint(), + uexpobds.getObMANOprovider().getUsername(), uexpobds.getObMANOprovider().getPassword(), + uexpobds.getObMANOprovider().getProject()); + // MANOStatus.setOsm5CommunicationStatusActive(null); + } catch (Exception e) { + logger.error("onBoardNSDFromMANOProvider, " + manoVersion + " fails authentication. Aborting action."); + centralLogger.log(CLevel.ERROR, "onBoardNSDFromMANOProvider, " + manoVersion + + " fails authentication. Aborting NSD Onboarding action.", compname); + logger.error("onBoardNSDFromMANOProvider, " + manoVersion + + " fails authentication. Aborting NSD Onboarding action."); + // MANOStatus.setOsm5CommunicationStatusFailed(" Aborting NSD Onboarding + // action."); + // Set the reason of the failure + uexpobds.setFeedbackMessage("OSM communication failed. Aborting NSD Onboarding action."); + uexpobds.setOnBoardingStatus(OnBoardingStatus.FAILED); + centralLogger.log(CLevel.ERROR, "Onboarding Status change of Experiment " + + uexpobds.getExperiment().getName() + " to " + uexpobds.getOnBoardingStatus(), compname); + logger.error("Onboarding Status change of Experiment " + uexpobds.getExperiment().getName() + " to " + + uexpobds.getOnBoardingStatus()); + // Set Valid to false if it fails OnBoarding + uexpobds.getExperiment().setValid(false); + aMANOClient.updateExperimentOnBoardDescriptor(uexpobds); + aMANOClient.onBoardNSDFailed(uexpobds); + return; + } + + ResponseEntity response = null; + response = osmClient.createNSDPackage(); + if (response == null || response.getStatusCode().is4xxClientError() + || response.getStatusCode().is5xxServerError()) { + logger.error("Creation of NSD Package Content failed. Deleting NSD Package."); + uexpobds.setOnBoardingStatus(OnBoardingStatus.FAILED); + centralLogger.log(CLevel.INFO, "Onboarding Status change of Experiment " + + uexpobds.getExperiment().getName() + " to " + uexpobds.getOnBoardingStatus(), compname); + // Set the reason of the failure + uexpobds.setFeedbackMessage(response.getBody().toString()); + // Set Valid to false if it fails OnBoarding + uexpobds.getExperiment().setValid(false); + aMANOClient.updateExperimentOnBoardDescriptor(uexpobds); + aMANOClient.onBoardNSDFailed(uexpobds); + return; + } else { + JSONObject obj = new JSONObject(response.getBody()); + String nsd_id = obj.getString("id"); + logger.info(response.getStatusCode() + " replied. The new NSD Package id is :" + nsd_id); + response = osmClient.uploadNSDPackageContent(nsd_id, allBytes); + if (response == null || response.getStatusCode().is4xxClientError() + || response.getStatusCode().is5xxServerError()) { + logger.error("Upload of NSD Package Content failed. Deleting NSD Package."); + osmClient.deleteNSDPackage(nsd_id); + uexpobds.setOnBoardingStatus(OnBoardingStatus.FAILED); + centralLogger.log(CLevel.INFO, "Onboarding Status change of Experiment " + + uexpobds.getExperiment().getName() + " to " + uexpobds.getOnBoardingStatus(), compname); + logger.error("Onboarding Status change of Experiment " + uexpobds.getExperiment().getName() + " to " + + uexpobds.getOnBoardingStatus()); + + if (response.getBody() != null) { + uexpobds.setFeedbackMessage(response.getBody().toString()); + } + logger.error("Onboarding Feedbacj Message of Experiment " + uexpobds.getExperiment().getName() + " is " + + uexpobds.getFeedbackMessage()); + // Set Valid to false if it fails OnBoarding + uexpobds.getExperiment().setValid(false); + aMANOClient.updateExperimentOnBoardDescriptor(uexpobds); + aMANOClient.onBoardNSDFailed(uexpobds); + return; + } else { + uexpobds.setOnBoardingStatus(OnBoardingStatus.ONBOARDED); + centralLogger.log(CLevel.INFO, "Onboarding Status change of Experiment " + + uexpobds.getExperiment().getName() + " to " + uexpobds.getOnBoardingStatus(), compname); + logger.info("Onboarding Status change of Experiment " + uexpobds.getExperiment().getName() + " to " + + uexpobds.getOnBoardingStatus()); + uexpobds.setFeedbackMessage("NSD Onboarded Successfully"); + // The Deploy ID is set as the VNFD Package id in OSMANO4Provider + uexpobds.setDeployId(nsd_id); + // What should be the NSD Name. Something like cirros_nsd. + uexpobds.setExperimentMANOProviderID(em.getName()); + // Set Onboarding date + uexpobds.setLastOnboarding(new Date()); + // We decide to set valid when we have the final version. Thus we comment this. + // uexpobds.getExperiment().setValid(true); + // Save the changes to vxfobds + aMANOClient.updateExperimentOnBoardDescriptor(uexpobds); + aMANOClient.onBoardNSDSucceded(uexpobds); + } + } + } + + public void onBoardNSDToMANOProvider(ExperimentOnBoardDescriptor uexpobd) throws Exception { + + ExperimentMetadata em = uexpobd.getExperiment(); + if (em == null) { + em = (ExperimentMetadata) aMANOClient.getNSDById(uexpobd.getExperimentid()); + } + uexpobd.setExperiment(em); + uexpobd.setOnBoardingStatus(OnBoardingStatus.ONBOARDING); + + // This is the Deployment ID for the portal + uexpobd.setDeployId(UUID.randomUUID().toString()); + centralLogger.log(CLevel.INFO, "Onboarding status change of Experiment " + uexpobd.getExperiment().getName() + + " to " + uexpobd.getOnBoardingStatus(), compname); + logger.info("Onboarding status change of Experiment " + uexpobd.getExperiment().getName() + " to " + + uexpobd.getOnBoardingStatus()); + + // uexpobd.setVxfMANOProviderID(em.getName()); // Possible Error. This probably + // needs to be + uexpobd.setExperimentMANOProviderID(em.getName()); + + uexpobd.setLastOnboarding(new Date()); + + ExperimentOnBoardDescriptor uexpobds = aMANOClient.updateExperimentOnBoardDescriptor(uexpobd); + if (uexpobds == null) { + throw new Exception("Cannot load NSDOnBoardedDescriptor"); + } + em = uexpobds.getExperiment(); + if (em == null) { + em = (ExperimentMetadata) aMANOClient.getNSDById(uexpobd.getExperimentid()); + } + uexpobds.setExperiment(em); + + String manoVersion = uexpobds.getObMANOprovider().getSupportedMANOplatform().getVersion(); + OSMClient osmClient = null; + try { + osmClient = OSMClientFactory.getOSMClient(manoVersion, uexpobd.getObMANOprovider().getApiEndpoint(), + uexpobd.getObMANOprovider().getUsername(), uexpobd.getObMANOprovider().getPassword(), + uexpobd.getObMANOprovider().getProject()); + // MANOStatus.setOsm5CommunicationStatusActive(null); + } catch (Exception e) { + logger.error("onBoardNSDFromMANOProvider, " + manoVersion + " fails authentication. Aborting action."); + centralLogger.log(CLevel.ERROR, "onBoardNSDFromMANOProvider, " + manoVersion + + " fails authentication. Aborting NSD Onboarding action.", compname); + logger.error("onBoardNSDFromMANOProvider, " + manoVersion + + " fails authentication. Aborting NSD Onboarding action."); + // MANOStatus.setOsm5CommunicationStatusFailed(" Aborting NSD Onboarding + // action."); + // Set the reason of the failure + uexpobds.setFeedbackMessage("OSM communication failed. Aborting NSD Onboarding action."); + uexpobds.setOnBoardingStatus(OnBoardingStatus.FAILED); + centralLogger.log(CLevel.ERROR, "Onboarding Status change of Experiment " + + uexpobds.getExperiment().getName() + " to " + uexpobds.getOnBoardingStatus(), compname); + logger.error("Onboarding Status change of Experiment " + uexpobds.getExperiment().getName() + " to " + + uexpobds.getOnBoardingStatus()); + // Set Valid to false if it fails OnBoarding + uexpobds.getExperiment().setValid(false); + aMANOClient.updateExperimentOnBoardDescriptor(uexpobds); + aMANOClient.onBoardNSDFailed(uexpobds); + return; + } + + ResponseEntity response = null; + response = osmClient.createNSDPackage(); + if (response == null || response.getStatusCode().is4xxClientError() + || response.getStatusCode().is5xxServerError()) { + logger.error("Creation of NSD Package Content failed. Deleting NSD Package."); + uexpobds.setOnBoardingStatus(OnBoardingStatus.FAILED); + centralLogger.log(CLevel.INFO, "Onboarding Status change of Experiment " + + uexpobds.getExperiment().getName() + " to " + uexpobds.getOnBoardingStatus(), compname); + // Set the reason of the failure + uexpobds.setFeedbackMessage(response.getBody().toString()); + // Set Valid to false if it fails OnBoarding + uexpobds.getExperiment().setValid(false); + aMANOClient.updateExperimentOnBoardDescriptor(uexpobds); + aMANOClient.onBoardNSDFailed(uexpobds); + return; + } else { + JSONObject obj = new JSONObject(response.getBody()); + String nsd_id = obj.getString("id"); + logger.info(response.getStatusCode() + " replied. The new NSD Package id is :" + nsd_id); + String pLocation = uexpobd.getExperiment().getPackageLocation(); + logger.info("Package location to onboard is :" + pLocation); + response = osmClient.uploadNSDPackageContent(nsd_id, pLocation); + if (response == null || response.getStatusCode().is4xxClientError() + || response.getStatusCode().is5xxServerError()) { + logger.error("Upload of NSD Package Content failed. Deleting NSD Package."); + osmClient.deleteNSDPackage(nsd_id); + uexpobds.setOnBoardingStatus(OnBoardingStatus.FAILED); + centralLogger.log(CLevel.INFO, "Onboarding Status change of Experiment " + + uexpobds.getExperiment().getName() + " to " + uexpobds.getOnBoardingStatus(), compname); + logger.error("Onboarding Status change of Experiment " + uexpobds.getExperiment().getName() + " to " + + uexpobds.getOnBoardingStatus()); + uexpobds.setFeedbackMessage(response.getBody().toString()); + logger.error("Onboarding Feedbacj Message of Experiment " + uexpobds.getExperiment().getName() + " is " + + uexpobds.getFeedbackMessage()); + // Set Valid to false if it fails OnBoarding + uexpobds.getExperiment().setValid(false); + aMANOClient.updateExperimentOnBoardDescriptor(uexpobds); + aMANOClient.onBoardNSDFailed(uexpobds); + return; + } else { + uexpobds.setOnBoardingStatus(OnBoardingStatus.ONBOARDED); + centralLogger.log(CLevel.INFO, "Onboarding Status change of Experiment " + + uexpobds.getExperiment().getName() + " to " + uexpobds.getOnBoardingStatus(), compname); + logger.info("Onboarding Status change of Experiment " + uexpobds.getExperiment().getName() + " to " + + uexpobds.getOnBoardingStatus()); + uexpobds.setFeedbackMessage("NSD Onboarded Successfully"); + // The Deploy ID is set as the VNFD Package id in OSMANO4Provider + uexpobds.setDeployId(nsd_id); + // What should be the NSD Name. Something like cirros_nsd. + uexpobds.setExperimentMANOProviderID(em.getName()); + // Set Onboarding date + uexpobds.setLastOnboarding(new Date()); + // We decide to set valid when we have the final version. Thus we comment this. + // uexpobds.getExperiment().setValid(true); + // Save the changes to vxfobds + aMANOClient.updateExperimentOnBoardDescriptor(uexpobds); + aMANOClient.onBoardNSDSucceded(uexpobds); + } + } + } + + public ResponseEntity offBoardNSDFromMANOProvider(ExperimentOnBoardDescriptor uexpobd) { + // TODO Auto-generated method stub + ResponseEntity response = null; + + String nsd_id = uexpobd.getDeployId(); + String manoVersion = uexpobd.getObMANOprovider().getSupportedMANOplatform().getVersion(); + OSMClient osmClient = null; + try { + osmClient = OSMClientFactory.getOSMClient(manoVersion, uexpobd.getObMANOprovider().getApiEndpoint(), + uexpobd.getObMANOprovider().getUsername(), uexpobd.getObMANOprovider().getPassword(), + uexpobd.getObMANOprovider().getProject()); + // MANOStatus.setOsm5CommunicationStatusActive(null); + } catch (HttpStatusCodeException e) { + logger.error("offBoardNSDFromMANOProvider, " + manoVersion + " fails authentication. Aborting action."); + centralLogger.log(CLevel.ERROR, + "offBoardNSDFromMANOProvider, " + manoVersion + " fails authentication. Aborting action.", + compname); + // MANOStatus.setOsm5CommunicationStatusFailed(" Aborting NSD offboarding + // action."); + return ResponseEntity.status(e.getRawStatusCode()).headers(e.getResponseHeaders()) + .body(e.getResponseBodyAsString()); + } + response = osmClient.deleteNSDPackage(nsd_id); + logger.info("offBoardNSDFromMANOProvider, response sent back tou ActiveMQ: " + response.toString()); + return response; + } + + 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 DeploymentDescriptorsToComplete = aMANOClient.getDeploymentsToBeCompleted(); + // For each deployment + for (DeploymentDescriptor deployment_descriptor_tmp : DeploymentDescriptorsToComplete) { + logger.info("Deployment with id" + deployment_descriptor_tmp.getName() + " with status " + + deployment_descriptor_tmp.getStatus() + " is going to be terminated"); + + // Terminate the deployment + this.terminateNSFromMANOProvider(deployment_descriptor_tmp.getId()); + } + } + + public void checkAndDeleteTerminatedOrFailedDeployments() { + logger.info("Check and Delete Terminated and Failed Deployments"); + List DeploymentDescriptorsToDelete = aMANOClient.getDeploymentsToBeDeleted(); + for (DeploymentDescriptor d : DeploymentDescriptorsToDelete) { + // Launch the deployment + logger.info("Send to bus control to delete: " + d.getId()); + this.deleteNSFromMANOProvider(d.getId()); + } + } + + 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 DeploymentDescriptorsToRun = aMANOClient.getDeploymentsToInstantiate(); + // Foreach deployment found, start the instantiation + for (DeploymentDescriptor d : DeploymentDescriptorsToRun) { + // Launch the deployment + logger.info("Send to bus control to deploy: " + d.getId()); + this.deployNSDToMANOProvider(d.getId()); + } + } + + public void getScaleAlertMessageBody(String Body) + { + logger.info("Scale Alert Body "+Body); + } + + @Transactional + public void checkAndUpdateMANOProvidersResources() { + + // Get MANO Providers + List mps = aMANOClient.getMANOprovidersForSync(); + // For each MANO Provider + for (int i = 0; i < mps.size(); i++) + { + //****************************************************************** + MANOprovider mp = aMANOClient.getMANOproviderByID(mps.get(i).getId()); + String manoVersion = mp.getSupportedMANOplatform().getVersion(); + OSMClient osmClient = null; + + try { + osmClient = OSMClientFactory.getOSMClient(manoVersion, mp.getApiEndpoint(), + mp.getUsername(), mp.getPassword(), mp.getProject()); + } catch (Exception e) { + logger.error(manoVersion + " fails authentication. Details: " + mp.getName() + " " + mp.getApiEndpoint() ); + centralLogger.log(CLevel.ERROR, manoVersion + " fails authentication. Details: " + mp.getName() + " " + mp.getApiEndpoint() , compname); + continue; + } + synchronizeVIMs(osmClient, mp); + synchronizeVNFDs(osmClient, mp); + synchronizeNSDs(osmClient, mp); + //synchronizeDeployments(osmClient, mp); + } + + } + + private void synchronizeVIMs(OSMClient osmClient, MANOprovider mp) + { + logger.info("Synchronize VIMs for MANOProvider "+mp.getName()); + //****************************************************************** + // Get available VIMs from the portal's Database + List infrastructures = aMANOClient.getInfrastructures(); + for(int j = 0; j < infrastructures.size(); j++) + { + logger.debug("Found VIM with id:"+infrastructures.get(j).toJSON()); + //centralLogger.log( CLevel.INFO, "Synchronize VIM with id:"+infrastructures.get(j).getVIMid() , compname); + } + //****************************************************************** + // Get VIMs from OSM MANO. + ResponseEntity vims_list_entity = osmClient.getVIMs(); + VIMCreateRequestPayload[] vim_osm_array; + if (vims_list_entity == null || vims_list_entity.getStatusCode().is4xxClientError() + || vims_list_entity.getStatusCode().is5xxServerError()) { + logger.error("VIMs List Get Request failed. Status Code:" + vims_list_entity.getStatusCode().toString() + + ", Payload:" + vims_list_entity.getBody().toString()); + } else { + logger.debug("Got VIM list for MANOProvider "+mp.getName()+": "+vims_list_entity.getBody()); + ObjectMapper mapper = new ObjectMapper(); + try { + vim_osm_array = (VIMCreateRequestPayload[]) mapper.readValue(vims_list_entity.getBody(), VIMCreateRequestPayload[].class); + for(VIMCreateRequestPayload vim : vim_osm_array) + { + // Εδώ θα συγκρίνουμε αυτό που λάβαμε απο τη βάση με αυτό που λάβαμε απο το osm και θα το ανανεώσουμε στη βάση. + logger.debug("VIM to JSON:"+vim.toJSON()); + boolean exists_in_db = false; + for(Infrastructure dbvim : infrastructures) + { + if(dbvim.getVIMid().equals(vim.get_id())) + { + logger.info("VIM "+vim.get_id()+" already exists"); + exists_in_db = true; + } + } + if(exists_in_db == false) + { + //Map osm vim to db vim object + Infrastructure newInfrastructure = new Infrastructure(); + newInfrastructure.setVIMid(vim.get_id()); + newInfrastructure.setName(vim.getName()); + newInfrastructure.setOrganization(vim.getName()); + newInfrastructure.setDatacentername(vim.getDatacenter()); + newInfrastructure.setMp(mp); + newInfrastructure.setDatacentername(mp.getName()); + newInfrastructure.setInfrastructureStatus(InfrastructureStatus.OSM_PRESENT); + newInfrastructure.setDateCreated(new Date()); + //newInfrastructure.setMANOProvider(mps.get(i).getId()); + //Add object to db + aMANOClient.addInfrastructure(newInfrastructure); + logger.info("VIM "+vim.get_id()+" added"); + } + } + + } catch (IllegalStateException | IOException e) { + logger.error(e.getMessage()); + e.printStackTrace(); + return; + } + + // Check for orphaned + for(Infrastructure infrastructure : infrastructures) + { + boolean exists_in_osm = false; + // For each object + for(VIMCreateRequestPayload vim : vim_osm_array) + { + // Εδώ θα συγκρίνουμε αυτό που λάβαμε απο τη βάση με αυτό που λάβαμε απο το osm και θα το ανανεώσουμε στη βάση. + logger.debug("VIM to JSON:"+vim.toJSON()); + if(infrastructure.getVIMid().equals(vim.get_id())) + { + logger.info("VIM "+vim.get_id()+" still exists in osm"); + exists_in_osm = true; + infrastructure.setInfrastructureStatus(InfrastructureStatus.OSM_PRESENT); + infrastructure = aMANOClient.updateInfrastructure(infrastructure); + if(infrastructure != null) + { + logger.info("synchronizeVIMs: Infrastructure " + infrastructure.getVIMid() + " updated Infrastructure status to OSM_PRESENT"); + } + else + { + logger.warn("synchronizeVIMs: Infrastructure " + infrastructure.getVIMid() + " update to Infrastructure status to OSM_PRESENT FAILED"); + } + } + } + try + { + if(exists_in_osm == false && infrastructure.getMp().getName().equals(mp.getName()) && infrastructure.getMp().getProject().equals(mp.getProject())) + { + logger.debug("VIM with id "+ infrastructure.getVIMid()+" does not exist and MP name '"+infrastructure.getMp().getName()+"'='"+mp.getName()+"' and project '"+infrastructure.getMp().getProject()+"'='"+mp.getProject()+"'"); + exists_in_osm = false; + infrastructure.setInfrastructureStatus(InfrastructureStatus.OSM_MISSING); + infrastructure = aMANOClient.updateInfrastructure(infrastructure); + if(infrastructure != null) + { + logger.info("synchronizeVIMs: Infrastructure " + infrastructure.getVIMid() + " updated Infrastructure status to OSM_MISSING"); + } + else + { + logger.warn("synchronizeVIMs: Infrastructure " + infrastructure.getVIMid() + " update to Infrastructure status to OSM_MISSING FAILED"); + } + } + } + catch(Exception e) + { + logger.error("Possible missing MP for VIM with id "+infrastructure.getVIMid()+". VIM OSM Presence check failed and skipped.");; + } + } + + } + } + + private void synchronizeVNFDs(OSMClient osmClient, MANOprovider mp) + { + //****************************************************************** + // Get ExperimentMetadata available from the portal's Database + //List vxfMetadatas = aMANOClient.getVnfds(); + List vxFOnBoardedDescriptors = aMANOClient.getVxFOnBoardedDescriptors(); + + //****************************************************************** + // Get VNFDs from OSM MANO. + ResponseEntity vnfds_list_entity = osmClient.getVNFDescriptorsList(); + if (vnfds_list_entity == null || vnfds_list_entity.getStatusCode().is4xxClientError() + || vnfds_list_entity.getStatusCode().is5xxServerError()) { + logger.error("VNFDs List Get Request failed. Status Code:" + vnfds_list_entity.getStatusCode().toString() + + ", Payload:" + vnfds_list_entity.getBody().toString()); + } else { + logger.debug("Got VNFD list "+vnfds_list_entity.getBody()); + if(mp.getSupportedMANOplatform().getVersion().equals("OSMvTEN")) + { + synchronizeVNFDsOSM10(vxFOnBoardedDescriptors, vnfds_list_entity, mp); + } + if(mp.getSupportedMANOplatform().getVersion().equals("OSMvELEVEN")) + { + synchronizeVNFDsOSM11(vxFOnBoardedDescriptors, vnfds_list_entity, mp); + } + if(mp.getSupportedMANOplatform().getVersion().equals("OSMvTHIRTEEN")) + { + synchronizeVNFDsOSM13(vxFOnBoardedDescriptors, vnfds_list_entity, mp); + } + } + } + + + private void synchronizeVNFDsOSM10(List vxFOnBoardedDescriptors, ResponseEntity vnfds_list_entity, MANOprovider mp) + { + ObjectMapper mapper = new ObjectMapper(); + try { + // Parse the json list of objects + org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd[] vnfd_array = (org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd[]) mapper.readValue(vnfds_list_entity.getBody(), org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd[].class); + // For each object + for(org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd vnfd : vnfd_array) + { + String jsonInString=null; + ObjectMapper mapper2 = new ObjectMapper(); + mapper2.setSerializationInclusion(Include.NON_NULL); + try { + jsonInString = mapper2.writerWithDefaultPrettyPrinter().writeValueAsString(vnfd); + } catch (JsonProcessingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + // Compare db derived data with osm derived data and update the database. + logger.debug("VNFD to JSON:"+jsonInString); + logger.info("VNFD " + vnfd.getId() + " added"); + + // Get the mapped ExperimentMetadata object + VxFMetadata prod = mapOSM10VNFD2ProductFromJSON(vnfd); + try { + jsonInString = mapper2.writerWithDefaultPrettyPrinter().writeValueAsString(prod); + } catch (JsonProcessingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + logger.debug("Prod created:"+jsonInString); + + // Now that we have the product + // Check if the VxFMetadata uuid already exists in the database + + boolean exists_in_db = false; + for(VxFOnBoardedDescriptor dbvxfobd : vxFOnBoardedDescriptors) + { + if(dbvxfobd.getDeployId().equals(vnfd.getId())) + { + logger.info("VNFD " + vnfd.getId() + " already exists"); + exists_in_db = true; + } + } + if(exists_in_db == false) + { + logger.info("VNFD " + vnfd.getId() + " does not exist. Adding to db."); + exists_in_db = true; + //Map osm vim to db vim object + VxFMetadata newVxFMetadata = new VxFMetadata(); + newVxFMetadata.setUuid(vnfd.getId()); + // Combine the vnfd name with the OSM name. + newVxFMetadata.setName(vnfd.getProductName()); + newVxFMetadata.setValidationStatus(ValidationStatus.COMPLETED); + newVxFMetadata.setDateCreated(new Date()); + newVxFMetadata.setDateUpdated(new Date()); + newVxFMetadata.setShortDescription(vnfd.getProductName()+"@"+mp.getName()); + newVxFMetadata.setPackagingFormat(PackagingFormat.OSMvTEN); + //Get the manoServiceOwner to add it + newVxFMetadata.setOwner(aMANOClient.getPortalUserByUsername("manoService")); + + // Get VNF Requirements from the vnfd + OSM10VNFRequirements vnfreq = new OSM10VNFRequirements(vnfd); + // Store the requirements in HTML + newVxFMetadata.setDescriptorHTML(vnfreq.toHTML()); + // Store the YAML file + newVxFMetadata.setDescriptor(vnfds_list_entity.getBody()); + + //Add VxFMetadata object to db and get the generated object + newVxFMetadata = aMANOClient.addVxFMetadata(newVxFMetadata); + logger.info("VxF " + vnfd.getId() + " added with VxFMetadata id="+newVxFMetadata.getId()); + + //Create the OnboardedDescriptor + VxFOnBoardedDescriptor newVxFOnBoardedDescriptor = new VxFOnBoardedDescriptor(newVxFMetadata); + newVxFOnBoardedDescriptor.setDeployId(vnfd.getId()); + newVxFOnBoardedDescriptor.setFeedbackMessage("Automatically Retrieved from OSM"); + newVxFOnBoardedDescriptor.setLastOnboarding(new Date()); + newVxFOnBoardedDescriptor.setOnBoardingStatus(OnBoardingStatus.ONBOARDED); + newVxFOnBoardedDescriptor.setUuid(vnfd.getId()); + newVxFOnBoardedDescriptor.setVxfMANOProviderID(vnfd.getProductName()); + newVxFOnBoardedDescriptor.setObMANOprovider(mp); + newVxFOnBoardedDescriptor.setVxf(aMANOClient.getVxFById(newVxFMetadata.getId())); + //Add VxFOnBoardedDescriptor object to db and get the generated object + newVxFOnBoardedDescriptor=aMANOClient.addVxFOnBoardedDescriptor(newVxFOnBoardedDescriptor); + logger.info("VxFOnBoardedDescriptor " + newVxFOnBoardedDescriptor.getId() + " added"); + + } + } + // Check for orphaned + for(VxFOnBoardedDescriptor dbvxfobd : vxFOnBoardedDescriptors) + { + boolean exists_in_osm = false; + // For each object + for(org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd vnfd : vnfd_array) + { + if(dbvxfobd.getDeployId().equals(vnfd.getId())) + { + logger.info("VNFD " + vnfd.getId() + " exists in osm"); + exists_in_osm = true; + } + } + logger.debug(dbvxfobd.getDeployId()+" does not exist and MP name '"+dbvxfobd.getObMANOprovider().getName()+"'='"+mp.getName()+"' and project '"+dbvxfobd.getObMANOprovider().getProject()+"'='"+mp.getProject()+"'?"); + if(exists_in_osm == false && dbvxfobd.getObMANOprovider().getName().equals(mp.getName()) && dbvxfobd.getObMANOprovider().getProject().equals(mp.getProject())) + { + logger.debug(dbvxfobd.getDeployId()+" does not exist and MP name '"+dbvxfobd.getObMANOprovider().getName()+"'='"+mp.getName()+"' and project '"+dbvxfobd.getObMANOprovider().getProject()+"'='"+mp.getProject()+"'"); + dbvxfobd.setOnBoardingStatus(OnBoardingStatus.OSM_MISSING); + dbvxfobd = aMANOClient.updateVxFOnBoardedDescriptor(dbvxfobd); + logger.info("synchronizeVNFDsOSM10 : VxFOnBoardedDescriptor " + dbvxfobd.getId() + " updated OnboardingStatus to OSM_MISSING"); + } + } + } catch (IllegalStateException | IOException e) { + logger.error(e.getMessage()); + e.printStackTrace(); + } + } + + private void synchronizeVNFDsOSM11(List vxFOnBoardedDescriptors, ResponseEntity vnfds_list_entity, MANOprovider mp) + { + ObjectMapper mapper = new ObjectMapper(); + try { + // Parse the json list of objects + org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd[] vnfd_array = (org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd[]) mapper.readValue(vnfds_list_entity.getBody(), org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd[].class); + // For each object + for(org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd vnfd : vnfd_array) + { + String jsonInString=null; + ObjectMapper mapper2 = new ObjectMapper(); + mapper2.setSerializationInclusion(Include.NON_NULL); + try { + jsonInString = mapper2.writerWithDefaultPrettyPrinter().writeValueAsString(vnfd); + } catch (JsonProcessingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + // Compare db derived data with osm derived data and update the database. + logger.debug("VNFD to JSON:"+jsonInString); + logger.info("VNFD " + vnfd.getId() + " added"); + + // Get the mapped ExperimentMetadata object + VxFMetadata prod = mapOSM10VNFD2ProductFromJSON(vnfd); + try { + jsonInString = mapper2.writerWithDefaultPrettyPrinter().writeValueAsString(prod); + } catch (JsonProcessingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + logger.debug("Prod created:"+jsonInString); + + // Now that we have the product + // Check if the VxFMetadata uuid already exists in the database + + boolean exists_in_db = false; + for(VxFOnBoardedDescriptor dbvxfobd : vxFOnBoardedDescriptors) + { + if(dbvxfobd.getDeployId().equals(vnfd.getId())) + { + logger.info("VNFD " + vnfd.getId() + " already exists"); + exists_in_db = true; + } + } + if(exists_in_db == false) + { + logger.info("VNFD " + vnfd.getId() + " does not exist. Adding to db."); + exists_in_db = true; + //Map osm vim to db vim object + VxFMetadata newVxFMetadata = new VxFMetadata(); + newVxFMetadata.setUuid(vnfd.getId()); + // Combine the vnfd name with the OSM name. + newVxFMetadata.setName(vnfd.getProductName()); + newVxFMetadata.setValidationStatus(ValidationStatus.COMPLETED); + newVxFMetadata.setDateCreated(new Date()); + newVxFMetadata.setDateUpdated(new Date()); + newVxFMetadata.setShortDescription(vnfd.getProductName()+"@"+mp.getName()); + newVxFMetadata.setPackagingFormat(PackagingFormat.OSMvELEVEN); + //Get the manoServiceOwner to add it + newVxFMetadata.setOwner(aMANOClient.getPortalUserByUsername("manoService")); + + // Get VNF Requirements from the vnfd + OSM10VNFRequirements vnfreq = new OSM10VNFRequirements(vnfd); + // Store the requirements in HTML + newVxFMetadata.setDescriptorHTML(vnfreq.toHTML()); + // Store the YAML file + newVxFMetadata.setDescriptor(vnfds_list_entity.getBody()); + + //Add VxFMetadata object to db and get the generated object + newVxFMetadata = aMANOClient.addVxFMetadata(newVxFMetadata); + logger.info("VxF " + vnfd.getId() + " added with VxFMetadata id="+newVxFMetadata.getId()); + + //Create the OnboardedDescriptor + VxFOnBoardedDescriptor newVxFOnBoardedDescriptor = new VxFOnBoardedDescriptor(newVxFMetadata); + newVxFOnBoardedDescriptor.setDeployId(vnfd.getId()); + newVxFOnBoardedDescriptor.setFeedbackMessage("Automatically Retrieved from OSM"); + newVxFOnBoardedDescriptor.setLastOnboarding(new Date()); + newVxFOnBoardedDescriptor.setOnBoardingStatus(OnBoardingStatus.ONBOARDED); + newVxFOnBoardedDescriptor.setUuid(vnfd.getId()); + newVxFOnBoardedDescriptor.setVxfMANOProviderID(vnfd.getProductName()); + newVxFOnBoardedDescriptor.setObMANOprovider(mp); + newVxFOnBoardedDescriptor.setVxf(aMANOClient.getVxFById(newVxFMetadata.getId())); + //Add VxFOnBoardedDescriptor object to db and get the generated object + newVxFOnBoardedDescriptor=aMANOClient.addVxFOnBoardedDescriptor(newVxFOnBoardedDescriptor); + logger.info("VxFOnBoardedDescriptor " + newVxFOnBoardedDescriptor.getId() + " added"); + + } + } + // Check for orphaned + for(VxFOnBoardedDescriptor dbvxfobd : vxFOnBoardedDescriptors) + { + boolean exists_in_osm = false; + // For each object + for(org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd vnfd : vnfd_array) + { + if(dbvxfobd.getDeployId().equals(vnfd.getId())) + { + logger.info("VNFD " + vnfd.getId() + " exists in osm"); + exists_in_osm = true; + } + } + if(exists_in_osm == false && dbvxfobd.getObMANOprovider().getName().equals(mp.getName()) && dbvxfobd.getObMANOprovider().getProject().equals(mp.getProject())) + { + logger.debug(dbvxfobd.getDeployId()+" does not exist and MP name '"+dbvxfobd.getObMANOprovider().getName()+"'='"+mp.getName()+"' and project '"+dbvxfobd.getObMANOprovider().getProject()+"'='"+mp.getProject()+"'"); + dbvxfobd.setOnBoardingStatus(OnBoardingStatus.OSM_MISSING); + dbvxfobd = aMANOClient.updateVxFOnBoardedDescriptor(dbvxfobd); + logger.info("synchronizeVNFDsOSM11 : VxFOnBoardedDescriptor " + dbvxfobd.getId() + " updated OnboardingStatus to OSM_MISSING"); + } + } + } catch (IllegalStateException | IOException e) { + logger.error(e.getMessage()); + e.printStackTrace(); + } + } + + private void synchronizeVNFDsOSM13(List vxFOnBoardedDescriptors, ResponseEntity vnfds_list_entity, MANOprovider mp) + { + ObjectMapper mapper = new ObjectMapper(); + try { + // Parse the json list of objects + org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd[] vnfd_array = (org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd[]) mapper.readValue(vnfds_list_entity.getBody(), org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd[].class); + // For each object + for(org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd vnfd : vnfd_array) + { + String jsonInString=null; + ObjectMapper mapper2 = new ObjectMapper(); + mapper2.setSerializationInclusion(Include.NON_NULL); + try { + jsonInString = mapper2.writerWithDefaultPrettyPrinter().writeValueAsString(vnfd); + } catch (JsonProcessingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + // Compare db derived data with osm derived data and update the database. + logger.debug("VNFD to JSON:"+jsonInString); + logger.info("VNFD " + vnfd.getId() + " added"); + + // Get the mapped ExperimentMetadata object + VxFMetadata prod = mapOSM10VNFD2ProductFromJSON(vnfd); + try { + jsonInString = mapper2.writerWithDefaultPrettyPrinter().writeValueAsString(prod); + } catch (JsonProcessingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + logger.debug("Prod created:"+jsonInString); + + // Now that we have the product + // Check if the VxFMetadata uuid already exists in the database + + boolean exists_in_db = false; + for(VxFOnBoardedDescriptor dbvxfobd : vxFOnBoardedDescriptors) + { + if(dbvxfobd.getDeployId().equals(vnfd.getId())) + { + logger.info("VNFD " + vnfd.getId() + " already exists"); + exists_in_db = true; + } + } + if(exists_in_db == false) + { + logger.info("VNFD " + vnfd.getId() + " does not exist. Adding to db."); + exists_in_db = true; + //Map osm vim to db vim object + VxFMetadata newVxFMetadata = new VxFMetadata(); + newVxFMetadata.setUuid(vnfd.getId()); + // Combine the vnfd name with the OSM name. + newVxFMetadata.setName(vnfd.getProductName()); + newVxFMetadata.setValidationStatus(ValidationStatus.COMPLETED); + newVxFMetadata.setDateCreated(new Date()); + newVxFMetadata.setDateUpdated(new Date()); + newVxFMetadata.setShortDescription(vnfd.getProductName()+"@"+mp.getName()); + newVxFMetadata.setPackagingFormat(PackagingFormat.OSMvTHIRTEEN); + //Get the manoServiceOwner to add it + newVxFMetadata.setOwner(aMANOClient.getPortalUserByUsername("manoService")); + + // Get VNF Requirements from the vnfd + OSM10VNFRequirements vnfreq = new OSM10VNFRequirements(vnfd); + // Store the requirements in HTML + newVxFMetadata.setDescriptorHTML(vnfreq.toHTML()); + // Store the YAML file + newVxFMetadata.setDescriptor(vnfds_list_entity.getBody()); + + //Add VxFMetadata object to db and get the generated object + newVxFMetadata = aMANOClient.addVxFMetadata(newVxFMetadata); + logger.info("VxF " + vnfd.getId() + " added with VxFMetadata id="+newVxFMetadata.getId()); + + //Create the OnboardedDescriptor + VxFOnBoardedDescriptor newVxFOnBoardedDescriptor = new VxFOnBoardedDescriptor(newVxFMetadata); + newVxFOnBoardedDescriptor.setDeployId(vnfd.getId()); + newVxFOnBoardedDescriptor.setFeedbackMessage("Automatically Retrieved from OSM"); + newVxFOnBoardedDescriptor.setLastOnboarding(new Date()); + newVxFOnBoardedDescriptor.setOnBoardingStatus(OnBoardingStatus.ONBOARDED); + newVxFOnBoardedDescriptor.setUuid(vnfd.getId()); + newVxFOnBoardedDescriptor.setVxfMANOProviderID(vnfd.getProductName()); + newVxFOnBoardedDescriptor.setObMANOprovider(mp); + newVxFOnBoardedDescriptor.setVxf(aMANOClient.getVxFById(newVxFMetadata.getId())); + //Add VxFOnBoardedDescriptor object to db and get the generated object + newVxFOnBoardedDescriptor=aMANOClient.addVxFOnBoardedDescriptor(newVxFOnBoardedDescriptor); + logger.info("VxFOnBoardedDescriptor " + newVxFOnBoardedDescriptor.getId() + " added"); + + } + } + // Check for orphaned + for(VxFOnBoardedDescriptor dbvxfobd : vxFOnBoardedDescriptors) + { + boolean exists_in_osm = false; + // For each object + for(org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd vnfd : vnfd_array) + { + if(dbvxfobd.getDeployId().equals(vnfd.getId())) + { + logger.info("VNFD " + vnfd.getId() + " exists in osm"); + exists_in_osm = true; + } + } + if(exists_in_osm == false && dbvxfobd.getObMANOprovider().getName().equals(mp.getName()) && dbvxfobd.getObMANOprovider().getProject().equals(mp.getProject())) + { + logger.debug(dbvxfobd.getDeployId()+" does not exist and MP name '"+dbvxfobd.getObMANOprovider().getName()+"'='"+mp.getName()+"' and project '"+dbvxfobd.getObMANOprovider().getProject()+"'='"+mp.getProject()+"'"); + dbvxfobd.setOnBoardingStatus(OnBoardingStatus.OSM_MISSING); + dbvxfobd = aMANOClient.updateVxFOnBoardedDescriptor(dbvxfobd); + logger.info("synchronizeVNFDsOSM11 : VxFOnBoardedDescriptor " + dbvxfobd.getId() + " updated OnboardingStatus to OSM_MISSING"); + } + } + } catch (IllegalStateException | IOException e) { + logger.error(e.getMessage()); + e.printStackTrace(); + } + } + + private void synchronizeNSDs(OSMClient osmClient, MANOprovider mp) + { + //****************************************************************** + // Get ExperimentMetadata available from the portal's Database + //List experimentMetadatas = aMANOClient.getExperiments(); + List experimentOnboardDescriptors = aMANOClient.getExperimentOnBoardDescriptors(); + //****************************************************************** + // Get NSDs from OSM MANO. + ResponseEntity nsds_list_entity = osmClient.getNSDescriptorsList(); + if (nsds_list_entity == null || nsds_list_entity.getStatusCode().is4xxClientError() + || nsds_list_entity.getStatusCode().is5xxServerError()) { + logger.error("NSDs List Get Request failed. Status Code:" + nsds_list_entity.getStatusCode().toString() + + ", Payload:" + nsds_list_entity.getBody().toString()); + } else { + logger.debug("Got NSD list "+nsds_list_entity.getBody()); + logger.info("Got MP Version:"+mp.getSupportedMANOplatform().getVersion()); + + if(mp.getSupportedMANOplatform().getVersion().equals("OSMvTEN")) + { + synchronizeNSDsOSM10(experimentOnboardDescriptors, nsds_list_entity, mp); + } + if(mp.getSupportedMANOplatform().getVersion().equals("OSMvELEVEN")) + { + synchronizeNSDsOSM11(experimentOnboardDescriptors, nsds_list_entity, mp); + } + if(mp.getSupportedMANOplatform().getVersion().equals("OSMvTHIRTEEN")) + { + synchronizeNSDsOSM11(experimentOnboardDescriptors, nsds_list_entity, mp); + } + } + } + + + + private void synchronizeNSDsOSM10(List experimentOnBoardDescriptors, ResponseEntity nsds_list_entity, MANOprovider mp) + { + ObjectMapper mapper = new ObjectMapper(); + try { + // Parse the json list of objects + org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd[] nsd_array = (org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd[]) mapper.readValue(nsds_list_entity.getBody(), org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd[].class); + // For each object + for(org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd nsd : nsd_array) + { + String jsonInString=null; + ObjectMapper mapper2 = new ObjectMapper(); + mapper2.setSerializationInclusion(Include.NON_NULL); + try { + jsonInString = mapper2.writerWithDefaultPrettyPrinter().writeValueAsString(nsd); + } catch (JsonProcessingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + // Εδώ θα συγκρίνουμε αυτό που λάβαμε απο τη βάση με αυτό που λάβαμε απο το osm και θα το ανανεώσουμε στη βάση. + logger.debug("NSD to JSON:"+jsonInString); + logger.info("NSD " + nsd.getInvariantId() + " added"); + + // Get the mapped ExperimentMetadata object + ExperimentMetadata prod = mapOSM10NSD2ProductFromJSON(nsd,mp); + try { + jsonInString = mapper2.writerWithDefaultPrettyPrinter().writeValueAsString(prod); + } catch (JsonProcessingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + logger.debug("Prod created:"+jsonInString); + + // Now that we have the product + // Check if the ExperimentMetadata uuid already exists in the database + + boolean exists_in_db = false; + for(ExperimentOnBoardDescriptor dbexpobd : experimentOnBoardDescriptors) + { + if(dbexpobd.getDeployId().equals(nsd.getInvariantId())) + { + logger.info("NSD " + nsd.getInvariantId() + " already exists"); + exists_in_db = true; + } + } + if(exists_in_db == false) + { + logger.info("NSD " + nsd.getInvariantId() + " does not exist. Adding to db."); + exists_in_db = true; + //Map osm vim to db vim object + ExperimentMetadata newExperimentMetadata = new ExperimentMetadata(); + newExperimentMetadata.setUuid(nsd.getInvariantId()); + // Combine the vnfd name with the OSM name. + newExperimentMetadata.setName(nsd.getName()); + newExperimentMetadata.setValidationStatus(ValidationStatus.COMPLETED); + newExperimentMetadata.setDateCreated(new Date()); + newExperimentMetadata.setDateUpdated(new Date()); + newExperimentMetadata.setShortDescription(nsd.getName()+"@"+mp.getName()); + newExperimentMetadata.setPackagingFormat(PackagingFormat.OSMvTEN); + //Get the manoServiceOwner to add it + newExperimentMetadata.setOwner(aMANOClient.getPortalUserByUsername("manoService")); + + // Get VNF Requirements from the vnfd + OSM10NSRequirements nsdreq = new OSM10NSRequirements(nsd); + // Store the requirements in HTML + newExperimentMetadata.setDescriptorHTML(nsdreq.toHTML()); + // Store the YAML file + newExperimentMetadata.setDescriptor(nsds_list_entity.getBody()); + + for (Df v : nsd.getDf().values()) { + for( VnfProfile q : v.getVnfProfile().values()) + { + ConstituentVxF cvxf = new ConstituentVxF(); + try { + cvxf.setMembervnfIndex(q.getId()); + + } catch ( NumberFormatException e) { + cvxf.setMembervnfIndex( "0" ); + } + cvxf.setVnfdidRef((String) q.getVnfdId()); + String vxfuuid = aMANOClient.getVxFOnBoardedDescriptorByVxFAndMP(q.getVnfdId(), mp.getId()); + VxFMetadata vxf = (VxFMetadata) aMANOClient.getVxFByUUid(vxfuuid); + cvxf.setVxfref(vxf); + ((ExperimentMetadata) newExperimentMetadata).getConstituentVxF().add(cvxf); + } + } + //Add VxFMetadata object to db and get the generated object + newExperimentMetadata = aMANOClient.addExperimentMetadata(newExperimentMetadata); + logger.info("Experiment " + nsd.getId() + " added with ExperimentMetadata id="+newExperimentMetadata.getId()); + + //Create the OnboardedDescriptor + ExperimentOnBoardDescriptor newExperimentOnBoardedDescriptor = new ExperimentOnBoardDescriptor(newExperimentMetadata); + newExperimentOnBoardedDescriptor.setDeployId(nsd.getInvariantId()); + newExperimentOnBoardedDescriptor.setFeedbackMessage("Automatically Retrieved from OSM"); + newExperimentOnBoardedDescriptor.setLastOnboarding(new Date()); + newExperimentOnBoardedDescriptor.setOnBoardingStatus(OnBoardingStatus.ONBOARDED); + newExperimentOnBoardedDescriptor.setUuid(nsd.getInvariantId()); + newExperimentOnBoardedDescriptor.setExperimentMANOProviderID(nsd.getName()); + newExperimentOnBoardedDescriptor.setObMANOprovider(mp); + newExperimentOnBoardedDescriptor.setExperiment(aMANOClient.getNSDById(newExperimentMetadata.getId())); + //Add VxFOnBoardedDescriptor object to db and get the generated object + newExperimentOnBoardedDescriptor=aMANOClient.addExperimentOnBoardedDescriptor(newExperimentOnBoardedDescriptor); + logger.info("ExperimentOnBoardedDescriptor " + newExperimentOnBoardedDescriptor.getId() + " added"); + } + } + // Check for orphaned + for(ExperimentOnBoardDescriptor dbexpobd : experimentOnBoardDescriptors) + { + boolean exists_in_osm = false; + // For each object + for(org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd nsd : nsd_array) + { + logger.debug("getDeployId()= " + dbexpobd.getDeployId() + "?=nsd.getInvariantId()" +nsd.getInvariantId()); + if(dbexpobd.getDeployId().equals(nsd.getInvariantId())) + { + logger.info("NSD " + dbexpobd.getDeployId() + " already exists"); + exists_in_osm = true; + } + } + logger.debug(dbexpobd.getDeployId()+" does not exist and MP name '"+dbexpobd.getObMANOprovider().getName()+"'='"+mp.getName()+"' and project '"+dbexpobd.getObMANOprovider().getProject()+"'='"+mp.getProject()+"'?"); + if(exists_in_osm == false && dbexpobd.getObMANOprovider().getName().equals(mp.getName()) && dbexpobd.getObMANOprovider().getProject().equals(mp.getProject())) + { + logger.debug(dbexpobd.getDeployId()+" does not exist and MP name '"+dbexpobd.getObMANOprovider().getName()+"'='"+mp.getName()+"' and project '"+dbexpobd.getObMANOprovider().getProject()+"'='"+mp.getProject()+"'"); + logger.info("synchronizeNSDsOSM10 : ExperimentOnBoardedDescriptor " + dbexpobd.getId() + " not found. Updating OnboardingStatus to OSM_MISSING"); + dbexpobd.setOnBoardingStatus(OnBoardingStatus.OSM_MISSING); + dbexpobd = aMANOClient.updateExperimentOnBoardDescriptor(dbexpobd); + logger.info("synchronizeNSDsOSM10 : ExperimentOnBoardedDescriptor " + dbexpobd.getId() + " updated OnboardingStatus to OSM_MISSING"); + } + } + + } catch (Exception e) { + logger.error(e.getMessage()); + e.printStackTrace(); + } + } + + private void synchronizeNSDsOSM11(List experimentOnBoardDescriptors, ResponseEntity nsds_list_entity, MANOprovider mp) + { + ObjectMapper mapper = new ObjectMapper(); + try { + // Parse the json list of objects + org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd[] nsd_array = (org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd[]) mapper.readValue(nsds_list_entity.getBody(), org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd[].class); + // For each object + for(org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd nsd : nsd_array) + { + String jsonInString=null; + ObjectMapper mapper2 = new ObjectMapper(); + mapper2.setSerializationInclusion(Include.NON_NULL); + try { + jsonInString = mapper2.writerWithDefaultPrettyPrinter().writeValueAsString(nsd); + } catch (JsonProcessingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + // Compare the received from the osm with the database entry and update the database. + logger.debug("NSD to JSON:"+jsonInString); + logger.info("NSD " + nsd.getInvariantId() + " added"); + + // Get the mapped ExperimentMetadata object + ExperimentMetadata prod = mapOSM10NSD2ProductFromJSON(nsd,mp); + try { + jsonInString = mapper2.writerWithDefaultPrettyPrinter().writeValueAsString(prod); + } catch (JsonProcessingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + logger.debug("Prod created:"+jsonInString); + + // Now that we have the product + // Check if the ExperimentMetadata uuid already exists in the database + + boolean exists_in_db = false; + for(ExperimentOnBoardDescriptor dbexpobd : experimentOnBoardDescriptors) + { + if(dbexpobd.getDeployId().equals(nsd.getInvariantId())) + { + logger.info("NSD " + nsd.getInvariantId() + " already exists"); + exists_in_db = true; + } + } + if(exists_in_db == false) + { + logger.info("NSD " + nsd.getInvariantId() + " does not exist. Adding to db."); + exists_in_db = true; + // Map osm vim to db vim object + ExperimentMetadata newExperimentMetadata = new ExperimentMetadata(); + newExperimentMetadata.setUuid(nsd.getInvariantId()); + // Combine the vnfd name with the OSM name. + newExperimentMetadata.setName(nsd.getName()); + newExperimentMetadata.setValidationStatus(ValidationStatus.COMPLETED); + newExperimentMetadata.setDateCreated(new Date()); + newExperimentMetadata.setDateUpdated(new Date()); + newExperimentMetadata.setShortDescription(nsd.getName()+"@"+mp.getName()); + newExperimentMetadata.setPackagingFormat(PackagingFormat.OSMvELEVEN); + // Get the manoServiceOwner to add it + newExperimentMetadata.setOwner(aMANOClient.getPortalUserByUsername("manoService")); + + // Get VNF Requirements from the vnfd + OSM10NSRequirements nsdreq = new OSM10NSRequirements(nsd); + // Store the requirements in HTML + newExperimentMetadata.setDescriptorHTML(nsdreq.toHTML()); + // Store the YAML file + newExperimentMetadata.setDescriptor(nsds_list_entity.getBody()); + + for (Df v : nsd.getDf().values()) { + for( VnfProfile q : v.getVnfProfile().values()) + { + ConstituentVxF cvxf = new ConstituentVxF(); + try { + cvxf.setMembervnfIndex(q.getId()); + + } catch ( NumberFormatException e) { + cvxf.setMembervnfIndex( "0" ); + } + cvxf.setVnfdidRef((String) q.getVnfdId()); + String vxfuuid = aMANOClient.getVxFOnBoardedDescriptorByVxFAndMP(q.getVnfdId(), mp.getId()); + VxFMetadata vxf = (VxFMetadata) aMANOClient.getVxFByUUid(vxfuuid); + cvxf.setVxfref(vxf); + ((ExperimentMetadata) newExperimentMetadata).getConstituentVxF().add(cvxf); + } + } + // Add VxFMetadata object to db and get the generated object + newExperimentMetadata = aMANOClient.addExperimentMetadata(newExperimentMetadata); + logger.info("Experiment " + nsd.getId() + " added with ExperimentMetadata id="+newExperimentMetadata.getId()); + + // Create the OnboardedDescriptor + ExperimentOnBoardDescriptor newExperimentOnBoardedDescriptor = new ExperimentOnBoardDescriptor(newExperimentMetadata); + newExperimentOnBoardedDescriptor.setDeployId(nsd.getInvariantId()); + newExperimentOnBoardedDescriptor.setFeedbackMessage("Automatically Retrieved from OSM"); + newExperimentOnBoardedDescriptor.setLastOnboarding(new Date()); + newExperimentOnBoardedDescriptor.setOnBoardingStatus(OnBoardingStatus.ONBOARDED); + newExperimentOnBoardedDescriptor.setUuid(nsd.getInvariantId()); + newExperimentOnBoardedDescriptor.setExperimentMANOProviderID(nsd.getName()); + newExperimentOnBoardedDescriptor.setObMANOprovider(mp); + newExperimentOnBoardedDescriptor.setExperiment(aMANOClient.getNSDById(newExperimentMetadata.getId())); + // Add VxFOnBoardedDescriptor object to db and get the generated object + newExperimentOnBoardedDescriptor=aMANOClient.addExperimentOnBoardedDescriptor(newExperimentOnBoardedDescriptor); + logger.info("ExperimentOnBoardedDescriptor " + newExperimentOnBoardedDescriptor.getId() + " added"); + } + } + // Check for orphaned + for(ExperimentOnBoardDescriptor dbexpobd : experimentOnBoardDescriptors) + { + boolean exists_in_osm = false; + // For each object + for(org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd nsd : nsd_array) + { + logger.debug("getDeployId()= " + dbexpobd.getDeployId() + "?=nsd.getInvariantId()" +nsd.getInvariantId()); + if(dbexpobd.getDeployId().equals(nsd.getInvariantId())) + { + logger.info("NSD " + dbexpobd.getDeployId() + " already exists"); + exists_in_osm = true; + } + } + if(exists_in_osm == false && dbexpobd.getObMANOprovider().getName().equals(mp.getName()) && dbexpobd.getObMANOprovider().getProject().equals(mp.getProject())) + { + logger.debug(dbexpobd.getDeployId()+" does not exist and MP name '"+dbexpobd.getObMANOprovider().getName()+"'='"+mp.getName()+"' and project '"+dbexpobd.getObMANOprovider().getProject()+"'='"+mp.getProject()+"'"); + logger.info("synchronizeNSDsOSM11 : ExperimentOnBoardedDescriptor " + dbexpobd.getId() + " not found. Updating OnboardingStatus to OSM_MISSING"); + dbexpobd.setOnBoardingStatus(OnBoardingStatus.OSM_MISSING); + dbexpobd = aMANOClient.updateExperimentOnBoardDescriptor(dbexpobd); + logger.info("synchronizeNSDsOSM11 : ExperimentOnBoardedDescriptor " + dbexpobd.getId() + " updated OnboardingStatus to OSM_MISSING"); + } + } + + } catch (Exception e) { + logger.error(e.getMessage()); + e.printStackTrace(); + } + } + + private void synchronizeNSDsOSM13(List experimentOnBoardDescriptors, ResponseEntity nsds_list_entity, MANOprovider mp) + { + ObjectMapper mapper = new ObjectMapper(); + try { + // Parse the json list of objects + org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd[] nsd_array = (org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd[]) mapper.readValue(nsds_list_entity.getBody(), org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd[].class); + // For each object + for(org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd nsd : nsd_array) + { + String jsonInString=null; + ObjectMapper mapper2 = new ObjectMapper(); + mapper2.setSerializationInclusion(Include.NON_NULL); + try { + jsonInString = mapper2.writerWithDefaultPrettyPrinter().writeValueAsString(nsd); + } catch (JsonProcessingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + // Compare the received from the osm with the database entry and update the database. + logger.debug("NSD to JSON:"+jsonInString); + logger.info("NSD " + nsd.getInvariantId() + " added"); + + // Get the mapped ExperimentMetadata object + ExperimentMetadata prod = mapOSM10NSD2ProductFromJSON(nsd,mp); + try { + jsonInString = mapper2.writerWithDefaultPrettyPrinter().writeValueAsString(prod); + } catch (JsonProcessingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + logger.debug("Prod created:"+jsonInString); + + // Now that we have the product + // Check if the ExperimentMetadata uuid already exists in the database + + boolean exists_in_db = false; + for(ExperimentOnBoardDescriptor dbexpobd : experimentOnBoardDescriptors) + { + if(dbexpobd.getDeployId().equals(nsd.getInvariantId())) + { + logger.info("NSD " + nsd.getInvariantId() + " already exists"); + exists_in_db = true; + } + } + if(exists_in_db == false) + { + logger.info("NSD " + nsd.getInvariantId() + " does not exist. Adding to db."); + exists_in_db = true; + // Map osm vim to db vim object + ExperimentMetadata newExperimentMetadata = new ExperimentMetadata(); + newExperimentMetadata.setUuid(nsd.getInvariantId()); + // Combine the vnfd name with the OSM name. + newExperimentMetadata.setName(nsd.getName()); + newExperimentMetadata.setValidationStatus(ValidationStatus.COMPLETED); + newExperimentMetadata.setDateCreated(new Date()); + newExperimentMetadata.setDateUpdated(new Date()); + newExperimentMetadata.setShortDescription(nsd.getName()+"@"+mp.getName()); + newExperimentMetadata.setPackagingFormat(PackagingFormat.OSMvTHIRTEEN); + // Get the manoServiceOwner to add it + newExperimentMetadata.setOwner(aMANOClient.getPortalUserByUsername("manoService")); + + // Get VNF Requirements from the vnfd + OSM10NSRequirements nsdreq = new OSM10NSRequirements(nsd); + // Store the requirements in HTML + newExperimentMetadata.setDescriptorHTML(nsdreq.toHTML()); + // Store the YAML file + newExperimentMetadata.setDescriptor(nsds_list_entity.getBody()); + + for (Df v : nsd.getDf().values()) { + for( VnfProfile q : v.getVnfProfile().values()) + { + ConstituentVxF cvxf = new ConstituentVxF(); + try { + cvxf.setMembervnfIndex(q.getId()); + + } catch ( NumberFormatException e) { + cvxf.setMembervnfIndex( "0" ); + } + cvxf.setVnfdidRef((String) q.getVnfdId()); + String vxfuuid = aMANOClient.getVxFOnBoardedDescriptorByVxFAndMP(q.getVnfdId(), mp.getId()); + VxFMetadata vxf = (VxFMetadata) aMANOClient.getVxFByUUid(vxfuuid); + cvxf.setVxfref(vxf); + ((ExperimentMetadata) newExperimentMetadata).getConstituentVxF().add(cvxf); + } + } + // Add VxFMetadata object to db and get the generated object + newExperimentMetadata = aMANOClient.addExperimentMetadata(newExperimentMetadata); + logger.info("Experiment " + nsd.getId() + " added with ExperimentMetadata id="+newExperimentMetadata.getId()); + + // Create the OnboardedDescriptor + ExperimentOnBoardDescriptor newExperimentOnBoardedDescriptor = new ExperimentOnBoardDescriptor(newExperimentMetadata); + newExperimentOnBoardedDescriptor.setDeployId(nsd.getInvariantId()); + newExperimentOnBoardedDescriptor.setFeedbackMessage("Automatically Retrieved from OSM"); + newExperimentOnBoardedDescriptor.setLastOnboarding(new Date()); + newExperimentOnBoardedDescriptor.setOnBoardingStatus(OnBoardingStatus.ONBOARDED); + newExperimentOnBoardedDescriptor.setUuid(nsd.getInvariantId()); + newExperimentOnBoardedDescriptor.setExperimentMANOProviderID(nsd.getName()); + newExperimentOnBoardedDescriptor.setObMANOprovider(mp); + newExperimentOnBoardedDescriptor.setExperiment(aMANOClient.getNSDById(newExperimentMetadata.getId())); + // Add VxFOnBoardedDescriptor object to db and get the generated object + newExperimentOnBoardedDescriptor=aMANOClient.addExperimentOnBoardedDescriptor(newExperimentOnBoardedDescriptor); + logger.info("ExperimentOnBoardedDescriptor " + newExperimentOnBoardedDescriptor.getId() + " added"); + } + } + // Check for orphaned + for(ExperimentOnBoardDescriptor dbexpobd : experimentOnBoardDescriptors) + { + boolean exists_in_osm = false; + // For each object + for(org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd nsd : nsd_array) + { + logger.debug("getDeployId()= " + dbexpobd.getDeployId() + "?=nsd.getInvariantId()" +nsd.getInvariantId()); + if(dbexpobd.getDeployId().equals(nsd.getInvariantId())) + { + logger.info("NSD " + dbexpobd.getDeployId() + " already exists"); + exists_in_osm = true; + } + } + if(exists_in_osm == false && dbexpobd.getObMANOprovider().getName().equals(mp.getName()) && dbexpobd.getObMANOprovider().getProject().equals(mp.getProject())) + { + logger.debug(dbexpobd.getDeployId()+" does not exist and MP name '"+dbexpobd.getObMANOprovider().getName()+"'='"+mp.getName()+"' and project '"+dbexpobd.getObMANOprovider().getProject()+"'='"+mp.getProject()+"'"); + logger.info("synchronizeNSDsOSM11 : ExperimentOnBoardedDescriptor " + dbexpobd.getId() + " not found. Updating OnboardingStatus to OSM_MISSING"); + dbexpobd.setOnBoardingStatus(OnBoardingStatus.OSM_MISSING); + dbexpobd = aMANOClient.updateExperimentOnBoardDescriptor(dbexpobd); + logger.info("synchronizeNSDsOSM11 : ExperimentOnBoardedDescriptor " + dbexpobd.getId() + " updated OnboardingStatus to OSM_MISSING"); + } + } + + } catch (Exception e) { + logger.error(e.getMessage()); + e.printStackTrace(); + } + } + + public VxFMetadata mapOSM8VNFD2ProductFromJSON(Vnfd vnfd) { + + VxFMetadata prod = new VxFMetadata(); + // We need to provide different implementations for each OSM version as this + // maps to a different version of NSD model. + prod.setUuid(vnfd.getId()); + prod.setName(vnfd.getName()); + prod.setVersion(vnfd.getVersion()); + prod.setShortDescription(vnfd.getName()); + prod.setLongDescription(vnfd.getName()); + // Store the requirements in HTML + prod.setDescriptorHTML(""); + // Store the YAML file + prod.setDescriptor("Automatically loaded VNFD"); + prod.setIconsrc(""); + return prod; + + } + + public VxFMetadata mapOSM9VNFD2ProductFromJSON(org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd vnfd) { + + VxFMetadata prod = new VxFMetadata(); + // We need to provide different implementations for each OSM version as this + // maps to a different version of NSD model. + prod.setUuid(vnfd.getId()); + prod.setName(vnfd.getProductName()); + prod.setVersion(vnfd.getVersion()); + prod.setShortDescription(vnfd.getProductName()); + prod.setLongDescription(vnfd.getProductName()); + // Store the requirements in HTML + prod.setDescriptorHTML(""); + // Store the YAML file + prod.setDescriptor("Automatically loaded VNFD"); + prod.setIconsrc(""); + return prod; + + } + + public VxFMetadata mapOSM10VNFD2ProductFromJSON(org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd vnfd) { + + VxFMetadata prod = new VxFMetadata(); + // We need to provide different implementations for each OSM version as this + // maps to a different version of NSD model. + prod.setUuid(vnfd.getId()); + prod.setName(vnfd.getProductName()); + prod.setVersion(vnfd.getVersion()); + prod.setShortDescription(vnfd.getProductName()); + prod.setLongDescription(vnfd.getProductName()); + // Store the requirements in HTML + prod.setDescriptorHTML(""); + // Store the YAML file + prod.setDescriptor("Automatically loaded VNFD"); + prod.setIconsrc(""); + return prod; + + } + + + + public ExperimentMetadata mapOSM10NSD2ProductFromJSON(org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd nsd, MANOprovider mp) + { + try + { + ExperimentMetadata prod = new ExperimentMetadata(); + // We need to provide different implementations for each OSM version as this + // maps to a different version of NSD model. + prod.setUuid(nsd.getInvariantId()); + prod.setName(nsd.getName()); + prod.setVersion(nsd.getVersion()); + //prod.setVendor(ns.getDesigner()); + prod.setShortDescription(nsd.getName()); + prod.setLongDescription(nsd.getName()); + for (Df v : nsd.getDf().values()) { + for( VnfProfile q : v.getVnfProfile().values()) + { + ConstituentVxF cvxf = new ConstituentVxF(); + cvxf.setMembervnfIndex(q.getId()); + cvxf.setVnfdidRef((String) q.getVnfdId()); + String vxfuuid = aMANOClient.getVxFOnBoardedDescriptorByVxFAndMP(q.getVnfdId(), mp.getId()); + VxFMetadata vxf = (VxFMetadata) aMANOClient.getVxFByUUid(vxfuuid); + cvxf.setVxfref(vxf); + ((ExperimentMetadata) prod).getConstituentVxF().add(cvxf); + } + } + // Get NS Requirements from the nsd + OSM10NSRequirements vr = new OSM10NSRequirements(nsd); + // Store the requirements in HTML + prod.setDescriptorHTML(vr.toHTML()); + // Store the YAML file + prod.setDescriptor("Automatically loaded NSD"); + prod.setIconsrc(""); + return prod; + } + catch(Exception e) + { + centralLogger.log(CLevel.ERROR, "Failed to map NSD 2 Product for "+nsd.getName()+". Retuning null.", compname); + return null; + } + } + + @Transactional + public void checkAndUpdateRunningDeploymentDescriptors() { + checkAndUpdateMANOProvidersResources(); + logger.info("Update Deployment Descriptors"); + // centralLogger.log( CLevel.INFO, "Update Deployment Descriptors!!!!", + // compname); + try { + List runningDeploymentDescriptors = aMANOClient + .getRunningInstantiatingAndTerminatingDeployments(); + for (DeploymentDescriptor nsd : runningDeploymentDescriptors) { + logger.info("NSD name:" + nsd.getName()); + + } + OSMClient osmClient = null; + // For each deployment get the status info and the IPs + for (int i = 0; i < runningDeploymentDescriptors.size(); i++) { + DeploymentDescriptor deployment_tmp = aMANOClient + .getDeploymentByIdEager(runningDeploymentDescriptors.get(i).getId()); + //deployment_tmp.getExperimentFullDetails(); + try { + // Get the MANO Provider for each deployment + logger.debug("MANOprovider sm deployment_tmp.getObddescriptor_uuid() = " + deployment_tmp.getObddescriptor_uuid() ); + logger.debug("MANOprovider sm deployment_tmp.getObddescriptor_uuid().toString() = " + deployment_tmp.getObddescriptor_uuid().toString() ); + MANOprovider sm = deployment_tmp.getObddescriptor_uuid().getObMANOprovider() ; + + logger.debug("manoVersion sm.getSupportedMANOplatform() = " + sm.getSupportedMANOplatform() ); + logger.debug("manoVersion sm.getSupportedMANOplatform().getVersion() = " + sm.getSupportedMANOplatform().getVersion() ); + String manoVersion = sm.getSupportedMANOplatform().getVersion(); + + //if (osmClient == null || !osmClient.getMANOApiEndpoint().equals(sm.getApiEndpoint())) { + try { + osmClient = OSMClientFactory.getOSMClient(manoVersion, sm.getApiEndpoint(), + sm.getUsername(), sm.getPassword(), sm.getProject()); + + + + JSONObject ns_instance_info = osmClient.getNSInstanceInfo(deployment_tmp.getInstanceId()); + // JSONObject ns_instance_content_info = + // osmClient.getNSInstanceContentInfo(deployment_tmp.getInstanceId()); + // If the no nsd with the specific id is found, mark the instance as faile to + // delete. + if (ns_instance_info == null) { + deployment_tmp.setStatus(DeploymentDescriptorStatus.FAILED_OSM_REMOVED); + centralLogger.log(CLevel.INFO, "Status change of deployment1 " + deployment_tmp.getName() + + " to " + deployment_tmp.getStatus(), compname); + logger.info("NS not found in OSM. Status change of deployment1 " + deployment_tmp.getName() + + " to " + deployment_tmp.getStatus()); + deployment_tmp.setFeedback("NS instance not present in OSM. Marking as FAILED_OSM_REMOVED"); + logger.info("Update DeploymentDescriptor Object in 363"); + DeploymentDescriptor deploymentdescriptor_final = aMANOClient + .updateDeploymentDescriptor(deployment_tmp); + logger.info("NS status change is now " + deploymentdescriptor_final.getStatus()); + aMANOClient.deleteInstanceFailed(deploymentdescriptor_final); + } else { + try { + // String nsr_string = JSONObject.quote(ns_instance_info.toString()); + deployment_tmp.setNsr(ns_instance_info.toString()); + deployment_tmp = aMANOClient.updateDeploymentDescriptor(deployment_tmp); + logger.info("Setting NSR Info:" + deployment_tmp.getNsr()); + + + + if (deployment_tmp.getStatus() == DeploymentDescriptorStatus.RUNNING) { + + updateDescriptorInRunningState( deployment_tmp, osmClient, ns_instance_info ); + + + } + logger.info("Setting Operational Status"); + deployment_tmp.setOperationalStatus(ns_instance_info.getString("operational-status")); + deployment_tmp.setConfigStatus(ns_instance_info.getString("config-status")); + deployment_tmp.setDetailedStatus(ns_instance_info.getString("detailed-status") + .replaceAll("\\n", " ").replaceAll("\'", "'").replaceAll("\\\\", "")); + logger.debug("deployment_tmp before update "+deployment_tmp.toJSON()); + deployment_tmp = aMANOClient.updateDeploymentDescriptor(deployment_tmp); + logger.debug("deployment_tmp after update "+deployment_tmp.toJSON()); + + + // Depending on the current OSM status, change the portal status. + if (deployment_tmp.getStatus() == DeploymentDescriptorStatus.INSTANTIATING + && deployment_tmp.getOperationalStatus().toLowerCase().equals("running")) { + JSONObject ns_nslcm_details = osmClient + .getNSLCMDetails(deployment_tmp.getNsLcmOpOccId()); + deployment_tmp.setNs_nslcm_details(ns_nslcm_details.toString()); + deployment_tmp = aMANOClient.updateDeploymentDescriptor(deployment_tmp); + deployment_tmp.setStatus(DeploymentDescriptorStatus.RUNNING); + logger.info("Status change of deployment1 " + deployment_tmp.getName() + " to " + + deployment_tmp.getStatus()); + centralLogger.log(CLevel.INFO, "Status change of deployment1 " + deployment_tmp.getName() + + " to " + deployment_tmp.getStatus(), compname); + deployment_tmp.setFeedback(ns_instance_info.getString("detailed-status") + .replaceAll("\\n", " ").replaceAll("\'", "'").replaceAll("\\\\", "")); + + deployment_tmp.setConstituentVnfrIps( extractIPsFromNSR(ns_instance_info) ); + + updateDescriptorInRunningState( deployment_tmp, osmClient, ns_instance_info ); + +// deployment_tmp = aMANOClient.updateDeploymentDescriptor(deployment_tmp); +// aMANOClient.deploymentInstantiationSucceded(deployment_tmp); + } + // deployment_tmp.getStatus() == DeploymentDescriptorStatus.TERMINATING && + if (deployment_tmp.getOperationalStatus().toLowerCase().equals("terminated")) { + // This message changes in OSM5 from "terminating" to "terminated" + // && deployment_tmp.getConfigStatus().toLowerCase().equals("terminated") + // && deployment_tmp.getDetailedStatus().toLowerCase().equals("done")) { + deployment_tmp.setFeedback(ns_instance_info.getString("detailed-status") + .replaceAll("\\n", " ").replaceAll("\'", "'").replaceAll("\\\\", "")); + deployment_tmp.setStatus(DeploymentDescriptorStatus.TERMINATED); + centralLogger.log(CLevel.INFO, "Status change of deployment1 " + deployment_tmp.getName() + + " to " + deployment_tmp.getStatus(), compname); + logger.info("Status change of deployment1 " + deployment_tmp.getName() + " to " + + deployment_tmp.getStatus()); + deployment_tmp.setConstituentVnfrIps("N/A"); + deployment_tmp = aMANOClient.updateDeploymentDescriptor(deployment_tmp); + aMANOClient.deploymentTerminationSucceded(deployment_tmp); + } + // if(deployment_tmp.getStatus() != DeploymentDescriptorStatus.FAILED && + // deployment_tmp.getOperationalStatus().equals("failed")) + if (deployment_tmp.getStatus() == DeploymentDescriptorStatus.INSTANTIATING + && deployment_tmp.getOperationalStatus().equals("failed")) { + deployment_tmp.setStatus(DeploymentDescriptorStatus.FAILED); + centralLogger.log(CLevel.INFO, "Status change of deployment1 " + deployment_tmp.getName() + + " to " + deployment_tmp.getStatus(), compname); + logger.info("Status change of deployment1 " + deployment_tmp.getName() + " to " + + deployment_tmp.getStatus()); + deployment_tmp.setFeedback(ns_instance_info.getString("detailed-status") + .replaceAll("\\n", " ").replaceAll("\'", "'").replaceAll("\\\\", "")); + deployment_tmp.setConstituentVnfrIps("N/A"); + deployment_tmp = aMANOClient.updateDeploymentDescriptor(deployment_tmp); + aMANOClient.deploymentInstantiationFailed(deployment_tmp); + } + if (deployment_tmp.getStatus() == DeploymentDescriptorStatus.TERMINATING + && deployment_tmp.getOperationalStatus().equals("failed")) { + deployment_tmp.setStatus(DeploymentDescriptorStatus.TERMINATION_FAILED); + centralLogger.log(CLevel.INFO, "Status change of deployment1 " + deployment_tmp.getName() + + " to " + deployment_tmp.getStatus(), compname); + logger.info("Status change of deployment1 " + deployment_tmp.getName() + " to " + + deployment_tmp.getStatus()); + deployment_tmp.setFeedback(ns_instance_info.getString("detailed-status") + .replaceAll("\\n", " ").replaceAll("\'", "'").replaceAll("\\\\", "")); + deployment_tmp = aMANOClient.updateDeploymentDescriptor(deployment_tmp); + aMANOClient.deploymentTerminationFailed(deployment_tmp); + } + logger.info("NS status change is now " + deployment_tmp.getStatus()); + } catch (JSONException e) { + logger.error("Status update failed with error:" + e.getMessage()); + } + } + + } catch (Exception e) { + logger.error(manoVersion + " fails authentication"); + centralLogger.log(CLevel.ERROR, manoVersion + " fails authentication", compname); + + //return; + } + //}//end if + + + + + } catch (Exception e) { + logger.error("Check and update process failed with error:" + e.getMessage()); + } + } + checkAndDeployExperimentToMANOProvider(); + checkAndTerminateExperimentToMANOProvider(); + checkAndDeleteTerminatedOrFailedDeployments(); + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + + private void updateDescriptorInRunningState(DeploymentDescriptor deployment_tmp, OSMClient osmClient, JSONObject ns_instance_info) { + + // JSONObject ns_nslcm_details = + // osmClient.getNSLCMDetails(deployment_tmp.getNsLcmOpOccId()); + + String previous_nslcm_details = deployment_tmp.getNs_nslcm_details(); //contains last performed action of array + String current_nslcm_details = osmClient + .getNSLCMDetailsListByNSID(deployment_tmp.getInstanceId()); + logger.info("Calling alert on scale"); + current_nslcm_details = aMANOClient.alertOnScaleOpsList(deployment_tmp, previous_nslcm_details, current_nslcm_details); + + deployment_tmp.setNs_nslcm_details(current_nslcm_details); + logger.info("After Calling alert on scale"); +// deployment_tmp = aMANOClient.updateDeploymentDescriptor(deployment_tmp); + + //ResponseEntity response=this.performNSInstanceAction("{\"nsInstanceId\": \"1f12d5d7-2ffe-454b-95b5-a805b480303b\",\"member_vnf_index\" : \"1\",\"primitive\" : \"touch\", \"primitive_params\" : {\"filename\" : \"/home/ubuntu/osmclienttest2\"}}"); + //JSONObject obj = new JSONObject(response.getBody()); + //String action_id = obj.getString("id"); + //logger.info("Got action id:"+action_id); + + // ******************************************************************************************************************* + // Create the payload for + //logger.info("Starting scaling"); + //ANSScaleRequestPayload nsscalerequestpayload = new ANSScaleRequestPayload(); + //nsscalerequestpayload.setScaleType("SCALE_VNF"); + //nsscalerequestpayload.setNsInstanceId(deployment_tmp.getInstanceId()); + //nsscalerequestpayload.getScaleVnfData().getScaleByStepData().setMember_vnf_index("1"); + //nsscalerequestpayload.getScaleVnfData().getScaleByStepData() + // .setScaling_group_descriptor("apache_vdu_autoscale"); + //if (Math.random() > 0.5) { + // nsscalerequestpayload.getScaleVnfData().setScaleVnfType("SCALE_IN"); + //} else { + // nsscalerequestpayload.getScaleVnfData().setScaleVnfType("SCALE_OUT"); + //} + //ResponseEntity response = this + // .performNSInstanceScale(nsscalerequestpayload.toJSON()); + //logger.info(nsscalerequestpayload.toJSON()); + //JSONObject obj = new JSONObject(response.getBody()); + //String action_id = obj.getString("id"); + //logger.info("Got action id:" + action_id); + // ******************************************************************************************************************* + + + + //Get the VNF instance ids + logger.debug("checkAndUpdateRunningDeploymentDescriptors ns instance info "+ns_instance_info); + List constituent_vnfr_refs = JsonPath.read(ns_instance_info.toString(), "$.constituent-vnfr-ref"); + Integer q=0; + deployment_tmp.getDeploymentDescriptorVxFInstanceInfo().clear(); + for(String constituent_vnfr_ref : constituent_vnfr_refs) + { + logger.info("VNF with id "+constituent_vnfr_ref+" found in NS instance info."); + //get the info of the vnf instances + JSONObject vnf_instance_info = osmClient.getVNFInstanceInfo(constituent_vnfr_ref); + if (vnf_instance_info == null) { + deployment_tmp.setFeedback("VNF instance not present in NS Instance Info."); + } else { + try { + logger.info("Updating vxfPlacementInfo"); + logger.debug("VNF Instance information " +vnf_instance_info.toString()); + logger.debug("Initial "+deployment_tmp.getDeploymentDescriptorVxFInstanceInfo()); + DeploymentDescriptorVxFInstanceInfo tmp = new DeploymentDescriptorVxFInstanceInfo(); + String member_vnf_index_ref = JsonPath.read(vnf_instance_info.toString(), "$.member-vnf-index-ref"); + tmp.setMemberVnfIndexRef(member_vnf_index_ref); + tmp.setVxfInstanceInfo(vnf_instance_info.toString()); + deployment_tmp.getDeploymentDescriptorVxFInstanceInfo().add(tmp); + } + catch (Exception e) { + logger.error("Failed to load vxfplacements info with error " + e.getMessage()); + } + } + q++; + } + + + + if (!deployment_tmp.getOperationalStatus() + .equals(ns_instance_info.getString("operational-status")) + || !deployment_tmp.getConfigStatus() + .equals(ns_instance_info.getString("config-status")) + || !deployment_tmp.getDetailedStatus() + .equals(ns_instance_info.getString("detailed-status") + .replaceAll("\\n", " ").replaceAll("\'", "'") + .replaceAll("\\\\", ""))) { + logger.info("Status change of deployment1 " + deployment_tmp.getName() + " to " + + deployment_tmp.getStatus()); + centralLogger.log(CLevel.INFO, "Status change of deployment1 " + + deployment_tmp.getName() + " to " + deployment_tmp.getStatus(), compname); + deployment_tmp.setFeedback(ns_instance_info.getString("detailed-status") + .replaceAll("\\n", " ").replaceAll("\'", "'").replaceAll("\\\\", "")); + if(deployment_tmp.getExperimentFullDetails().getPackagingFormat().ordinal()<=PackagingFormat.OSMvEIGHT.ordinal()) + { + deployment_tmp.setConstituentVnfrIps( extractIPsFromNSR(ns_instance_info) ); + } + else if(deployment_tmp.getExperimentFullDetails().getPackagingFormat().ordinal()>PackagingFormat.OSMvEIGHT.ordinal()) + { + deployment_tmp.setConstituentVnfrIps("ToDo"); + } + + deployment_tmp = aMANOClient.updateDeploymentDescriptor(deployment_tmp); + aMANOClient.deploymentInstantiationSucceded(deployment_tmp); + } else { + deployment_tmp = aMANOClient.updateDeploymentDescriptor(deployment_tmp); + } + + + /** + * publish topic event that NSLCM changed + */ + if ( + !previous_nslcm_details.equals( deployment_tmp.getNs_nslcm_details() ) ) { + logger.info("Calling notifyOnLCMChanged"); + aMANOClient.notifyOnLCMChanged( deployment_tmp ); + } + + + } + + private String extractIPsFromNSR(JSONObject ns_instance_info) { + try { + JSONObject deploymentStatus = ns_instance_info.getJSONObject("deploymentStatus"); + StringBuffer IPinfo = new StringBuffer(); + JSONArray vnfs = deploymentStatus.getJSONArray("vnfs"); + for (int k = 0; k < vnfs.length(); k++) { + JSONObject vnf = (JSONObject) vnfs.get(k); + IPinfo.append(vnf.get("vnf_name") + ":"); + IPinfo.append(vnf.get("ip_address")); + JSONArray vms = vnf.getJSONArray("vms"); + IPinfo.append("["); + for (int l = 0; l < vms.length(); l++) { + JSONObject vm = (JSONObject) vms.get(l); + JSONArray interfaces = vm.getJSONArray("interfaces"); + // IPinfo.append( "ifs=" ); + for (int m = 0; m < interfaces.length(); m++) { + JSONObject ipinterface = (JSONObject) interfaces.get(m); + IPinfo.append(ipinterface.get("ip_address") + ","); + } + + } + IPinfo.append("]\n"); + } + + logger.debug(IPinfo); + return IPinfo.toString(); + + } catch (Exception e) { + logger.error(e.getMessage()); + } + return ""; + } + + private ExperimentOnBoardDescriptor getExperimOBD(DeploymentDescriptor deployment_tmp) { + logger.debug( "getExperimOBD start"); + for (ExperimentOnBoardDescriptor e : deployment_tmp.getExperimentFullDetails() + .getExperimentOnBoardDescriptors()) { + logger.debug( "getExperimOBD:"+ e.toString()); + return e; // return the first one found + } + return null; + } + + public ResponseEntity performNSInstanceAction(String nsactionrequestpayloadstring) { + // Deserialize input string as a NSActionRequestPayload + ΑNSActionRequestPayload nsactionrequestpayload; + try { + ObjectMapper mapper = new ObjectMapper(); + nsactionrequestpayload = mapper.readValue(nsactionrequestpayloadstring, ΑNSActionRequestPayload.class); + + DeploymentDescriptor deploymentdescriptor = aMANOClient + .getDeploymentByInstanceIdEager(nsactionrequestpayload.getNsInstanceId()); + ExperimentOnBoardDescriptor tmp = deploymentdescriptor.getObddescriptor_uuid(); + // Connect to OSM + OSMClient osmClient = null; + try { + logger.debug("Connecting to " + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " MANO Client of version " + tmp.getObMANOprovider().getSupportedMANOplatform().getVersion() + + "."); + osmClient = OSMClientFactory.getOSMClient( + tmp.getObMANOprovider().getSupportedMANOplatform().getVersion(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getApiEndpoint(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getUsername(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getPassword(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getProject()); + // MANOStatus.setOsm5CommunicationStatusActive(null); + } catch (Exception e) { + logger.error("performNSInstanceAction, " + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " fails authentication! Aborting action on NS."); + centralLogger.log(CLevel.ERROR, + "performNSInstanceAction, " + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " fails authentication! Aborting action on NS.", + compname); + deploymentdescriptor + .setFeedback((new Date()) + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " communication failed. Aborting action on NS. "); + deploymentdescriptor.setOperationalStatus((new Date()) + " communication-failure "); + deploymentdescriptor = aMANOClient.updateDeploymentDescriptor(deploymentdescriptor); + // aMANOClient.deploymentInstantiationFailed(deploymentdescriptor); + return (ResponseEntity) ResponseEntity.badRequest().body("{message:" + e.getMessage() + "}"); + } + + // Create the payload + // nsactionrequestpayload = new NSActionRequestPayload(); + // nsactionrequestpayload.setNsInstanceId(deploymentdescriptor.getInstanceId()); + // nsactionrequestpayload.setMember_vnf_index("1"); + // nsactionrequestpayload.setPrimitive("touch"); + // Map primitive_params = new LinkedHashMap(); + // primitive_params.put("filename", "/home/ubuntu/osmclienttest2"); + // nsactionrequestpayload.setPrimitive_params(primitive_params); + + // Apply the Action + ResponseEntity ns_action_entity = osmClient.actionNSInstance(deploymentdescriptor.getInstanceId(), + nsactionrequestpayload.toJSON()); + if (ns_action_entity == null || ns_action_entity.getStatusCode().is4xxClientError() + || ns_action_entity.getStatusCode().is5xxServerError()) { + logger.error("NS Action failed. Status Code:" + ns_action_entity.getStatusCode().toString() + + ", Payload:" + ns_action_entity.getBody().toString()); + } else { + // NS action starts + logger.info("NS action of NS with id" + deploymentdescriptor.getInstanceId() + " started."); + // Save the changes to DeploymentDescriptor + logger.debug("NS action Status Code:" + ns_action_entity.getStatusCode().toString() + ", Payload:" + + ns_action_entity.getBody().toString()); + } + // Get the response id or failure + return ns_action_entity; + } catch (JsonParseException e) { + // TODO Auto-generated catch block + logger.error(e.getMessage()); + return (ResponseEntity) ResponseEntity.badRequest().body("{message:" + e.getMessage() + "}"); + } catch (JsonMappingException e) { + // TODO Auto-generated catch block + logger.error(e.getMessage()); + return (ResponseEntity) ResponseEntity.badRequest().body("{message:" + e.getMessage() + "}"); + } catch (IOException e) { + // TODO Auto-generated catch block + logger.error(e.getMessage()); + return (ResponseEntity) ResponseEntity.badRequest().body("{message:" + e.getMessage() + "}"); + } + } + + public ResponseEntity performNSScale(ScaleDescriptor aScaleDescriptor) { + + DeploymentDescriptor deploymentdescriptor = aMANOClient + .getDeploymentByInstanceIdEager(aScaleDescriptor.getNsInstanceId()); + + ExperimentOnBoardDescriptor tmp = deploymentdescriptor.getObddescriptor_uuid(); + // Connect to OSM + OSMClient osmClient = null; + try { + logger.debug("Connecting to " + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " MANO Client of version " + tmp.getObMANOprovider().getSupportedMANOplatform().getVersion() + + "."); + osmClient = OSMClientFactory.getOSMClient(tmp.getObMANOprovider().getSupportedMANOplatform().getVersion(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getApiEndpoint(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getUsername(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getPassword(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getProject()); + // MANOStatus.setOsm5CommunicationStatusActive(null); + } catch (Exception e) { + logger.error("performNSScale, " + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " fails authentication! Aborting action on NS."); + centralLogger.log(CLevel.ERROR, + "performNSScale, " + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " fails authentication! Aborting action on NS.", + compname); + deploymentdescriptor.setFeedback((new Date()) + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " communication failed. Aborting action on NS. "); + deploymentdescriptor.setOperationalStatus((new Date()) + " communication-failure "); + deploymentdescriptor = aMANOClient.updateDeploymentDescriptor(deploymentdescriptor); + // aMANOClient.deploymentInstantiationFailed(deploymentdescriptor); + return (ResponseEntity) ResponseEntity.badRequest().body("{message:" + e.getMessage() + "}"); + } + + ANSScaleRequestPayload nsscalerequestpayload = new ANSScaleRequestPayload(); + nsscalerequestpayload.setScaleType(aScaleDescriptor.getScaleType()); + nsscalerequestpayload.setNsInstanceId(aScaleDescriptor.getNsInstanceId()); + nsscalerequestpayload.getScaleVnfData().getScaleByStepData() + .setMember_vnf_index(aScaleDescriptor.getMemberVnfIndex()); + nsscalerequestpayload.getScaleVnfData().getScaleByStepData() + .setScaling_group_descriptor(aScaleDescriptor.getScalingGroupDescriptor()); + + nsscalerequestpayload.getScaleVnfData().setScaleVnfType(aScaleDescriptor.getScaleVnfType()); + + // Apply the Action + ResponseEntity ns_scale_entity = osmClient.scaleNSInstance(deploymentdescriptor.getInstanceId(), + nsscalerequestpayload.toJSON()); + if (ns_scale_entity == null || ns_scale_entity.getStatusCode().is4xxClientError() + || ns_scale_entity.getStatusCode().is5xxServerError()) { + logger.error("NS Scale failed. Status Code:" + ns_scale_entity.getStatusCode().toString() + ", Payload:" + + ns_scale_entity.getBody().toString()); + } else { + // NS action starts + logger.info("NS scale of NS with id" + deploymentdescriptor.getInstanceId() + " started."); + // Save the changes to DeploymentDescriptor + logger.debug("NS scale Status Code:" + ns_scale_entity.getStatusCode().toString() + ", Payload:" + + ns_scale_entity.getBody().toString()); + } + // Get the response id or failure + return ns_scale_entity; + + } + + public ResponseEntity performNSInstanceScale(String nsscalerequestpayloadstring) { + // Deserialize input string as a NSScaleRequestPayload + ANSScaleRequestPayload nsscalerequestpayload; + try { + ObjectMapper mapper = new ObjectMapper(); + nsscalerequestpayload = mapper.readValue(nsscalerequestpayloadstring, ANSScaleRequestPayload.class); + + DeploymentDescriptor deploymentdescriptor = aMANOClient + .getDeploymentByInstanceIdEager(nsscalerequestpayload.getNsInstanceId()); + ExperimentOnBoardDescriptor tmp = deploymentdescriptor.getObddescriptor_uuid(); + // Connect to OSM + OSMClient osmClient = null; + try { + logger.debug("Connecting to " + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " MANO Client of version " + tmp.getObMANOprovider().getSupportedMANOplatform().getVersion() + + "."); + osmClient = OSMClientFactory.getOSMClient( + tmp.getObMANOprovider().getSupportedMANOplatform().getVersion(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getApiEndpoint(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getUsername(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getPassword(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getProject()); + // MANOStatus.setOsm5CommunicationStatusActive(null); + } catch (Exception e) { + logger.error("performNSInstanceScale, " + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " fails authentication! Aborting action on NS."); + centralLogger.log(CLevel.ERROR, + "performNSInstanceScale, " + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " fails authentication! Aborting action on NS.", + compname); + deploymentdescriptor + .setFeedback((new Date()) + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " communication failed. Aborting action on NS. "); + deploymentdescriptor.setOperationalStatus((new Date()) + " communication-failure "); + deploymentdescriptor = aMANOClient.updateDeploymentDescriptor(deploymentdescriptor); + // aMANOClient.deploymentInstantiationFailed(deploymentdescriptor); + return (ResponseEntity) ResponseEntity.badRequest().body("{message:" + e.getMessage() + "}"); + } + + // Apply the Action + ResponseEntity ns_scale_entity = osmClient.scaleNSInstance(deploymentdescriptor.getInstanceId(), + nsscalerequestpayload.toJSON()); + if (ns_scale_entity == null || ns_scale_entity.getStatusCode().is4xxClientError() + || ns_scale_entity.getStatusCode().is5xxServerError()) { + logger.error("NS Scale failed. Status Code:" + ns_scale_entity.getStatusCode().toString() + ", Payload:" + + ns_scale_entity.getBody().toString()); + } else { + // NS action starts + logger.info("NS scale of NS with id" + deploymentdescriptor.getInstanceId() + " started."); + // Save the changes to DeploymentDescriptor + logger.debug("NS scale Status Code:" + ns_scale_entity.getStatusCode().toString() + ", Payload:" + + ns_scale_entity.getBody().toString()); + } + // Get the response id or failure + return ns_scale_entity; + } catch (JsonParseException e) { + // TODO Auto-generated catch block + logger.error(e.getMessage()); + return (ResponseEntity) ResponseEntity.badRequest().body("{message:" + e.getMessage() + "}"); + } catch (JsonMappingException e) { + // TODO Auto-generated catch block + logger.error(e.getMessage()); + return (ResponseEntity) ResponseEntity.badRequest().body("{message:" + e.getMessage() + "}"); + } catch (IOException e) { + // TODO Auto-generated catch block + logger.error(e.getMessage()); + return (ResponseEntity) ResponseEntity.badRequest().body("{message:" + e.getMessage() + "}"); + } + } + + public ResponseEntity getNSLCMDetails(String nsactionid) { + return null; + } + + public void deployNSDToMANOProvider(long deploymentdescriptorid) { + logger.debug("Starting deployNSDToMANOProvicer"); + DeploymentDescriptor deploymentdescriptor = aMANOClient.getDeploymentByIdEager(deploymentdescriptorid); + logger.debug("Starting getExperimOBD"); + ExperimentOnBoardDescriptor tmp = deploymentdescriptor.getObddescriptor_uuid(); + logger.debug("The loaded obddescriptor contains:"+tmp.toJSON()); + logger.debug("Starting connection to osm"); + OSMClient osmClient = null; + try { + logger.debug("Connecting to " + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " MANO Client of version " + tmp.getObMANOprovider().getSupportedMANOplatform().getVersion() + + "."); + osmClient = OSMClientFactory.getOSMClient(tmp.getObMANOprovider().getSupportedMANOplatform().getVersion(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getApiEndpoint(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getUsername(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getPassword(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getProject()); + // MANOStatus.setOsm5CommunicationStatusActive(null); + } catch (Exception e) { + logger.error("deployNSDToMANOProvider, " + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " fails authentication! Aborting deployment of NSD."); + centralLogger.log(CLevel.ERROR, + "deployNSDToMANOProvider, " + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " fails authentication! Aborting deployment of NSD.", + compname); + // MANOStatus.setOsm5CommunicationStatusFailed(" Aborting deployment of NSD."); + // NS instance creation failed + // deploymentdescriptor.setStatus(DeploymentDescriptorStatus.FAILED); + deploymentdescriptor.setFeedback((new Date()) + tmp.getObMANOprovider().getSupportedMANOplatform().getName() + + " communication failed. Aborting NSD deployment action. "); + deploymentdescriptor.setOperationalStatus((new Date()) + " communication-failure "); + deploymentdescriptor = aMANOClient.updateDeploymentDescriptor(deploymentdescriptor); + // aMANOClient.deploymentInstantiationFailed(deploymentdescriptor); + return; + } + logger.debug("Connected to OSM"); + NSCreateInstanceRequestPayload nscreateinstancerequestpayload = null; + String nscreateinstancerequestpayload_json = null; + if (deploymentdescriptor.getInstantiationconfig() != null) { + nscreateinstancerequestpayload_json = deploymentdescriptor.getInstantiationconfig(); + logger.debug("Found and parsed instantiation configuration " + nscreateinstancerequestpayload_json); + } else { + logger.info("Could not find or parse instantiation configuration from user. Getting default configuration"); + nscreateinstancerequestpayload = new NSCreateInstanceRequestPayload(deploymentdescriptor); + nscreateinstancerequestpayload_json = nscreateinstancerequestpayload.toJSON(); + } + // Get Experiment ID and VIM ID and create NS Instance. + logger.info("NS Instance creation payload : " + nscreateinstancerequestpayload_json); + ResponseEntity ns_instance_creation_entity = osmClient + .createNSInstance(nscreateinstancerequestpayload_json); + // The NS Instance ID is set + + // NS instance creation + if (ns_instance_creation_entity == null || ns_instance_creation_entity.getStatusCode().is4xxClientError() + || ns_instance_creation_entity.getStatusCode().is5xxServerError()) { + // NS instance creation failed + deploymentdescriptor.setStatus(DeploymentDescriptorStatus.FAILED); + centralLogger.log(CLevel.INFO, "Status change of deployment1 " + deploymentdescriptor.getName() + " to " + + deploymentdescriptor.getStatus(), compname); + logger.info("Status change of deployment1 " + deploymentdescriptor.getName() + " to " + + deploymentdescriptor.getStatus()); + deploymentdescriptor.setFeedback(ns_instance_creation_entity.getBody().toString()); + DeploymentDescriptor deploymentdescriptor_final = aMANOClient + .updateDeploymentDescriptor(deploymentdescriptor); + aMANOClient.deploymentInstantiationFailed(deploymentdescriptor_final); + logger.error( + "NS Instance creation failed with response: " + ns_instance_creation_entity.getBody().toString()); + } else { + // String nsr_id = + // osm5Client.instantiateNSInstance(nsd_instance_id,deploymentdescriptor.getName(),deploymentdescriptor.getInfrastructureForAll().getVIMid(), + // deploymentdescriptor.getExperimentFullDetails().getExperimentOnBoardDescriptors().get(0).getDeployId()); + JSONObject ns_instance_creation_entity_json_obj = new JSONObject(ns_instance_creation_entity.getBody()); + String nsd_instance_id = ns_instance_creation_entity_json_obj.getString("id"); + deploymentdescriptor.setInstanceId(nsd_instance_id); + // Instantiate NS Instance + // NSInstantiateInstanceRequestPayload nsrequestpayload = new + // NSInstantiateInstanceRequestPayload(deploymentdescriptor); + // logger.debug("NS Instantiation payload : " + nsrequestpayload.toJSON()); + + NSInstantiateInstanceRequestPayload nsrequestpayload = null; + String nsrequestpayload_json = null; + if (deploymentdescriptor.getInstantiationconfig() != null) { + nsrequestpayload_json = deploymentdescriptor.getInstantiationconfig(); + logger.debug("Found and parsed instantiation configuration " + nsrequestpayload_json); + } else { + logger.info( + "Could not find or parse instantiation configuration from user. Getting default configuration"); + nsrequestpayload = new NSInstantiateInstanceRequestPayload(deploymentdescriptor); + nsrequestpayload_json = nscreateinstancerequestpayload.toJSON(); + } + // Get Experiment ID and VIM ID and create NS Instance. + logger.debug("NS Instance creation payload : " + nsrequestpayload_json); + + // Here we need the feedback + // String nsr_id = osm5Client.instantiateNSInstance(nsd_instance_id, + // nsrequestpayload.toJSON()); + ResponseEntity instantiate_ns_instance_entity = osmClient.instantiateNSInstance(nsd_instance_id, + nsrequestpayload_json); + if (instantiate_ns_instance_entity == null + || instantiate_ns_instance_entity.getStatusCode().is4xxClientError() + || instantiate_ns_instance_entity.getStatusCode().is5xxServerError()) { + // NS Instantiation failed + deploymentdescriptor.setStatus(DeploymentDescriptorStatus.FAILED); + centralLogger.log(CLevel.INFO, "Status change of deployment1 " + deploymentdescriptor.getName() + " to " + + deploymentdescriptor.getStatus(), compname); + logger.info("Status change of deployment1 " + deploymentdescriptor.getName() + " to " + + deploymentdescriptor.getStatus()); + deploymentdescriptor.setFeedback(instantiate_ns_instance_entity.getBody().toString()); + logger.error("NS Instantiation failed. Status Code:" + + instantiate_ns_instance_entity.getStatusCode().toString() + ", Payload:" + + ns_instance_creation_entity.getBody().toString()); + // Save the changes to DeploymentDescriptor + DeploymentDescriptor deploymentdescriptor_final = aMANOClient + .updateDeploymentDescriptor(deploymentdescriptor); + aMANOClient.deploymentInstantiationFailed(deploymentdescriptor_final); + } else { + // NS Instantiation starts + JSONObject instantiate_ns_instance_entity_json_obj = new JSONObject( + instantiate_ns_instance_entity.getBody()); + deploymentdescriptor.setNsLcmOpOccId(instantiate_ns_instance_entity_json_obj.getString("id")); + deploymentdescriptor.setStatus(DeploymentDescriptorStatus.INSTANTIATING); + centralLogger.log(CLevel.INFO, "Status change of deployment1 " + deploymentdescriptor.getName() + " to " + + deploymentdescriptor.getStatus(), compname); + logger.info("Status change of deployment1 " + deploymentdescriptor.getName() + " to " + + deploymentdescriptor.getStatus()); + deploymentdescriptor.setFeedback(instantiate_ns_instance_entity.getBody().toString()); + logger.info("NS Instantiation of NS with id" + nsd_instance_id + " started."); + // Save the changes to DeploymentDescriptor + aMANOClient.updateDeploymentDescriptor(deploymentdescriptor); + // aMANOClient.deploymentInstantiationSucceded(deploymentdescriptor_final ); + } + } + return; + } + + public void terminateNSFromMANOProvider(long deploymentdescriptorid) { + logger.info("Starting terminateNSFromMANOProvicer"); + DeploymentDescriptor deploymentdescriptor = aMANOClient.getDeploymentByIdEager(deploymentdescriptorid); + + logger.info("Current status change before termination is :" + deploymentdescriptor.getStatus()); + if (deploymentdescriptor.getStatus() == DeploymentDescriptorStatus.INSTANTIATING + || deploymentdescriptor.getStatus() == DeploymentDescriptorStatus.RUNNING + || deploymentdescriptor.getStatus() == DeploymentDescriptorStatus.FAILED) { + try { + MANOprovider tmpMANOProvider = deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider(); + OSMClient osmClient = OSMClientFactory.getOSMClient( + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getSupportedMANOplatform().getVersion(), + tmpMANOProvider.getApiEndpoint(), tmpMANOProvider.getUsername(), tmpMANOProvider.getPassword(), + tmpMANOProvider.getProject()); + + ResponseEntity response = osmClient + .terminateNSInstanceNew(deploymentdescriptor.getInstanceId()); + if (response == null || response.getStatusCode().is4xxClientError() + || response.getStatusCode().is5xxServerError()) { + deploymentdescriptor.setStatus(DeploymentDescriptorStatus.TERMINATION_FAILED); + centralLogger.log(CLevel.ERROR, "Status change of deployment1 " + deploymentdescriptor.getName() + + " to " + deploymentdescriptor.getStatus(), compname); + logger.info("Status change of deployment1 " + deploymentdescriptor.getName() + " to " + + deploymentdescriptor.getStatus()); + deploymentdescriptor.setFeedback(response.getBody().toString()); + logger.error("Termination of NS instance " + deploymentdescriptor.getInstanceId() + " failed"); + DeploymentDescriptor deploymentdescriptor_final = aMANOClient + .updateDeploymentDescriptor(deploymentdescriptor); + logger.info("NS status change is now " + deploymentdescriptor_final.getStatus()); + aMANOClient.terminateInstanceFailed(deploymentdescriptor_final); + } else { + // NS Termination succeeded + deploymentdescriptor.setStatus(DeploymentDescriptorStatus.TERMINATING); + centralLogger.log(CLevel.INFO, "Status change of deployment1 " + deploymentdescriptor.getName() + + " to " + deploymentdescriptor.getStatus(), compname); + logger.info("Status change of deployment1 " + deploymentdescriptor.getName() + " to " + + deploymentdescriptor.getStatus()); + deploymentdescriptor.setConstituentVnfrIps("N/A"); + logger.info("Termination of NS " + deploymentdescriptor.getInstanceId() + " with name " + + deploymentdescriptor.getName() + " succeded"); + DeploymentDescriptor deploymentdescriptor_final = aMANOClient + .updateDeploymentDescriptor(deploymentdescriptor); + logger.info("NS status change is now " + deploymentdescriptor_final.getStatus()); + aMANOClient.terminateInstanceSucceded(deploymentdescriptor_final); + } + } catch (Exception e) { + centralLogger.log(CLevel.ERROR, + "terminateNSFromMANOProvider, " + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider() + .getSupportedMANOplatform().getName() + " fails authentication. Aborting action.", + compname); + } + } + } + + public void deleteNSFromMANOProvider(long deploymentdescriptorid) { + DeploymentDescriptor deploymentdescriptor = aMANOClient.getDeploymentByIdEager(deploymentdescriptorid); + + logger.info("Will delete with deploymentdescriptorid : " + deploymentdescriptorid); + String aMANOplatform = ""; + try { + logger.debug("MANOplatform: " + aMANOplatform); + aMANOplatform = deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getSupportedMANOplatform().getVersion(); + } catch (Exception e) { + aMANOplatform = "UNKNOWN"; + } + if (OSMClientFactory.isOSMVersionSupported(aMANOplatform)) { + logger.info( + "Descriptor targets an " + aMANOplatform + " deploymentdescriptorid: " + deploymentdescriptorid); + // There can be multiple MANOs for the Experiment. We need to handle that also. + // After TERMINATION + boolean force = false; + + if ( deploymentdescriptor.getStatus() == DeploymentDescriptorStatus.TERMINATED + || deploymentdescriptor.getStatus() == DeploymentDescriptorStatus.FAILED + || deploymentdescriptor.getStatus() == DeploymentDescriptorStatus.TERMINATION_FAILED ) // for FAILED + // OR + // TERMINATION_FAILED + // instances + { + centralLogger.log(CLevel.INFO, "Following forcefull deletion. Status of " + deploymentdescriptor.getId() + + " is " + deploymentdescriptor.getStatus(), compname); + logger.info("Following forcefull deletion. Status of " + deploymentdescriptor.getId() + " is " + + deploymentdescriptor.getStatus()); + force = false; + /** + * ctranoris: changed on 20210324 making force always false. + */ + } else { + logger.info("Skipping deletion. Status of " + deploymentdescriptor.getId() + " is " + + deploymentdescriptor.getStatus()); + return; + } + OSMClient osmClient = null; + try { + osmClient = OSMClientFactory.getOSMClient(aMANOplatform, + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getApiEndpoint(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getUsername(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getPassword(), + deploymentdescriptor.getObddescriptor_uuid().getObMANOprovider().getProject()); + // MANOStatus.setOsm5CommunicationStatusActive(null); + } catch (Exception e) { + logger.error(aMANOplatform + " fails authentication"); + // MANOStatus.setOsm5CommunicationStatusFailed(" Aborting NS deletion action."); + centralLogger.log(CLevel.ERROR, aMANOplatform + " fails authentication", compname); + deploymentdescriptor.setFeedback(aMANOplatform + " communication failed. Aborting NS deletion action."); + logger.error("Deletion of NS instance " + deploymentdescriptor.getInstanceId() + " failed"); + aMANOClient.deleteInstanceFailed(deploymentdescriptor); + return; + } + ResponseEntity deletion_response = osmClient + .deleteNSInstanceNew(deploymentdescriptor.getInstanceId(), force); + if (deletion_response.getStatusCode().is4xxClientError() + || deletion_response.getStatusCode().is5xxServerError()) { + deploymentdescriptor.setStatus(DeploymentDescriptorStatus.DELETION_FAILED); + centralLogger.log(CLevel.INFO, "Status change of deployment1 " + deploymentdescriptor.getName() + " to " + + deploymentdescriptor.getStatus(), compname); + logger.info("Status change of deployment1 " + deploymentdescriptor.getName() + " to " + + deploymentdescriptor.getStatus()); + deploymentdescriptor.setFeedback(deletion_response.getBody().toString()); + logger.error("Deletion of NS instance " + deploymentdescriptor.getInstanceId() + " failed"); + DeploymentDescriptor deploymentdescriptor_final = aMANOClient + .updateDeploymentDescriptor(deploymentdescriptor); + logger.info("NS status change is now " + deploymentdescriptor_final.getStatus()); + aMANOClient.deleteInstanceFailed(deploymentdescriptor_final); + } else if (deletion_response.getStatusCode().is2xxSuccessful()) { + if (deploymentdescriptor.getStatus() == DeploymentDescriptorStatus.TERMINATED) { + deploymentdescriptor.setStatus(DeploymentDescriptorStatus.COMPLETED); + centralLogger.log(CLevel.INFO, "Status change of deployment1 " + deploymentdescriptor.getName() + + " to " + deploymentdescriptor.getStatus(), compname); + logger.info("Status change of deployment1 " + deploymentdescriptor.getName() + " to " + + deploymentdescriptor.getStatus()); + logger.info("Deletion of NS instance " + deploymentdescriptor.getInstanceId() + " succeded"); + DeploymentDescriptor deploymentdescriptor_final = aMANOClient + .updateDeploymentDescriptor(deploymentdescriptor); + logger.info("NS status change is now " + deploymentdescriptor_final.getStatus()); + aMANOClient.deleteInstanceSucceded(deploymentdescriptor_final); + } + if (deploymentdescriptor.getStatus() == DeploymentDescriptorStatus.FAILED + || deploymentdescriptor.getStatus() == DeploymentDescriptorStatus.TERMINATION_FAILED) { + deploymentdescriptor.setStatus(DeploymentDescriptorStatus.FAILED_OSM_REMOVED); + centralLogger.log(CLevel.INFO, "Status change of deployment1 " + deploymentdescriptor.getName() + + " to " + deploymentdescriptor.getStatus(), compname); + logger.info("Status change of deployment1 " + deploymentdescriptor.getName() + " to " + + deploymentdescriptor.getStatus()); + logger.info("Deletion of NS instance " + deploymentdescriptor.getInstanceId() + " succeeded"); + DeploymentDescriptor deploymentdescriptor_final = aMANOClient + .updateDeploymentDescriptor(deploymentdescriptor); + logger.info("NS status change is now " + deploymentdescriptor_final.getStatus()); + aMANOClient.deleteInstanceSucceded(deploymentdescriptor_final); + } + } else { + try { + centralLogger.log(CLevel.ERROR, + "Status change of deployment1 " + deploymentdescriptor.getName() + " to " + + deploymentdescriptor.getStatus() + " replied with false code " + + deletion_response.getStatusCodeValue() + "and body" + deletion_response.getBody(), + compname); + logger.error("Status change of deployment1 " + deploymentdescriptor.getName() + " to " + + deploymentdescriptor.getStatus() + " replied with false code " + + deletion_response.getStatusCodeValue() + "and body" + deletion_response.getBody()); + } catch (Exception e) { + centralLogger.log(CLevel.ERROR, "Deletion failed with message" + e.getMessage(), compname); + logger.error("Deletion failed with message" + e.getMessage()); + } + } + } else { + // if this is not a supported 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 deployment1 " + deploymentdescriptor.getId() + ", " + + deploymentdescriptor.getName() + " to " + deploymentdescriptor.getStatus()); + DeploymentDescriptor deploymentdescriptor_final = aMANOClient + .updateDeploymentDescriptor(deploymentdescriptor); + logger.info("NS status changed is now :" + deploymentdescriptor_final.getStatus()); + } + } + + + + + public String mapOSM10VNFD2ProductEagerDataJson(String yamlFile) throws JsonProcessingException { + VxFMetadata vxfMetadata = this.mapOSM10VNFD2Product(yamlFile); + ObjectMapper mapper = new ObjectMapper(); + String res = mapper.writeValueAsString(vxfMetadata); + + return res; + } + + + + public String mapOSM10NSD2ProductEagerDataJson(String yamlFile) throws JsonProcessingException { + ExperimentMetadata vxfMetadata = this.mapOSM10NSD2Product(yamlFile); + ObjectMapper mapper = new ObjectMapper(); + String res = mapper.writeValueAsString(vxfMetadata); + + return res; + } + + + + public ExperimentMetadata mapOSM10NSD2Product(String yamlFile) { + ExperimentMetadata prod = new ExperimentMetadata(); + + // Get the nsd object out of the file info + org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Nsd ns; + try { + // We need to provide different implementations for each OSM version as this + // maps to a different version of NSD model. + ns = OSM10NSExtractor.extractNsdDescriptorFromYAMLFile(yamlFile); + + prod.setName(ns.getName()); + prod.setVersion(ns.getVersion()); + prod.setVendor(ns.getDesigner()); + prod.setShortDescription(ns.getName()); + prod.setLongDescription(ns.getName()); + + for (Df v : ns.getDf().values()) { + for( VnfProfile q : v.getVnfProfile().values()) + { + ConstituentVxF cvxf = new ConstituentVxF(); + // Here we try to convert the id to int. + cvxf.setMembervnfIndex(q.getId()); + cvxf.setVnfdidRef((String) q.getVnfdId()); + VxFMetadata vxf = (VxFMetadata) aMANOClient.getVxFByName((String) q.getVnfdId()); + cvxf.setVxfref(vxf); + ((ExperimentMetadata) prod).getConstituentVxF().add(cvxf); + } + } + + // Get NS Requirements from the nsd + OSM10NSRequirements vr = new OSM10NSRequirements(ns); + // Store the requirements in HTML + prod.setDescriptorHTML(vr.toHTML()); + // Store the YAML file + prod.setDescriptor(yamlFile); + prod.setIconsrc(""); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return prod; + } + + + + + public VxFMetadata mapOSM10VNFD2Product(String yamlFile) { + VxFMetadata prod = new VxFMetadata(); + // Get the vnfd object out of the file info + org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.Vnfd vnfd; + try { + // We need to provide different implementations for each OSM version as this + // maps to a different version of VNFD model. + vnfd = OSM10VNFDExtractor.extractVnfdDescriptorFromYAMLFile(yamlFile); + if (vnfd == null) { + logger.error("Cannot read Descriptor from YAML file:" + yamlFile); + return null; + } + // Get the name for the db + prod.setName(vnfd.getProductName()); + prod.setVersion(vnfd.getVersion()); + prod.setVendor(vnfd.getProvider()); + prod.setShortDescription(vnfd.getProductName()); + prod.setLongDescription(vnfd.getProductInfoDescription()); + + ((VxFMetadata) prod).setValidationStatus(ValidationStatus.UNDER_REVIEW); + ((VxFMetadata) prod).getVfimagesVDU().clear();// clear previous referenced images + if(vnfd.getVdu() != null) + { + for (org.opendaylight.yang.gen.v1.urn.etsi.nfv.yang.etsi.nfv.descriptors.rev190425.vnfd.Vdu vdu : vnfd.getVdu().values()) { + String imageName = vdu.getSwImageDesc(); + if ((imageName != null) && (!imageName.equals(""))) { + VFImage sm = new VFImage(); + sm.setName(imageName); + ((VxFMetadata) prod).getVfimagesVDU().add(sm); + } + } + } + // Get VNF Requirements from the vnfd + OSM10VNFRequirements vr = new OSM10VNFRequirements(vnfd); + // Store the requirements in HTML + prod.setDescriptorHTML(vr.toHTML()); + // Store the YAML file + prod.setDescriptor(yamlFile); + + prod.setIconsrc(""); + } catch (IOException e) { + logger.error("Cannot read Descriptor from YAML file:" + yamlFile); + e.printStackTrace(); + return null; + } + return prod; + } + + public void getScaleAlert(String body) + { + logger.info("Scaling message received with body"); + } + + + +} diff --git a/src/main/java/org/etsi/osl/mano/MANORouteBuilder.java b/src/main/java/org/etsi/osl/mano/MANORouteBuilder.java new file mode 100644 index 0000000..e902b9f --- /dev/null +++ b/src/main/java/org/etsi/osl/mano/MANORouteBuilder.java @@ -0,0 +1,283 @@ +/*- + * ========================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 org.etsi.osl.mano; + +import org.apache.camel.CamelContext; +import org.apache.camel.LoggingLevel; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.model.dataformat.JsonLibrary; +import org.json.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Component; + +import org.etsi.osl.model.ScaleDescriptor; +import org.etsi.osl.model.VxFOnBoardedDescriptor; + +/** + * @author ctranoris + * + */ +@Component +@Configuration +public class MANORouteBuilder extends RouteBuilder{ + + + @Autowired + MANOController aMANOController; + + + @Value("${NFV_CATALOG_NSACTIONS_SCALE}") + private String NFV_CATALOG_NSACTIONS_SCALE =""; + + + 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 +// 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!"); + +//********************************************************************************************** +// THESE NOW ARE CALLED DIRECTLY AND ARE NOT REQUIRED ANY MORE 26122019 +// 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!"+"${exception.message}").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://checkAndUpdateRunningDeploymentDescriptors?delay=1s&period=60000").bean( aMANOController,"checkAndUpdateRunningDeploymentDescriptors").stop(); +// from("timer://checkAndUpdateMANOProvidersResources?delay=1s&period=60000").bean( aMANOController,"checkAndUpdateMANOProvidersResources").stop(); + + // THESE SEND THE DeploymentDescriptor Object to Bugzilla for status updates + // Here we needed to add getDeploymentEagerDataJson from portal.api.service.DeploymentDescriptorService + // in order to create the marshalling + from("seda:nsd.deployment.instantiation.success?multipleConsumers=true") + .marshal().json( JsonLibrary.Jackson, true) + .convertBodyTo( String.class ) + .to( "activemq:topic:nsd.deployment.instantiation.success" ); + + from("seda:nsd.deployment.instantiation.fail?multipleConsumers=true") + .marshal().json( JsonLibrary.Jackson, true) + .convertBodyTo( String.class ) + .to( "activemq:topic:nsd.deployment.instantiation.fail" ); + + from("seda:nsd.deployment.termination.success?multipleConsumers=true") + .marshal().json( JsonLibrary.Jackson, true) + .convertBodyTo( String.class ) + .to( "activemq:topic:nsd.deployment.termination.success" ); + + from("seda:nsd.deployment.termination.fail?multipleConsumers=true") + .marshal().json( JsonLibrary.Jackson, true) + .convertBodyTo( String.class ) + .to( "activemq:topic:nsd.deployment.termination.fail" ); + + from("seda:vxf.onboard.success?multipleConsumers=true") + .marshal().json( JsonLibrary.Jackson, VxFOnBoardedDescriptor.class, true) + .convertBodyTo( String.class ) + .to( "activemq:topic:vxf.onboard.success" ); + + from("activemq:topic:vxf.onboard") + .log( "activemq:topic:vxf.onboard for ${body} !" ) + .unmarshal().json( JsonLibrary.Jackson, org.etsi.osl.model.VxFOnBoardedDescriptor.class, true) + .bean( aMANOController, "onBoardVxFToMANOProviderByOBD" ) + .to("log:DEBUG?showBody=true&showHeaders=true"); + + from("activemq:topic:vxf.onboardbyfile") + .log( "activemq:topic:vxf.onboardbyfile for ${body} !" ) + .unmarshal().json( JsonLibrary.Jackson, org.etsi.osl.model.VxFOnBoardedDescriptor.class, true) + .bean( aMANOController, "onBoardVxFToMANOProviderByFile" ) + .to("log:DEBUG?showBody=true&showHeaders=true"); + + from("activemq:topic:vxf.onBoardByCompositeObj") + .log( "activemq:topic:vxf.onBoardByCompositeObj for ${body} !" ) + .unmarshal().json( JsonLibrary.Jackson, org.etsi.osl.model.CompositeVxFOnBoardDescriptor.class, true) + .bean( aMANOController, "onBoardVxFToMANOProviderByCompositeObj" ) + .to("log:DEBUG?showBody=true&showHeaders=true"); + + from("activemq:topic:vxf.offboard") + .log( "activemq:topic:vxf.offboard for ${body} !" ) + .unmarshal().json( JsonLibrary.Jackson, org.etsi.osl.model.VxFOnBoardedDescriptor.class, true) + .doTry() + .bean( aMANOController, "offBoardVxFFromMANOProvider" ) //Replies with a ResponseInstance + .marshal().json( JsonLibrary.Jackson, true) + .convertBodyTo(String.class) + .log("offboarding ok with ${body}") + .doCatch(Exception.class) + .setBody(exceptionMessage()) + .log("offboard failed with exception ${body}") + .end(); + + from("activemq:topic:nsd.onboardbyfile") + .log( "activemq:topic:nsd.onboardbyfile for ${body} !" ) + .unmarshal().json( JsonLibrary.Jackson, org.etsi.osl.model.ExperimentOnBoardDescriptor.class, true) + .bean( aMANOController, "onBoardNSDToMANOProviderByFile" ) + .to("log:DEBUG?showBody=true&showHeaders=true"); + + from("activemq:topic:nsd.onBoardByCompositeObj") + .log( "activemq:topic:nsd.onBoardByCompositeObj for ${body} !" ) + .unmarshal().json( JsonLibrary.Jackson, org.etsi.osl.model.CompositeExperimentOnBoardDescriptor.class, true) + .bean( aMANOController, "onBoardNSDToMANOProviderByCompositeObj" ) + .to("log:DEBUG?showBody=true&showHeaders=true"); + + from("activemq:topic:nsd.onboard") + .log( "activemq:topic:nsd.onboard for ${body} !" ) + .unmarshal().json( JsonLibrary.Jackson, org.etsi.osl.model.ExperimentOnBoardDescriptor.class, true) + .bean( aMANOController, "onBoardNSDToMANOProvider" ) + .to("log:DEBUG?showBody=true&showHeaders=true"); + + from("activemq:topic:nsd.offboard") + .log( "activemq:topic:nsd.offboard for ${body} !" ) + .unmarshal().json( JsonLibrary.Jackson, org.etsi.osl.model.ExperimentOnBoardDescriptor.class, true) + .doTry() + .bean( aMANOController, "offBoardNSDFromMANOProvider" ) //Replies with a ResponseInstance + .marshal().json( JsonLibrary.Jackson, true) + .convertBodyTo(String.class) + .log("offboarding ok with ${body}") + .doCatch(Exception.class) + .setBody(exceptionMessage()) + .log("offboard failed with exception ${body}") + .end(); + + + from("activemq:topic:vxf.metadata.retrieve") + .log("activemq:topic:vxf.metadata.retrieve") + .choice() + .when(header("OSMType").isEqualTo("OSMvTEN")) + .bean(aMANOController, "mapOSM10VNFD2ProductEagerDataJson") + .when(header("OSMType").isEqualTo("OSMvELEVEN")) + .bean(aMANOController, "mapOSM10VNFD2ProductEagerDataJson") + .when(header("OSMType").isEqualTo("OSMvTHIRTEEN")) + .bean(aMANOController, "mapOSM10VNFD2ProductEagerDataJson"); + //.when(header("OSMType").isEqualTo("GenericSOL005")) + // .bean(aMANOController, "mapOSM7VNFD2ProductEagerDataJson"); + + from("activemq:topic:ns.metadata.retrieve") + .log("activemq:topic:ns.metadata.retrieve") + .choice() + .when(header("OSMType").isEqualTo("OSMvTEN")) + .bean(aMANOController, "mapOSM10NSD2ProductEagerDataJson") + .when(header("OSMType").isEqualTo("OSMvELEVEN")) + .bean(aMANOController, "mapOSM10NSD2ProductEagerDataJson") + .when(header("OSMType").isEqualTo("OSMvTHIRTEEN")) + .bean(aMANOController, "mapOSM10NSD2ProductEagerDataJson"); + //.when(header("OSMType").isEqualTo("GenericSOL005")) + // .bean(aMANOController, "mapOSM7NSD2ProductEagerDataJson"); + + from("jms:queue:ns.action.run") + .log("jms:queue:ns.action.run") + .convertBodyTo( String.class ) + .bean(aMANOController, "performNSInstanceAction") + .marshal().json( JsonLibrary.Jackson, true) + .convertBodyTo(String.class) + .log("action run ok with ${body}"); + + from("jms:queue:ns.scale.run") + .log("jms:queue:ns.scale.run") + .convertBodyTo( String.class ) + .bean(aMANOController, "performNSInstanceScale") + .marshal().json( JsonLibrary.Jackson, true) + .convertBodyTo(String.class) + .log("scale operation run ok with ${body}"); + + + from( NFV_CATALOG_NSACTIONS_SCALE ) + .log(LoggingLevel.INFO, log, NFV_CATALOG_NSACTIONS_SCALE + " message received!") + .to("log:DEBUG?showBody=true&showHeaders=true") + .unmarshal() + .json( JsonLibrary.Jackson, ScaleDescriptor.class, true) + .bean(aMANOController, "performNSScale") + .convertBodyTo(String.class); + + + + + + from("activemq:topic:ns.action.getnslcmdetails") + .log("activemq:topic:ns.action.getnslcmdetails") + .convertBodyTo( String.class ) + .bean(aMANOController, "getNSLCMDetails") + .convertBodyTo(JSONObject.class) + .log("action run ok with ${body}"); + + from("activemq:queue:ns.scalealert") + .convertBodyTo( String.class ) + .bean(aMANOController, "getScaleAlertMessageBody"); + + } +} diff --git a/src/main/java/org/etsi/osl/mano/MANOService.java b/src/main/java/org/etsi/osl/mano/MANOService.java new file mode 100644 index 0000000..a290ecc --- /dev/null +++ b/src/main/java/org/etsi/osl/mano/MANOService.java @@ -0,0 +1,54 @@ +/*- + * ========================LICENSE_START================================= + * org.etsi.osl.bugzilla + * %% + * 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 org.etsi.osl.mano; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.ComponentScan; + + +/** + * @author ichatzis + * + * based on + * https://github.com/apache/camel/tree/master/examples/camel-example-spring-boot-activemq + * https://github.com/indrabasak/spring-consul-example + */ +// This is equivalent to @Configuration, @EnableAutoConfiguration, and @ComponentScan +@SpringBootApplication +// This annotation is used for consul +//@EnableRetry +// This is from spring-cloud to allow local configuration application +// @EnableAutoConfiguration annotation tells Spring Boot to "guess" how you will want to configure Spring, +// based on the jar dependencies that you have added. For example, If HSQLDB is on your classpath, and you +// have not manually configured any database connection beans, then Spring will auto-configure an in-memory database. +@EnableAutoConfiguration +// This is enabled by default +@EnableConfigurationProperties +@ComponentScan(basePackages = { + "org.etsi.osl.mano", + "org.etsi.osl.centrallog.client" }) +public class MANOService { + public static void main(String[] args) { + SpringApplication.run( MANOService.class, args); + } +} \ No newline at end of file diff --git a/src/main/java/org/etsi/osl/mano/MANOStatus.java b/src/main/java/org/etsi/osl/mano/MANOStatus.java new file mode 100644 index 0000000..9adf3b8 --- /dev/null +++ b/src/main/java/org/etsi/osl/mano/MANOStatus.java @@ -0,0 +1,141 @@ +package org.etsi.osl.mano; +///*- +// * ========================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 org.etsi.osl.mano; +//import java.util.UUID; +//import portal.api.bus.BusController; +// +///** +// * @author ctranoris +// * +// */ +//public class MANOStatus +//{ +// //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 static 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.getInstance().osm5CommunicationFailed(MANOStatus.class); +// } +// } finally { +// lock.writeLock().unlock(); +// } +// } +// +// +// +// public static 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.getInstance().osm5CommunicationRestored(MANOStatus.class); +// } +// } finally { +// lock.writeLock().unlock(); +// } +// } +//} +// diff --git a/src/main/java/org/etsi/osl/mano/NSCreateInstanceRequestPayload.java b/src/main/java/org/etsi/osl/mano/NSCreateInstanceRequestPayload.java new file mode 100644 index 0000000..3331042 --- /dev/null +++ b/src/main/java/org/etsi/osl/mano/NSCreateInstanceRequestPayload.java @@ -0,0 +1,40 @@ +/*- + * ========================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 org.etsi.osl.mano; + +import org.etsi.osl.model.DeploymentDescriptor; + +/** + * @author ctranoris + * + */ +public class NSCreateInstanceRequestPayload extends NSInstantiateInstanceRequestPayload +{ + //public String notificationType="NsIdentifierCreationNotification"; + + + public NSCreateInstanceRequestPayload(DeploymentDescriptor deploymentdescriptor) + { + super(deploymentdescriptor); + } +} + diff --git a/src/main/java/org/etsi/osl/mano/NSInstantiateInstanceRequestPayload.java b/src/main/java/org/etsi/osl/mano/NSInstantiateInstanceRequestPayload.java new file mode 100644 index 0000000..7140dd3 --- /dev/null +++ b/src/main/java/org/etsi/osl/mano/NSInstantiateInstanceRequestPayload.java @@ -0,0 +1,129 @@ +/*- + * ========================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 org.etsi.osl.mano; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.etsi.osl.model.DeploymentDescriptor; +import org.etsi.osl.model.DeploymentDescriptorVxFPlacement; +import org.etsi.osl.model.ExperimentOnBoardDescriptor; + +/** + * @author ctranoris + * + */ +public class NSInstantiateInstanceRequestPayload { + public String nsName; + public String vimAccountId; + public String nsdId; + public List vnf = new ArrayList<>(); + //private List vld = null; //new ArrayList<>(); + + class VnF { + @JsonProperty("member-vnf-index") + public String memberVnFIndex; + @JsonProperty("vimAccountId") + public String vimAccount; + } + + class Vld + { + @JsonProperty("name") + private String name; + @JsonProperty("vim-network-name") + private LinkedHashMap vimNetworkName = new LinkedHashMap<>(); + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public LinkedHashMap getVimNetworkName() { + return vimNetworkName; + } + public void setVimNetworkName(LinkedHashMap vimNetworkName) { + this.vimNetworkName = vimNetworkName; + } + } + +// public List getVld() { +// return vld; +// } +// +// public void setVld(List vld) { +// this.vld = vld; +// } + + public NSInstantiateInstanceRequestPayload(DeploymentDescriptor deploymentdescriptor) { + this.nsName = deploymentdescriptor.getName(); + this.vimAccountId = deploymentdescriptor.getInfrastructureForAll().getVIMid(); + // Here we need to get the ExperimentOnBoardDescriptor based on the Experiment. + // An Experiment might have multiple OnBoardDescriptors if it is OnBoarded to + // multiple OSM MANOs. + // We temporarily select the first (and most probably the only one). + // Otherwise the user needs to define the OSM MANO where the Experiment is + // OnBoarded in order to instantiate. + this.nsdId = deploymentdescriptor.getObddescriptor_uuid().getDeployId(); + + Integer count = 1; + for (DeploymentDescriptorVxFPlacement tmp : deploymentdescriptor.getVxfPlacements()) { + VnF vnf_tmp = new VnF(); + vnf_tmp.memberVnFIndex = tmp.getConstituentVxF().getMembervnfIndex(); + vnf_tmp.vimAccount = tmp.getInfrastructure().getVIMid(); + this.vnf.add(vnf_tmp); + count++; + } + } + + private ExperimentOnBoardDescriptor getExperimOBD(DeploymentDescriptor deployment_tmp) { + + for (ExperimentOnBoardDescriptor e : deployment_tmp.getExperimentFullDetails() + .getExperimentOnBoardDescriptors()) { + + return e; // return the first one found + } + return null; + } + + public String toJSON() + { + String jsonInString=null; + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_NULL); + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this); + } catch (JsonProcessingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return jsonInString; + } + +} diff --git a/src/main/java/org/etsi/osl/mano/OSMClientFactory.java b/src/main/java/org/etsi/osl/mano/OSMClientFactory.java new file mode 100644 index 0000000..cce8c16 --- /dev/null +++ b/src/main/java/org/etsi/osl/mano/OSMClientFactory.java @@ -0,0 +1,79 @@ +/*- + * ========================LICENSE_START================================= + * org.etsi.osl.manoclient + * %% + * Copyright (C) 2019 - 2020 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 org.etsi.osl.mano; + +import java.io.File; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.HttpStatusCodeException; + +import OSM10NBIClient.OSM10Client; +import OSM10Util.OSM10ArchiveExtractor.OSM10NSExtractor; +import org.etsi.osl.sol005nbi.OSMClient; +import org.etsi.osl.sol005nbi.OSMUtil.OSMNSExtractor; + +@Configuration +public class OSMClientFactory { + + public static OSMClient getOSMClient(String type,String apiEndpoint, String username, String password, String project_id) throws HttpStatusCodeException + { + String tokenEndpoint = "https://10.10.10.41:9999/osm/admin/v1/tokens/"; + String basePath = "/vnfpkgm/v1"; + + switch(type) + { + + case "OSMvTEN": + return new OSM10Client(apiEndpoint,username,password,project_id); + case "OSMvELEVEN": + return new OSM10Client(apiEndpoint,username,password,project_id); + + } + return new OSM10Client(apiEndpoint,username,password,project_id); + } + + public static OSMNSExtractor getOSMNSExtractor(String type,File NSDescriptorFile) + { + switch(type) + { + + case "OSMvTEN": + return new OSM10NSExtractor(NSDescriptorFile); + case "OSMvELEVEN": + return new OSM10NSExtractor(NSDescriptorFile); + case "OSMvTHIRTEEN": + return new OSM10NSExtractor(NSDescriptorFile); + } + return new OSM10NSExtractor(NSDescriptorFile); + } + + public static Boolean isOSMVersionSupported(String type) + { + switch(type) + { + case "OSMvTEN": + return true; + case "OSMvELEVEN": + return true; + case "OSMvTHIRTEEN": + return true; + } + return false; + } +} diff --git a/src/main/java/org/etsi/osl/mano/VIMCreateRequestPayload.java b/src/main/java/org/etsi/osl/mano/VIMCreateRequestPayload.java new file mode 100644 index 0000000..0b4d9d9 --- /dev/null +++ b/src/main/java/org/etsi/osl/mano/VIMCreateRequestPayload.java @@ -0,0 +1,118 @@ +package org.etsi.osl.mano; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class VIMCreateRequestPayload { + private String _id; + private String schema_version; + private String schema_type; + private String name; + private String description; + private String vim; + private String datacenter; + private String vim_type; + private String vim_url; + private String vim_tenant_name; + private String vim_user; + private String vim_password; + //private String config; + + public String getSchema_version() { + return schema_version; + } + public void setSchema_version(String schema_version) { + this.schema_version = schema_version; + } + public String getSchema_type() { + return schema_type; + } + public void setSchema_type(String schema_type) { + this.schema_type = schema_type; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public String getVim() { + return vim; + } + public void setVim(String vim) { + this.vim = vim; + } + public String getDatacenter() { + return datacenter; + } + public void setDatacenter(String datacenter) { + this.datacenter = datacenter; + } + public String getVim_type() { + return vim_type; + } + public void setVim_type(String vim_type) { + this.vim_type = vim_type; + } + public String getVim_url() { + return vim_url; + } + public void setVim_url(String vim_url) { + this.vim_url = vim_url; + } + public String getVim_tenant_name() { + return vim_tenant_name; + } + public void setVim_tenant_name(String vim_tenant_name) { + this.vim_tenant_name = vim_tenant_name; + } + public String getVim_user() { + return vim_user; + } + public void setVim_user(String vim_user) { + this.vim_user = vim_user; + } + public String getVim_password() { + return vim_password; + } + public void setVim_password(String vim_password) { + this.vim_password = vim_password; + } +// public String getConfig() { +// return config; +// } +// public void setConfig(String config) { +// this.config = config; +// } + + public String toJSON() + { + String jsonInString=null; + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_NULL); + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this); + } catch (JsonProcessingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return jsonInString; + } + public String get_id() { + return _id; + } + public void set_id(String _id) { + this._id = _id; + } + + +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..521a6b9 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,65 @@ +keycloak-issuer: http://localhost/auth/realms/openslice + +server: + port: 13011 + + +logging: + level: + root: INFO + org.apache.camel.zipkin: INFO + org.apache.camel.spring.cloud: INFO + org.apache.camel: INFO + file: logs/application-debug.log + pattern: + console: "%d %-5level %logger %M %L: %msg%n" + file: "%d %-5level [%thread] %logger : %msg%n" + + +spring: + config: + activate: + on-profile: "default" + application: + name: mano-client-service + activemq: + brokerUrl: tcp://localhost:61616?jms.watchTopicAdvisories=false + user: artemis + password: artemis + pool: + enabled: true + max-connections: 100 + packages: + trust-all: true + security: + oauth2: + resourceserver: + jwt: + issuer-uri: ${keycloak-issuer} + +portaltitle: "openslice" +maindomain: "http://localhost:13000" +main_operations_product: "Openslice Operations" + +keycloak: + realm: openslice + auth-server-url: http://localhost/auth + ssl-required: none + resource: admin-cli + credentials: + secret: none + public-client: false + bearer-only: true + principal-attribute: preferred_username + +#ALARMS +ALARMS_ADD_ALARM: "jms:queue:ALARMS.ADD.ALARM" +ALARMS_UPDATE_ALARM: "jms:queue:ALARMS.UPDATE.ALARM" +ALARMS_GET_ALARM: "jms:queue:ALARMS.GET.ALARM" + + +#NS ACTIONS +NFV_CATALOG_NSACTIONS_SCALE: "jms:queue:NSACTIONS.SCALE" +NFV_CATALOG_NS_LCMCHANGED: "jms:topic:NFV_CATALOG_NS_LCMCHANGED" + + diff --git a/src/main/resources/banner.txt b/src/main/resources/banner.txt new file mode 100644 index 0000000..74229cd --- /dev/null +++ b/src/main/resources/banner.txt @@ -0,0 +1,11 @@ + ___ ____ _ _ + / _ \ _ __ ___ _ __ / ___|| (_) ___ ___ + | | | | '_ \ / _ \ '_ \\___ \| | |/ __/ _ \ + | |_| | |_) | __/ | | |___) | | | (_| __/ + \___/| .__/ \___|_| |_|____/|_|_|\___\___| + |_| + __ __________________ + / / __ __ / __/_ __/ __/ _/ + / _ \/ // / / _/ / / _\ \_/ / + /_.__/\_, / /___/ /_/ /___/___/ + /___/ \ No newline at end of file diff --git a/src/main/resources/bootstrap.yml b/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..e69de29 diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000..208c635 --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + app.log + + + logs/archived/app.%d{yyyy-MM-dd}.%i.log + + 10MB + + 20GB + + 60 + + + + %d %p %c{1.} [%t] %m%n + + + + + + + + + + + diff --git a/src/test/resources/readme.txt b/src/test/resources/readme.txt new file mode 100644 index 0000000..e69de29 -- GitLab