81b9645feb18fa520b61e02cc8a6a7772f235746
[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.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.karaf.bundle.core.BundleInfo;
37 //import org.apache.karaf.bundle.core.BundleService;
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.common.file.PomPropertiesFile;
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     private 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 NO_DEVICEMANAGERS_RUNNING_MESSAGE = null;
75
76     private final String groupId = "org.onap.ccsdk.features.sdnr.wt";
77     private final String artifactId = "sdnr-wt-data-provider-provider";
78
79     private final Map<Integer,String> BUNDLESTATE_LUT;
80     private final Map<String, String> data;
81     private final String readmeContent;
82     //  private BundleService bundleService;
83
84
85     public AboutHttpServlet() {
86
87         this.data = new HashMap<>();
88         this.collectStaticData();
89         this.readmeContent = this.render(this.getResourceFileContent(README_FILE));
90         this.BUNDLESTATE_LUT = new HashMap<>();
91         this.BUNDLESTATE_LUT.put(Bundle.UNINSTALLED, "uninstalled");
92         this.BUNDLESTATE_LUT.put(Bundle.INSTALLED, "installed");
93         this.BUNDLESTATE_LUT.put(Bundle.RESOLVED, "resolved");
94         this.BUNDLESTATE_LUT.put(Bundle.STARTING, "starting");
95         this.BUNDLESTATE_LUT.put(Bundle.STOPPING, "stopping");
96         this.BUNDLESTATE_LUT.put(Bundle.ACTIVE, "active");
97
98     }
99
100     //  public void setBundleService(BundleService bundleService) {
101     //          this.bundleService = bundleService;
102     //  }
103
104     /**
105      * collect static versioning data
106      */
107     private void collectStaticData() {
108         PomPropertiesFile props = this.getPomProperties();
109         final String ccsdkVersion = this.getPomParentVersion();
110         final String mdsalVersion = SystemInfo.getMdSalVersion(UNKNOWN);
111         this.data.put(PLACEHOLDER_ONAP_RELEASENAME, ODLVersionLUT.getONAPReleaseName(ccsdkVersion, UNKNOWN));
112         this.data.put(PLACEHOLDER_ODL_RELEASENAME, ODLVersionLUT.getOdlVersion(mdsalVersion, UNKNOWN));
113         this.data.put(PLACEHOLDER_BUILD_TIMESTAMP, props != null ? props.getBuildDate().toString() : "");
114         this.data.put(PLACEHOLDER_PACAKGE_VERSION, this.getManifestValue("Bundle-Version"));
115         this.data.put(PLACEHOLDER_CCSDK_VERSION, ccsdkVersion);
116         this.data.put(PLACEHOLDER_ONAP_RELEASEVERSION, SystemInfo.getOnapVersion(UNKNOWN));
117         this.data.put(PLACEHOLDER_MDSAL_VERSION, mdsalVersion);
118         this.data.put(PLACEHOLDER_YANGTOOLS_VERSION, SystemInfo.getYangToolsVersion(UNKNOWN));
119         this.data.put(PLACEHOLDER_PACKAGE_GITHASH, this.getGitHash(UNKNOWN));
120     }
121
122     @Override
123     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
124
125         String uri = req.getRequestURI().substring(URI_PRE.length());
126         LOG.debug("request for {}", uri);
127         if (uri.length() <= 0 || uri.equals("/")) {
128             // collect data
129             this.collectData();
130             // render readme
131             String content = this.render();
132             byte[] output = content != null ? content.getBytes() : new byte[0];
133             // output
134             resp.setStatus(HttpServletResponse.SC_OK);
135             resp.setContentLength(output.length);
136             resp.setContentType("text/plain");
137             ServletOutputStream os = null;
138             try {
139                 os = resp.getOutputStream();
140                 os.write(output);
141             } catch (IOException e) {
142                 LOG.warn("problem writing response for {}: {}", uri, e);
143             } finally {
144                 if (os != null) {
145                     try {
146                         os.close();
147                     } catch (IOException e) {
148                         LOG.warn("problem closing response stream: {}", e);
149                     }
150                 }
151             }
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() {
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());
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     private 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 value for key out of /META-INF/maven/groupId/artifactId/pom.xml in properties section
242      *
243      * @param key
244      * @return
245      */
246     private String getPomProperty(String key) {
247         LOG.info("try to get pom property for {}", key);
248         URL url = Resources.getUrlForRessource(AboutHttpServlet.class,
249                 METAINF_MAVEN + groupId + "/" + artifactId + "/pom.xml");
250         if (url == null) {
251             return null;
252         }
253         PomFile pomfile;
254         try {
255             pomfile = new PomFile(url.openStream());
256             return pomfile.getProperty(key);
257         } catch (Exception e) {
258             LOG.warn(EXCEPTION_FORMAT_UNABLE_TO_READ_INNER_POMFILE, e);
259         }
260         return null;
261     }
262
263     /**
264      * get parent pom version out of /META-INF/maven/groupId/artifactId/pom.xml
265      *
266      * @return
267      */
268     private String getPomParentVersion() {
269         LOG.info("try to get pom parent version");
270         URL url = Resources.getUrlForRessource(AboutHttpServlet.class,
271                 METAINF_MAVEN + groupId + "/" + artifactId + "/pom.xml");
272         if (url == null) {
273             return null;
274         }
275         PomFile pomfile;
276         try {
277             pomfile = new PomFile(url.openStream());
278             return pomfile.getParentVersion();
279         } catch (Exception e) {
280             LOG.warn(EXCEPTION_FORMAT_UNABLE_TO_READ_INNER_POMFILE, e);
281         }
282         return null;
283     }
284
285     private String getDevicemanagerBundles() {
286         Bundle thisbundle = FrameworkUtil.getBundle(this.getClass());
287         BundleContext context = thisbundle ==null?null:thisbundle.getBundleContext();
288         if (context == null) {
289             LOG.debug("no bundle context available");
290             return "";
291         }
292         Bundle[] bundles = context.getBundles();
293         if (bundles == null || bundles.length <= 0) {
294             LOG.debug("no bundles found");
295             return NO_DEVICEMANAGERS_RUNNING_MESSAGE;
296         }
297         LOG.debug("found {} bundles", bundles.length);
298         MarkdownTable table = new MarkdownTable();
299         table.setHeader(new String[] {"Bundle-Id","Version","Symbolic-Name","Status"});
300         String name;
301         for (Bundle bundle : bundles) {
302             name = bundle.getSymbolicName();
303             if(!(name.contains("devicemanager") && name.contains("provider"))) {
304                 continue;
305             }
306             if(name.equals("org.onap.ccsdk.features.sdnr.wt.sdnr-wt-devicemanager-provider")) {
307                 continue;
308             }
309             table.addRow(new String[] {String.valueOf(bundle.getBundleId()), bundle.getVersion().toString(), name,
310                 BUNDLESTATE_LUT.getOrDefault(bundle.getState(),"unknown")});
311
312         }
313         return table.toMarkDown();
314     }
315
316     /**
317      * get file by uri from resources and write out to response stream
318      *
319      * @param uri
320      * @param resp
321      */
322     private void doGetFile(String uri, HttpServletResponse resp) {
323         String content = this.getResourceFileContent(uri);
324         if (content == null) {
325             try {
326                 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
327             } catch (IOException e) {
328                 LOG.debug("unable to send error response : {}", e);
329             }
330         } else {
331             byte[] data = content.getBytes();
332             resp.setStatus(HttpServletResponse.SC_OK);
333             resp.setContentType(this.getContentType(uri));
334             try {
335                 resp.getOutputStream().write(data);
336             } catch (IOException e) {
337                 LOG.debug("unable to send data : {}", e);
338             }
339         }
340
341     }
342
343     /**
344      * create http response contentType by filename
345      *
346      * @param filename
347      * @return
348      */
349     private String getContentType(String filename) {
350         String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
351         switch (ext) {
352             case "jpg":
353             case "jpeg":
354             case "svg":
355             case "png":
356             case "gif":
357             case "bmp":
358                 return "image/" + ext;
359             case "json":
360                 return "application/json";
361             case "html":
362             case "htm":
363                 return "text/html";
364             case "txt":
365             case "md":
366             default:
367                 return "text/plain";
368         }
369     }
370
371     /**
372      * render this.readmeContent with this.data
373      *
374      * @return
375      */
376     private String render() {
377         return this.render(null);
378     }
379
380     /**
381      * render content with this.data
382      *
383      * @param content
384      * @return
385      */
386     private String render(String content) {
387         if (content == null) {
388             content = this.readmeContent;
389         }
390         if (content == null) {
391             return null;
392         }
393         for (Entry<String, String> entry : this.data.entrySet()) {
394             if (entry.getValue() != null && content.contains(entry.getKey())) {
395                 content = content.replace(entry.getKey(), entry.getValue());
396             }
397         }
398
399         return content;
400     }
401
402     public void setClusterSize(String value) {
403         this.data.put(PLACEHOLDER_CLUSTER_SIZE, value);
404     }
405 }