48dc81199100840a809359a7f31cac630ecb8bfd
[policy/common.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019-2020 Nordix Foundation.
7  * Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.common.endpoints.http.server.internal;
24
25 import java.util.EnumSet;
26 import javax.servlet.DispatcherType;
27 import org.eclipse.jetty.security.ConstraintMapping;
28 import org.eclipse.jetty.security.ConstraintSecurityHandler;
29 import org.eclipse.jetty.security.HashLoginService;
30 import org.eclipse.jetty.security.UserStore;
31 import org.eclipse.jetty.security.authentication.BasicAuthenticator;
32 import org.eclipse.jetty.server.CustomRequestLog;
33 import org.eclipse.jetty.server.HttpConfiguration;
34 import org.eclipse.jetty.server.HttpConnectionFactory;
35 import org.eclipse.jetty.server.SecureRequestCustomizer;
36 import org.eclipse.jetty.server.Server;
37 import org.eclipse.jetty.server.ServerConnector;
38 import org.eclipse.jetty.server.Slf4jRequestLogWriter;
39 import org.eclipse.jetty.servlet.FilterHolder;
40 import org.eclipse.jetty.servlet.ServletContextHandler;
41 import org.eclipse.jetty.util.security.Constraint;
42 import org.eclipse.jetty.util.security.Credential;
43 import org.eclipse.jetty.util.ssl.SslContextFactory;
44 import org.onap.aaf.cadi.filter.CadiFilter;
45 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
46 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * Http Server implementation using Embedded Jetty.
52  */
53 public abstract class JettyServletServer implements HttpServletServer, Runnable {
54
55     /**
56      * Keystore/Truststore system property names.
57      */
58     public static final String SYSTEM_KEYSTORE_PROPERTY_NAME = "javax.net.ssl.keyStore";
59     public static final String SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.keyStorePassword"; //NOSONAR
60     public static final String SYSTEM_TRUSTSTORE_PROPERTY_NAME = "javax.net.ssl.trustStore";
61     public static final String SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.trustStorePassword"; //NOSONAR
62
63     /**
64      * Logger.
65      */
66     private static Logger logger = LoggerFactory.getLogger(JettyServletServer.class);
67
68     private static final String NOT_SUPPORTED = " is not supported on this type of jetty server";
69
70     /**
71      * Server name.
72      */
73     protected final String name;
74
75     /**
76      * Server host address.
77      */
78     protected final String host;
79
80     /**
81      * Server port to bind.
82      */
83     protected final int port;
84
85     /**
86      * Server auth user name.
87      */
88     protected String user;
89
90     /**
91      * Server auth password name.
92      */
93     protected String password;
94
95     /**
96      * Server base context path.
97      */
98     protected final String contextPath;
99
100     /**
101      * Embedded jetty server.
102      */
103     protected final Server jettyServer;
104
105     /**
106      * Servlet context.
107      */
108     protected final ServletContextHandler context;
109
110     /**
111      * Jetty connector.
112      */
113     protected final ServerConnector connector;
114
115     /**
116      * Jetty thread.
117      */
118     protected Thread jettyThread;
119
120     /**
121      * Start condition.
122      */
123     protected Object startCondition = new Object();
124
125     /**
126      * Constructor.
127      *
128      * @param name server name
129      * @param host server host
130      * @param port server port
131      * @param contextPath context path
132      *
133      * @throws IllegalArgumentException if invalid parameters are passed in
134      */
135     protected JettyServletServer(String name, boolean https, String host, int port, String contextPath) {
136         String srvName = name;
137
138         if (srvName == null || srvName.isEmpty()) {
139             srvName = "http-" + port;
140         }
141
142         if (port <= 0 || port >= 65535) {
143             throw new IllegalArgumentException("Invalid Port provided: " + port);
144         }
145
146         String srvHost = host;
147         if (srvHost == null || srvHost.isEmpty()) {
148             srvHost = "localhost";
149         }
150
151         String ctxtPath = contextPath;
152         if (ctxtPath == null || ctxtPath.isEmpty()) {
153             ctxtPath = "/";
154         }
155
156         this.name = srvName;
157
158         this.host = srvHost;
159         this.port = port;
160
161         this.contextPath = ctxtPath;
162
163         this.context = new ServletContextHandler(ServletContextHandler.SESSIONS);
164         this.context.setContextPath(ctxtPath);
165
166         this.jettyServer = new Server();
167
168         var requestLog = new CustomRequestLog(new Slf4jRequestLogWriter(), CustomRequestLog.EXTENDED_NCSA_FORMAT);
169         this.jettyServer.setRequestLog(requestLog);
170
171         if (https) {
172             this.connector = httpsConnector();
173         } else {
174             this.connector = httpConnector();
175         }
176
177         this.connector.setName(srvName);
178         this.connector.setReuseAddress(true);
179         this.connector.setPort(port);
180         this.connector.setHost(srvHost);
181
182         this.jettyServer.addConnector(this.connector);
183         this.jettyServer.setHandler(context);
184     }
185
186     protected JettyServletServer(String name, String host, int port, String contextPath) {
187         this(name, false, host, port, contextPath);
188     }
189
190     @Override
191     public void addFilterClass(String filterPath, String filterClass) {
192         if (filterClass == null || filterClass.isEmpty()) {
193             throw new IllegalArgumentException("No filter class provided");
194         }
195
196         String tempFilterPath = filterPath;
197         if (filterPath == null || filterPath.isEmpty()) {
198             tempFilterPath = "/*";
199         }
200
201         context.addFilter(filterClass, tempFilterPath, EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
202     }
203
204     /**
205      * Returns the https connector.
206      *
207      * @return the server connector
208      */
209     public ServerConnector httpsConnector() {
210         SslContextFactory sslContextFactory = new SslContextFactory.Server();
211
212         String keyStore = System.getProperty(SYSTEM_KEYSTORE_PROPERTY_NAME);
213         if (keyStore != null) {
214             sslContextFactory.setKeyStorePath(keyStore);
215
216             String ksPassword = System.getProperty(SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME);
217             if (ksPassword != null) {
218                 sslContextFactory.setKeyStorePassword(ksPassword);
219             }
220         }
221
222         String trustStore = System.getProperty(SYSTEM_TRUSTSTORE_PROPERTY_NAME);
223         if (trustStore != null) {
224             sslContextFactory.setTrustStorePath(trustStore);
225
226             String tsPassword = System.getProperty(SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME);
227             if (tsPassword != null) {
228                 sslContextFactory.setTrustStorePassword(tsPassword);
229             }
230         }
231
232         var https = new HttpConfiguration();
233         https.addCustomizer(new SecureRequestCustomizer());
234
235         return new ServerConnector(jettyServer, sslContextFactory, new HttpConnectionFactory(https));
236     }
237
238     public ServerConnector httpConnector() {
239         return new ServerConnector(this.jettyServer);
240     }
241
242     @Override
243     public void setAafAuthentication(String filterPath) {
244         this.addFilterClass(filterPath, CadiFilter.class.getName());
245     }
246
247     @Override
248     public boolean isAaf() {
249         for (FilterHolder filter : context.getServletHandler().getFilters()) {
250             if (CadiFilter.class.getName().equals(filter.getClassName())) {
251                 return true;
252             }
253         }
254         return false;
255     }
256
257     @Override
258     public void setBasicAuthentication(String user, String password, String servletPath) {
259         String srvltPath = servletPath;
260
261         if (user == null || user.isEmpty() || password == null || password.isEmpty()) {
262             throw new IllegalArgumentException("Missing user and/or password");
263         }
264
265         if (srvltPath == null || srvltPath.isEmpty()) {
266             srvltPath = "/*";
267         }
268
269         final var hashLoginService = new HashLoginService();
270         final var userStore = new UserStore();
271         userStore.addUser(user, Credential.getCredential(password), new String[] {"user"});
272         hashLoginService.setUserStore(userStore);
273         hashLoginService.setName(this.connector.getName() + "-login-service");
274
275         var constraint = new Constraint();
276         constraint.setName(Constraint.__BASIC_AUTH);
277         constraint.setRoles(new String[] {"user"});
278         constraint.setAuthenticate(true);
279
280         var constraintMapping = new ConstraintMapping();
281         constraintMapping.setConstraint(constraint);
282         constraintMapping.setPathSpec(srvltPath);
283
284         var securityHandler = new ConstraintSecurityHandler();
285         securityHandler.setAuthenticator(new BasicAuthenticator());
286         securityHandler.setRealmName(this.connector.getName() + "-realm");
287         securityHandler.addConstraintMapping(constraintMapping);
288         securityHandler.setLoginService(hashLoginService);
289
290         this.context.setSecurityHandler(securityHandler);
291
292         this.user = user;
293         this.password = password;
294     }
295
296     /**
297      * jetty server execution.
298      */
299     @Override
300     public void run() {
301         try {
302             logger.info("{}: STARTING", this);
303
304             this.jettyServer.start();
305
306             if (logger.isTraceEnabled()) {
307                 logger.trace("{}: STARTED: {}", this, this.jettyServer.dump());
308             }
309
310             synchronized (this.startCondition) {
311                 this.startCondition.notifyAll();
312             }
313
314             this.jettyServer.join();
315
316         } catch (InterruptedException e) {
317             logger.error("{}: error found while bringing up server", this, e);
318             Thread.currentThread().interrupt();
319
320         } catch (Exception e) {
321             logger.error("{}: error found while bringing up server", this, e);
322         }
323     }
324
325     @Override
326     public boolean waitedStart(long maxWaitTime) throws InterruptedException {
327         logger.info("{}: WAITED-START", this);
328
329         if (maxWaitTime < 0) {
330             throw new IllegalArgumentException("max-wait-time cannot be negative");
331         }
332
333         long pendingWaitTime = maxWaitTime;
334
335         if (!this.start()) {
336             return false;
337         }
338
339         synchronized (this.startCondition) {
340
341             while (!this.jettyServer.isRunning()) {
342                 try {
343                     long startTs = System.currentTimeMillis();
344
345                     this.startCondition.wait(pendingWaitTime);
346
347                     if (maxWaitTime == 0) {
348                         /* spurious notification */
349                         continue;
350                     }
351
352                     long endTs = System.currentTimeMillis();
353                     pendingWaitTime = pendingWaitTime - (endTs - startTs);
354
355                     logger.info("{}: pending time is {} ms.", this, pendingWaitTime);
356
357                     if (pendingWaitTime <= 0) {
358                         return false;
359                     }
360
361                 } catch (InterruptedException e) {
362                     logger.warn("{}: waited-start has been interrupted", this);
363                     throw e;
364                 }
365             }
366
367             return this.jettyServer.isRunning();
368         }
369     }
370
371     @Override
372     public boolean start() {
373         logger.info("{}: STARTING", this);
374
375         synchronized (this) {
376             if (jettyThread == null || !this.jettyThread.isAlive()) {
377
378                 this.jettyThread = new Thread(this);
379                 this.jettyThread.setName(this.name + "-" + this.port);
380                 this.jettyThread.start();
381             }
382         }
383
384         return true;
385     }
386
387     @Override
388     public boolean stop() {
389         logger.info("{}: STOPPING", this);
390
391         synchronized (this) {
392             if (jettyThread == null) {
393                 return true;
394             }
395
396             if (!jettyThread.isAlive()) {
397                 this.jettyThread = null;
398             }
399
400             try {
401                 this.connector.stop();
402             } catch (Exception e) {
403                 logger.error("{}: error while stopping management server", this, e);
404             }
405
406             try {
407                 this.jettyServer.stop();
408             } catch (Exception e) {
409                 logger.error("{}: error while stopping management server", this, e);
410                 return false;
411             }
412
413             Thread.yield();
414         }
415
416         return true;
417     }
418
419     @Override
420     public void shutdown() {
421         logger.info("{}: SHUTTING DOWN", this);
422
423         this.stop();
424
425         Thread jettyThreadCopy;
426         synchronized (this) {
427             if ((jettyThreadCopy = this.jettyThread) == null) {
428                 return;
429             }
430         }
431
432         if (jettyThreadCopy.isAlive()) {
433             try {
434                 jettyThreadCopy.join(2000L);
435             } catch (InterruptedException e) {
436                 logger.warn("{}: error while shutting down management server", this);
437                 Thread.currentThread().interrupt();
438             }
439             if (!jettyThreadCopy.isInterrupted()) {
440                 try {
441                     jettyThreadCopy.interrupt();
442                 } catch (Exception e) {
443                     // do nothing
444                     logger.warn("{}: exception while shutting down (OK)", this, e);
445                 }
446             }
447         }
448
449         this.jettyServer.destroy();
450     }
451
452     @Override
453     public boolean isAlive() {
454         if (this.jettyThread != null) {
455             return this.jettyThread.isAlive();
456         }
457
458         return false;
459     }
460
461     @Override
462     public int getPort() {
463         return this.port;
464     }
465
466     /**
467      * Get name.
468      *
469      * @return the name
470      */
471     @Override
472     public String getName() {
473         return name;
474     }
475
476     /**
477      * Get host.
478      *
479      * @return the host
480      */
481     public String getHost() {
482         return host;
483     }
484
485     /**
486      * Get user.
487      *
488      * @return the user
489      */
490     public String getUser() {
491         return user;
492     }
493
494     /**
495      * Get password.
496      *
497      * @return the password
498      */
499     @GsonJsonIgnore
500     public String getPassword() {
501         return password;
502     }
503
504     @Override
505     public void setSerializationProvider(String provider) {
506         throw new UnsupportedOperationException("setSerializationProvider()" + NOT_SUPPORTED);
507     }
508
509     @Override
510     public void addServletClass(String servletPath, String restClass) {
511         throw new UnsupportedOperationException("addServletClass()" + NOT_SUPPORTED);
512     }
513
514     @Override
515     public void addServletPackage(String servletPath, String restPackage) {
516         throw new UnsupportedOperationException("addServletPackage()" + NOT_SUPPORTED);
517     }
518
519     @Override
520     public void addServletResource(String servletPath, String resourceBase) {
521         throw new UnsupportedOperationException("addServletResource()" + NOT_SUPPORTED);
522     }
523
524     @Override
525     public String toString() {
526         var builder = new StringBuilder();
527         builder.append("JettyServer [name=").append(name).append(", host=").append(host).append(", port=").append(port)
528                 .append(", user=").append(user).append(", password=").append(password != null).append(", contextPath=")
529                 .append(contextPath).append(", jettyServer=").append(jettyServer).append(", context=")
530                 .append(this.context).append(", connector=").append(connector).append(", jettyThread=")
531                 .append(jettyThread).append("]");
532         return builder.toString();
533     }
534
535 }