re base code
[sdc.git] / openecomp-be / lib / openecomp-core-lib / openecomp-nosqldb-lib / openecomp-nosqldb-core / src / main / java / org / openecomp / core / nosqldb / impl / cassandra / CassandraSessionFactory.java
1 /*
2  * Copyright © 2016-2017 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.core.nosqldb.impl.cassandra;
18
19 import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
20 import com.datastax.driver.core.policies.LoadBalancingPolicy;
21 import com.datastax.driver.core.policies.TokenAwarePolicy;
22 import com.datastax.driver.core.Cluster;
23 import com.datastax.driver.core.ConsistencyLevel;
24 import com.datastax.driver.core.QueryOptions;
25 import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
26 import com.datastax.driver.core.SSLOptions;
27 import com.datastax.driver.core.Session;
28
29
30 import org.openecomp.core.nosqldb.util.CassandraUtils;
31 import org.openecomp.sdc.common.errors.SdcConfigurationException;
32 import org.openecomp.sdc.common.session.SessionContextProviderFactory;
33 import org.openecomp.sdc.logging.api.Logger;
34 import org.openecomp.sdc.logging.api.LoggerFactory;
35
36 import javax.net.ssl.SSLContext;
37 import javax.net.ssl.TrustManagerFactory;
38 import java.io.FileInputStream;
39 import java.security.KeyStore;
40 import java.security.SecureRandom;
41 import java.util.Objects;
42 import java.util.Optional;
43
44 public class CassandraSessionFactory {
45
46     private static final Logger LOGGER = LoggerFactory.getLogger(CassandraSessionFactory.class);
47
48     private CassandraSessionFactory() {
49         // static methods, cannot be instantiated
50     }
51
52     public static Session getSession() {
53         return ReferenceHolder.CASSANDRA;
54     }
55
56     /**
57      * New cassandra session session.
58      *
59      * @return the session
60      */
61     public static Session newCassandraSession() {
62         Cluster.Builder builder = Cluster.builder();
63         String[] addresses = CassandraUtils.getAddresses();
64         for (String address : addresses) {
65             builder.addContactPoint(address);
66         }
67
68         //Check if ssl
69         Boolean isSsl = CassandraUtils.isSsl();
70         if (isSsl) {
71             builder.withSSL(getSslOptions());
72         }
73         int port = CassandraUtils.getCassandraPort();
74         if (port > 0) {
75             builder.withPort(port);
76         }
77         //Check if user/pass
78         Boolean isAuthenticate = CassandraUtils.isAuthenticate();
79         if (isAuthenticate) {
80             builder.withCredentials(CassandraUtils.getUser(), CassandraUtils.getPassword());
81         }
82
83         setConsistencyLevel(builder, addresses);
84
85         setLocalDataCenter(builder);
86
87
88         Cluster cluster = builder.build();
89         String keyStore = SessionContextProviderFactory.getInstance().createInterface().get()
90             .getTenant();
91         return cluster.connect(keyStore);
92     }
93
94     private static void setLocalDataCenter(Cluster.Builder builder) {
95         String localDataCenter = CassandraUtils.getLocalDataCenter();
96         if (Objects.nonNull(localDataCenter)) {
97             LOGGER.info("localDatacenter was provided, setting Cassndra client to use datacenter: {} as " +
98                     "local.", localDataCenter);
99
100             LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(
101                     DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
102             builder.withLoadBalancingPolicy(tokenAwarePolicy);
103         } else {
104             LOGGER.info(
105                     "localDatacenter was provided,  the driver will use the datacenter of the first contact " +
106                             "point that was reached at initialization");
107         }
108     }
109
110     private static void setConsistencyLevel(Cluster.Builder builder, String[] addresses) {
111         if (addresses != null && addresses.length > 1) {
112             String consistencyLevel = CassandraUtils.getConsistencyLevel();
113             if (Objects.nonNull(consistencyLevel)) {
114                 LOGGER.info(
115                         "consistencyLevel was provided, setting Cassandra client to use consistencyLevel: {}" +
116                                 " as "
117                         , consistencyLevel);
118                 builder.withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf
119                         (consistencyLevel)));
120             }
121         }
122     }
123
124     private static SSLOptions getSslOptions() {
125
126         Optional<String> trustStorePath = Optional.ofNullable(CassandraUtils.getTruststore());
127         if (!trustStorePath.isPresent()) {
128             throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePath");
129         }
130
131         Optional<String> trustStorePassword = Optional.ofNullable(CassandraUtils.getTruststorePassword());
132         if (!trustStorePassword.isPresent()) {
133             throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePassword");
134         }
135
136         SSLContext context = getSslContext(trustStorePath.get(), trustStorePassword.get());
137         String[] css = new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"};
138         return RemoteEndpointAwareJdkSSLOptions.builder().withSSLContext(context).withCipherSuites(css).build();
139     }
140
141     private static SSLContext getSslContext(String truststorePath, String trustStorePassword) {
142
143         try (FileInputStream tsf = new FileInputStream(truststorePath)) {
144
145             SSLContext ctx = SSLContext.getInstance("SSL");
146
147             KeyStore ts = KeyStore.getInstance("JKS");
148             ts.load(tsf, trustStorePassword.toCharArray());
149             TrustManagerFactory tmf =
150                     TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
151             tmf.init(ts);
152
153             ctx.init(null, tmf.getTrustManagers(), new SecureRandom());
154             return ctx;
155
156         } catch (Exception exception) {
157             throw new SdcConfigurationException("Failed to get SSL Contexts for Cassandra connection", exception);
158         }
159     }
160
161     private static class ReferenceHolder {
162         private static final Session CASSANDRA = newCassandraSession();
163
164         private ReferenceHolder() {
165             // prevent instantiation
166         }
167     }
168
169
170 }