e088463137c8fff2a88fc2ac0d917ac28921bbaa
[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.rapp.RappResources;
23 import com.oransc.rappmanager.models.rappinstance.RappACMInstance;
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 static final String ACM_COMPOSITION_JSON_LOCATION = "Files/Acm/definition/compositions.json";
46     private static final String ACM_DEFINITION_LOCATION = "Files/Acm/definition";
47     private static final String ACM_INSTANCES_LOCATION = "Files/Acm/instances";
48
49     private static final String SME_PROVIDER_FUNCS_LOCATION = "Files/Sme/providers";
50     private static final String SME_SERVICE_APIS_LOCATION = "Files/Sme/serviceapis";
51
52     private static final String SME_INVOKERS_LOCATION = "Files/Sme/invokers";
53
54
55     public boolean isValidRappPackage(MultipartFile multipartFile) {
56         String originalFilename = multipartFile.getOriginalFilename();
57         if (originalFilename != null) {
58             return originalFilename.endsWith(".csar") && isFileExistsInCsar(multipartFile,
59                     ACM_COMPOSITION_JSON_LOCATION);
60         }
61         return false;
62     }
63
64     boolean isFileExistsInCsar(MultipartFile multipartFile, String fileLocation) {
65         try (ZipInputStream zipInputStream = new ZipInputStream(multipartFile.getInputStream())) {
66             ZipEntry zipEntry;
67             while ((zipEntry = zipInputStream.getNextEntry()) != null) {
68                 if (zipEntry.getName().matches(fileLocation)) {
69                     return Boolean.TRUE;
70                 }
71             }
72             return Boolean.FALSE;
73         } catch (IOException e) {
74             logger.error("Unable to find the CSAR file", e);
75             return Boolean.FALSE;
76         }
77     }
78
79     public Path getRappPackageLocation(String csarLocation, String rappId, String fileName) {
80         return Path.of(csarLocation, rappId, fileName);
81     }
82
83     public String getInstantiationPayload(Rapp rapp, RappACMInstance rappACMInstance, UUID compositionId) {
84         return getPayload(rapp, getResourceUri(ACM_INSTANCES_LOCATION, rappACMInstance.getInstance())).replaceAll(
85                 "COMPOSITIONID", String.valueOf(compositionId));
86     }
87
88     String getPayload(Rapp rapp, String location) {
89         logger.info("Getting payload for {} from {}", rapp.getRappId(), location);
90         File csarFile = getCsarFile(rapp);
91         return getFileFromCsar(csarFile, location).toString();
92     }
93
94     File getCsarFile(Rapp rapp) {
95         return new File(
96                 getRappPackageLocation(rapp.getPackageLocation(), rapp.getName(), rapp.getPackageName()).toUri());
97     }
98
99     ByteArrayOutputStream getFileFromCsar(File csarFile, String fileLocation) {
100         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
101         try (FileInputStream fileInputStream = new FileInputStream(csarFile);
102              ZipInputStream zipInputStream = new ZipInputStream(fileInputStream)) {
103             ZipEntry entry;
104             while ((entry = zipInputStream.getNextEntry()) != null) {
105                 if (!entry.isDirectory() && entry.getName().equals(fileLocation)) {
106                     byte[] buffer = new byte[1024];
107                     int bytesRead;
108                     while ((bytesRead = zipInputStream.read(buffer)) != -1) {
109                         byteArrayOutputStream.write(buffer, 0, bytesRead);
110                     }
111                 }
112             }
113         } catch (IOException e) {
114             logger.error("Unable to find the CSAR file", e);
115         }
116         return byteArrayOutputStream;
117     }
118
119
120     public String getSmeProviderDomainPayload(Rapp rapp, RappSMEInstance rappSMEInstance) {
121         return getPayload(rapp, getResourceUri(SME_PROVIDER_FUNCS_LOCATION, rappSMEInstance.getProviderFunction()));
122     }
123
124     public String getSmeProviderApiPayload(Rapp rapp, RappSMEInstance rappSMEInstance) {
125         return getPayload(rapp, getResourceUri(SME_SERVICE_APIS_LOCATION, rappSMEInstance.getServiceApis()));
126     }
127
128     public String getSmeInvokerPayload(Rapp rapp, RappSMEInstance rappSMEInstance) {
129         return getPayload(rapp, getResourceUri(SME_INVOKERS_LOCATION, rappSMEInstance.getInvokers()));
130     }
131
132     public String getAcmCompositionPayload(Rapp rapp) {
133         return getPayload(rapp,
134                 getResourceUri(ACM_DEFINITION_LOCATION, rapp.getRappResources().getAcm().getCompositionDefinitions()));
135     }
136
137     String getResourceUri(String resourceLocation, String resource) {
138         return resourceLocation + "/" + resource + ".json";
139     }
140
141     public RappResources getRappResource(Rapp rapp) {
142         RappResources rappResources = new RappResources();
143         try {
144             File csarFile = getCsarFile(rapp);
145             if (csarFile.exists()) {
146                 rappResources.setAcm(RappResources.ACMResources.builder().compositionDefinitions(
147                                 getFileListFromCsar(csarFile, ACM_DEFINITION_LOCATION).get(0))
148                                              .compositionInstances(getFileListFromCsar(csarFile, ACM_INSTANCES_LOCATION))
149                                              .build());
150                 rappResources.setSme(RappResources.SMEResources.builder()
151                                              .providerFunctions(getFileListFromCsar(csarFile,
152                                                      SME_PROVIDER_FUNCS_LOCATION))
153                                              .serviceApis(getFileListFromCsar(csarFile, SME_SERVICE_APIS_LOCATION))
154                                              .invokers(getFileListFromCsar(csarFile, SME_INVOKERS_LOCATION)).build());
155             }
156         } catch (Exception e) {
157             logger.warn("Error in getting the rapp resources", e);
158         }
159         return rappResources;
160     }
161
162     List<String> getFileListFromCsar(File csarFile, String dirLocation) {
163         try (ZipFile zipFile = new ZipFile(csarFile)) {
164             return zipFile.stream().filter(Predicate.not(ZipEntry::isDirectory)).map(ZipEntry::getName)
165                            .filter(name -> name.startsWith(dirLocation))
166                            .map(name -> name.substring(name.lastIndexOf("/") + 1, name.lastIndexOf("."))).toList();
167         } catch (IOException e) {
168             logger.warn("Error in listing the files from csar", e);
169         }
170         return List.of();
171     }
172 }