Extend SDNC persistent service to store CM
[ccsdk/features.git] / sdnr / wt / data-provider / provider / src / main / java / org / onap / ccsdk / features / sdnr / wt / dataprovider / http / about / AboutHttpServlet.java
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  *
21  */
22 package org.onap.ccsdk.features.sdnr.wt.dataprovider.http.about;
23
24 import java.io.IOException;
25 import java.net.URL;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.jar.Attributes;
30 import java.util.jar.Manifest;
31 import javax.servlet.ServletException;
32 import javax.servlet.ServletOutputStream;
33 import javax.servlet.http.HttpServlet;
34 import javax.servlet.http.HttpServletRequest;
35 import javax.servlet.http.HttpServletResponse;
36 import org.apache.http.HttpHeaders;
37 import org.onap.ccsdk.features.sdnr.wt.common.Resources;
38 import org.onap.ccsdk.features.sdnr.wt.common.file.PomFile;
39 import org.onap.ccsdk.features.sdnr.wt.common.file.PomPropertiesFile;
40 import org.osgi.framework.Bundle;
41 import org.osgi.framework.BundleContext;
42 import org.osgi.framework.FrameworkUtil;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 public class AboutHttpServlet extends HttpServlet {
47
48     /**
49      *
50      */
51     private static final long serialVersionUID = 1L;
52     private static final Logger LOG = LoggerFactory.getLogger(AboutHttpServlet.class);
53     private static final String UNKNOWN = "unknown";
54     private static final String METAINF_MAVEN = "/META-INF/maven/";
55     private static final String EXCEPTION_FORMAT_UNABLE_TO_READ_INNER_POMFILE = "unable to read inner pom file: {}";
56
57     private static final String URI_PRE = "/about";
58     private static final String RES_BASEPATH = "about/";
59
60     private static final String PLACEHOLDER_ONAP_RELEASENAME = "{release-name}";
61     private static final String PLACEHOLDER_ONAP_RELEASEVERSION = "{release-version}";
62     private static final String PLACEHOLDER_ODL_RELEASENAME = "{odl-version}";
63     private static final String PLACEHOLDER_BUILD_TIMESTAMP = "{build-time}";
64     private static final String PLACEHOLDER_PACKAGE_GITHASH = "{package-githash}";
65     private static final String PLACEHOLDER_PACAKGE_VERSION = "{package-version}";
66     private static final String PLACEHOLDER_CCSDK_VERSION = "{ccsdk-version}";
67     private static final String PLACEHOLDER_CLUSTER_SIZE = "{cluster-size}";
68     private static final String PLACEHOLDER_MDSAL_VERSION = "{mdsal-version}";
69     private static final String PLACEHOLDER_YANGTOOLS_VERSION = "{yangtools-version}";
70     private static final String PLACEHOLDER_KARAF_INFO = "{karaf-info}";
71     private static final String PLACEHOLDER_DEVICEMANAGER_TABLE = "{devicemanagers}";
72     private static final String README_FILE = "README.md";
73     private static final String JSON_FILE = "README.json";
74     private static final String NO_DEVICEMANAGERS_RUNNING_MESSAGE = null;
75     private static final String MIMETYPE_JSON = "application/json";
76     private static final String MIMETYPE_MARKDOWN = "text/markdown";
77
78     private final String groupId = this.getGroupIdOrDefault("org.onap.ccsdk.features.sdnr.wt");
79     private final String artifactId = "sdnr-wt-data-provider-provider";
80
81     private final Map<Integer, String> BUNDLESTATE_LUT;
82     private final Map<String, String> data;
83     private final String readmeContent;
84     private final String jsonContent;
85
86
87     public AboutHttpServlet() {
88
89         this.data = new HashMap<>();
90         this.collectStaticData();
91         this.readmeContent = this.render(ContentType.MARKDOWN, this.getResourceFileContent(README_FILE));
92         this.jsonContent = this.render(ContentType.MARKDOWN, this.getResourceFileContent(JSON_FILE));
93         this.BUNDLESTATE_LUT = new HashMap<>();
94         this.BUNDLESTATE_LUT.put(Bundle.UNINSTALLED, "uninstalled");
95         this.BUNDLESTATE_LUT.put(Bundle.INSTALLED, "installed");
96         this.BUNDLESTATE_LUT.put(Bundle.RESOLVED, "resolved");
97         this.BUNDLESTATE_LUT.put(Bundle.STARTING, "starting");
98         this.BUNDLESTATE_LUT.put(Bundle.STOPPING, "stopping");
99         this.BUNDLESTATE_LUT.put(Bundle.ACTIVE, "active");
100
101     }
102
103     protected String getGroupIdOrDefault(String def) {
104         String symbolicName = this.getManifestValue("Bundle-SymbolicName");
105         if (symbolicName != null) {
106             int idx = symbolicName.indexOf(this.artifactId);
107             if (idx > 0) {
108                 return symbolicName.substring(0, idx - 1);
109             }
110         }
111         return def;
112     }
113
114     /**
115      * collect static versioning data
116      */
117     private void collectStaticData() {
118         PomPropertiesFile props = this.getPomProperties();
119         final String ccsdkVersion = this.getPomParentVersion();
120         final String mdsalVersion = SystemInfo.getMdSalVersion(UNKNOWN);
121         this.data.put(PLACEHOLDER_ONAP_RELEASENAME, ODLVersionLUT.getONAPReleaseName(ccsdkVersion, UNKNOWN));
122         this.data.put(PLACEHOLDER_ODL_RELEASENAME, ODLVersionLUT.getOdlVersion(mdsalVersion, UNKNOWN));
123         this.data.put(PLACEHOLDER_BUILD_TIMESTAMP, props != null ? String.valueOf(props.getBuildDate()) : "");
124         this.data.put(PLACEHOLDER_PACAKGE_VERSION, this.getManifestValue("Bundle-Version"));
125         this.data.put(PLACEHOLDER_CCSDK_VERSION, ccsdkVersion);
126         this.data.put(PLACEHOLDER_ONAP_RELEASEVERSION, SystemInfo.getOnapVersion(UNKNOWN));
127         this.data.put(PLACEHOLDER_MDSAL_VERSION, mdsalVersion);
128         this.data.put(PLACEHOLDER_YANGTOOLS_VERSION, SystemInfo.getYangToolsVersion(UNKNOWN));
129         this.data.put(PLACEHOLDER_PACKAGE_GITHASH, this.getGitHash(UNKNOWN));
130     }
131
132     @Override
133     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
134
135         String uri = req.getRequestURI().substring(URI_PRE.length());
136         LOG.debug("request for {}", uri);
137         if (uri.length() <= 0 || uri.equals("/")) {
138             ContentType ctype = this.detectContentType(req, ContentType.MARKDOWN);
139             // collect data
140             this.collectData(ctype);
141             // render readme
142             String content = this.render(ctype);
143             byte[] output = content != null ? content.getBytes() : new byte[0];
144             // output
145             resp.setStatus(HttpServletResponse.SC_OK);
146             resp.setContentLength(output.length);
147             resp.setContentType(ctype.getMimeType());
148             try (ServletOutputStream os = resp.getOutputStream()) {
149                 os.write(output);
150             } catch (IOException e) {
151                 LOG.warn("problem writing response for {}: {}", uri, e);
152             }
153         } else {
154             this.doGetFile(uri, resp);
155         }
156     }
157
158     /**
159      * load git.commit.id from jar /META-INF/git.properties
160      *
161      * @param def
162      */
163     private String getGitHash(String def) {
164         String content = Resources.getFileContent(AboutHttpServlet.class, "/META-INF/git.properties");
165         if (content == null) {
166             return def;
167         }
168         String[] lines = content.split("\n");
169         for (String line : lines) {
170             if (line.startsWith("git.commit.id")) {
171                 def = line.substring("git.commit.id=".length());
172                 break;
173             }
174         }
175         return def;
176     }
177
178     private String getResourceFileContent(String filename) {
179         LOG.debug("try ti get content of {}", filename);
180         return Resources.getFileContent(AboutHttpServlet.class, RES_BASEPATH + filename);
181     }
182
183     /**
184      * collect dynamic data for about.md
185      */
186     private void collectData(ContentType ctype) {
187         LOG.info("collecting dynamic data");
188         try {
189             this.data.put(PLACEHOLDER_KARAF_INFO, SystemInfo.get());
190             this.data.put(PLACEHOLDER_DEVICEMANAGER_TABLE, this.getDevicemanagerBundles(ctype));
191         } catch (Exception e) {
192             LOG.warn("problem collecting system data: ", e);
193         }
194     }
195
196     /**
197      * get value for key out of /META-INF/MANIFEST.MF
198      *
199      * @param key
200      * @return
201      */
202     protected String getManifestValue(String key) {
203         URL url = Resources.getUrlForRessource(AboutHttpServlet.class, "/META-INF/MANIFEST.MF");
204         if (url == null) {
205             return null;
206         }
207         Manifest manifest;
208         try {
209             manifest = new Manifest(url.openStream());
210             Attributes attr = manifest.getMainAttributes();
211             return attr.getValue(key);
212         } catch (IOException e) {
213             LOG.warn("problem reading manifest: ", e);
214         }
215         return null;
216
217     }
218
219     /**
220      * get object representation of /META-INF/maven/groupId/artifactId/pom.properties
221      *
222      * @return
223      */
224     private PomPropertiesFile getPomProperties() {
225         URL url = Resources.getUrlForRessource(AboutHttpServlet.class,
226                 METAINF_MAVEN + groupId + "/" + artifactId + "/pom.properties");
227         PomPropertiesFile propfile;
228         if (url == null) {
229             return null;
230         }
231         try {
232             propfile = new PomPropertiesFile(url.openStream());
233             return propfile;
234         } catch (Exception e) {
235             LOG.warn(EXCEPTION_FORMAT_UNABLE_TO_READ_INNER_POMFILE, e);
236         }
237         return null;
238     }
239
240     /**
241      * get parent pom version out of /META-INF/maven/groupId/artifactId/pom.xml
242      *
243      * @return
244      */
245     private String getPomParentVersion() {
246         LOG.info("try to get pom parent version");
247         URL url = Resources.getUrlForRessource(AboutHttpServlet.class,
248                 METAINF_MAVEN + groupId + "/" + artifactId + "/pom.xml");
249         if (url == null) {
250             return null;
251         }
252         PomFile pomfile;
253         try {
254             pomfile = new PomFile(url.openStream());
255             return pomfile.getParentVersion();
256         } catch (Exception e) {
257             LOG.warn(EXCEPTION_FORMAT_UNABLE_TO_READ_INNER_POMFILE, e);
258         }
259         return null;
260     }
261
262     private String getDevicemanagerBundles(ContentType ctype) {
263         Bundle thisbundle = FrameworkUtil.getBundle(this.getClass());
264         BundleContext context = thisbundle == null ? null : thisbundle.getBundleContext();
265         if (context == null) {
266             LOG.debug("no bundle context available");
267             return ctype == ContentType.MARKDOWN ? "" : "[]";
268         }
269         Bundle[] bundles = context.getBundles();
270         if (bundles == null || bundles.length <= 0) {
271             LOG.debug("no bundles found");
272             return ctype == ContentType.MARKDOWN ? NO_DEVICEMANAGERS_RUNNING_MESSAGE : "[]";
273         }
274         LOG.debug("found {} bundles", bundles.length);
275         MarkdownTable table = new MarkdownTable();
276         table.setHeader(new String[] {"Bundle-Id", "Version", "Symbolic-Name", "Status"});
277         String name;
278         for (Bundle bundle : bundles) {
279             name = bundle.getSymbolicName();
280             if (!(name.contains("devicemanager") && name.contains("provider"))) {
281                 continue;
282             }
283             if (name.equals("org.onap.ccsdk.features.sdnr.wt.sdnr-wt-devicemanager-provider")) {
284                 continue;
285             }
286             table.addRow(new String[] {String.valueOf(bundle.getBundleId()), bundle.getVersion().toString(), name,
287                     BUNDLESTATE_LUT.getOrDefault(bundle.getState(), UNKNOWN)});
288
289         }
290         return ctype == ContentType.MARKDOWN ? table.toMarkDown() : table.toJson();
291     }
292
293     /**
294      * get file by uri from resources and write out to response stream
295      *
296      * @param uri
297      * @param resp
298      */
299     private void doGetFile(String uri, HttpServletResponse resp) {
300         String content = this.getResourceFileContent(uri);
301         if (content == null) {
302             try {
303                 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
304             } catch (IOException e) {
305                 LOG.debug("unable to send error response : {}", e);
306             }
307         } else {
308             byte[] data = content.getBytes();
309             resp.setStatus(HttpServletResponse.SC_OK);
310             resp.setContentType(this.getContentType(uri));
311             try {
312                 resp.getOutputStream().write(data);
313             } catch (IOException e) {
314                 LOG.debug("unable to send data: ", e);
315             }
316         }
317
318     }
319
320     /**
321      * create http response contentType by filename
322      *
323      * @param filename
324      * @return
325      */
326     private String getContentType(String filename) {
327         String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
328         switch (ext) {
329             case "jpg":
330             case "jpeg":
331             case "svg":
332             case "png":
333             case "gif":
334             case "bmp":
335                 return "image/" + ext;
336             case "json":
337                 return MIMETYPE_JSON;
338             case "html":
339             case "htm":
340                 return "text/html";
341             case "txt":
342             case "md":
343             default:
344                 return "text/plain";
345         }
346     }
347
348     /**
349      * render this.readmeContent with this.data
350      *
351      * @param ctype
352      *
353      * @return
354      */
355     private String render(ContentType ctype) {
356         return this.render(ctype, null);
357     }
358
359     /**
360      * render content with this.data
361      *
362      * @param content
363      * @return
364      */
365     private String render(ContentType ctype, String content) {
366         if (content == null) {
367             content = ctype == ContentType.MARKDOWN ? this.readmeContent : this.jsonContent;
368         }
369         if (content == null) {
370             return null;
371         }
372         for (Entry<String, String> entry : this.data.entrySet()) {
373             if (entry.getValue() != null && content.contains(entry.getKey())) {
374                 content = content.replace(entry.getKey(), entry.getValue());
375             }
376         }
377
378         return content;
379     }
380
381     public void setClusterSize(String value) {
382         this.data.put(PLACEHOLDER_CLUSTER_SIZE, value);
383     }
384
385     private ContentType detectContentType(HttpServletRequest req, ContentType def) {
386         String accept = req.getHeader(HttpHeaders.ACCEPT);
387         if (accept != null) {
388             if (accept.equals(MIMETYPE_JSON)) {
389                 return ContentType.JSON;
390             } else if (accept.equals(MIMETYPE_MARKDOWN)) {
391                 return ContentType.MARKDOWN;
392             }
393         }
394         return def;
395     }
396
397     private enum ContentType {
398         MARKDOWN(MIMETYPE_MARKDOWN), JSON(MIMETYPE_JSON);
399
400         private String mimeType;
401
402         ContentType(String mimeType) {
403             this.mimeType = mimeType;
404         }
405
406         String getMimeType() {
407             return this.mimeType;
408         }
409     }
410 }