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