Add Rapp Instances
[nonrtric/plt/rappmanager.git] / rapp-manager-models / src / main / java / com / oransc / rappmanager / models / csar / RappCsarConfigurationHandler.java
1 /*-
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2023 Nordix Foundation. All rights reserved.
4  * ===============================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ============LICENSE_END========================================================================
17  */
18
19 package com.oransc.rappmanager.models.csar;
20
21 import com.oransc.rappmanager.models.rapp.Rapp;
22 import com.oransc.rappmanager.models.rappinstance.RappACMInstance;
23 import com.oransc.rappmanager.models.rapp.RappResources;
24 import com.oransc.rappmanager.models.rappinstance.RappSMEInstance;
25 import java.io.ByteArrayOutputStream;
26 import java.io.File;
27 import java.io.FileInputStream;
28 import java.io.IOException;
29 import java.nio.file.Path;
30 import java.util.List;
31 import java.util.UUID;
32 import java.util.function.Predicate;
33 import java.util.zip.ZipEntry;
34 import java.util.zip.ZipFile;
35 import java.util.zip.ZipInputStream;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.springframework.stereotype.Service;
39 import org.springframework.web.multipart.MultipartFile;
40
41 @Service
42 public class RappCsarConfigurationHandler {
43
44     Logger logger = LoggerFactory.getLogger(RappCsarConfigurationHandler.class);
45     private final String acmCompositionJsonLocation = "Files/Acm/definition/compositions.json";
46     private final String acmDefinitionLocation = "Files/Acm/definition";
47     private final String acmInstancesLocation = "Files/Acm/instances";
48
49     private final String smeProviderFuncsLocation = "Files/Sme/providers";
50     private final String smeServiceApisLocation = "Files/Sme/serviceapis";
51
52     private final String smeInvokersLocation = "Files/Sme/invokers";
53
54
55     public boolean isValidRappPackage(MultipartFile multipartFile) {
56         return multipartFile.getOriginalFilename() != null && multipartFile.getOriginalFilename().endsWith(".csar")
57                        && isFileExistsInCsar(multipartFile, acmCompositionJsonLocation);
58         //TODO Additional file checks needs to be added
59     }
60
61     boolean isFileExistsInCsar(MultipartFile multipartFile, String fileLocation) {
62         try (ZipInputStream zipInputStream = new ZipInputStream(multipartFile.getInputStream())) {
63             ZipEntry zipEntry;
64             while ((zipEntry = zipInputStream.getNextEntry()) != null) {
65                 if (zipEntry.getName().matches(fileLocation)) {
66                     return Boolean.TRUE;
67                 }
68             }
69             return Boolean.FALSE;
70         } catch (IOException e) {
71             logger.error("Unable to find the CSAR file", e);
72             return Boolean.FALSE;
73         }
74     }
75
76     public Path getRappPackageLocation(String csarLocation, String rappId, String fileName) {
77         return Path.of(csarLocation, rappId, fileName);
78     }
79
80     public String getInstantiationPayload(Rapp rapp, RappACMInstance rappACMInstance, UUID compositionId) {
81         return getPayload(rapp, getResourceUri(acmInstancesLocation, rappACMInstance.getInstance())).replaceAll(
82                 "COMPOSITIONID", String.valueOf(compositionId));
83     }
84
85     String getPayload(Rapp rapp, String location) {
86         logger.info("Getting payload for {} from {}", rapp.getRappId(), location);
87         File csarFile = getCsarFile(rapp);
88         return getFileFromCsar(csarFile, location).toString();
89     }
90
91     File getCsarFile(Rapp rapp) {
92         return new File(
93                 getRappPackageLocation(rapp.getPackageLocation(), rapp.getName(), rapp.getPackageName()).toUri());
94     }
95
96     ByteArrayOutputStream getFileFromCsar(File csarFile, String fileLocation) {
97         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
98         try (FileInputStream fileInputStream = new FileInputStream(csarFile);
99              ZipInputStream zipInputStream = new ZipInputStream(fileInputStream)) {
100             ZipEntry entry;
101             while ((entry = zipInputStream.getNextEntry()) != null) {
102                 if (!entry.isDirectory() && entry.getName().equals(fileLocation)) {
103                     byte[] buffer = new byte[1024];
104                     int bytesRead;
105                     while ((bytesRead = zipInputStream.read(buffer)) != -1) {
106                         byteArrayOutputStream.write(buffer, 0, bytesRead);
107                     }
108                 }
109             }
110         } catch (IOException e) {
111             logger.error("Unable to find the CSAR file", e);
112         }
113         return byteArrayOutputStream;
114     }
115
116
117     public String getSmeProviderDomainPayload(Rapp rapp, RappSMEInstance rappSMEInstance) {
118         return getPayload(rapp, getResourceUri(smeProviderFuncsLocation, rappSMEInstance.getProviderFunction()));
119     }
120
121     public String getSmeProviderApiPayload(Rapp rapp, RappSMEInstance rappSMEInstance) {
122         return getPayload(rapp, getResourceUri(smeServiceApisLocation, rappSMEInstance.getServiceApis()));
123     }
124
125     public String getSmeInvokerPayload(Rapp rapp, RappSMEInstance rappSMEInstance) {
126         return getPayload(rapp, getResourceUri(smeInvokersLocation, rappSMEInstance.getInvokers()));
127     }
128
129     public String getAcmCompositionPayload(Rapp rapp) {
130         return getPayload(rapp,
131                 getResourceUri(acmDefinitionLocation, rapp.getRappResources().getAcm().getCompositionDefinitions()));
132     }
133
134     String getResourceUri(String resourceLocation, String resource) {
135         return resourceLocation + "/" + resource + ".json";
136     }
137
138     public RappResources getRappResource(Rapp rapp) {
139         RappResources rappResources = new RappResources();
140         try {
141             File csarFile = getCsarFile(rapp);
142             if (csarFile.exists()) {
143                 rappResources.setAcm(RappResources.ACMResources.builder().compositionDefinitions(
144                                 getFileListFromCsar(csarFile, acmDefinitionLocation).get(0))
145                                              .compositionInstances(getFileListFromCsar(csarFile, acmInstancesLocation))
146                                              .build());
147                 rappResources.setSme(RappResources.SMEResources.builder()
148                                              .providerFunctions(getFileListFromCsar(csarFile, smeProviderFuncsLocation))
149                                              .serviceApis(getFileListFromCsar(csarFile, smeServiceApisLocation))
150                                              .invokers(getFileListFromCsar(csarFile, smeInvokersLocation)).build());
151             }
152         } catch (Exception e) {
153             logger.warn("Error in getting the rapp resources", e);
154         }
155         return rappResources;
156     }
157
158     List<String> getFileListFromCsar(File csarFile, String dirLocation) {
159         try (ZipFile zipFile = new ZipFile(csarFile)) {
160             return zipFile.stream().filter(Predicate.not(ZipEntry::isDirectory)).map(ZipEntry::getName)
161                            .filter(name -> name.startsWith(dirLocation))
162                            .map(name -> name.substring(name.lastIndexOf("/") + 1, name.lastIndexOf("."))).toList();
163         } catch (IOException e) {
164             logger.warn("Error in listing the files from csar", e);
165         }
166         return List.of();
167     }
168 }