c6b9160bad1eb79abf4220728399a2126480b093
[sdc.git] /
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.Cluster;
20 import com.datastax.driver.core.ConsistencyLevel;
21 import com.datastax.driver.core.QueryOptions;
22 import com.datastax.driver.core.SSLOptions;
23 import com.datastax.driver.core.Session;
24 import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
25 import com.datastax.driver.core.policies.LoadBalancingPolicy;
26 import com.datastax.driver.core.policies.TokenAwarePolicy;
27 import org.openecomp.core.nosqldb.util.CassandraUtils;
28 import org.openecomp.sdc.common.errors.SdcConfigurationException;
29 import org.openecomp.sdc.logging.api.Logger;
30 import org.openecomp.sdc.logging.api.LoggerFactory;
31
32 import javax.net.ssl.SSLContext;
33 import javax.net.ssl.TrustManagerFactory;
34 import java.io.FileInputStream;
35 import java.security.KeyStore;
36 import java.security.SecureRandom;
37 import java.util.Objects;
38 import java.util.Optional;
39
40 public class CassandraSessionFactory {
41
42     private static final Logger LOGGER = LoggerFactory.getLogger(CassandraSessionFactory.class);
43
44     private CassandraSessionFactory() {
45         // static methods, cannot be instantiated
46     }
47
48     public static Session getSession() {
49         return ReferenceHolder.CASSANDRA;
50     }
51
52     /**
53      * New cassandra session session.
54      *
55      * @return the session
56      */
57     public static Session newCassandraSession() {
58         Cluster.Builder builder = Cluster.builder();
59         String[] addresses = CassandraUtils.getAddresses();
60         for (String address : addresses) {
61             builder.addContactPoint(address);
62         }
63
64         //Check if ssl
65         Boolean isSsl = CassandraUtils.isSsl();
66         if (isSsl) {
67             builder.withSSL(getSslOptions());
68         }
69         int port = CassandraUtils.getCassandraPort();
70         if (port > 0) {
71             builder.withPort(port);
72         }
73         //Check if user/pass
74         Boolean isAuthenticate = CassandraUtils.isAuthenticate();
75         if (isAuthenticate) {
76             builder.withCredentials(CassandraUtils.getUser(), CassandraUtils.getPassword());
77         }
78
79         setConsistencyLevel(builder, addresses);
80
81         setLocalDataCenter(builder);
82
83
84         Cluster cluster = builder.build();
85         String keyStore = CassandraUtils.getKeySpace();
86         return cluster.connect(keyStore);
87     }
88
89     private static void setLocalDataCenter(Cluster.Builder builder) {
90         String localDataCenter = CassandraUtils.getLocalDataCenter();
91         if (Objects.nonNull(localDataCenter)) {
92             LOGGER.info("localDatacenter was provided, setting Cassndra client to use datacenter: {} as " +
93                     "local.", localDataCenter);
94
95             LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(
96                     DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
97             builder.withLoadBalancingPolicy(tokenAwarePolicy);
98         } else {
99             LOGGER.info(
100                     "localDatacenter was provided,  the driver will use the datacenter of the first contact " +
101                             "point that was reached at initialization");
102         }
103     }
104
105     private static void setConsistencyLevel(Cluster.Builder builder, String[] addresses) {
106         if (addresses != null && addresses.length > 1) {
107             String consistencyLevel = CassandraUtils.getConsistencyLevel();
108             if (Objects.nonNull(consistencyLevel)) {
109                 LOGGER.info(
110                         "consistencyLevel was provided, setting Cassandra client to use consistencyLevel: {}" +
111                                 " as "
112                         , consistencyLevel);
113                 builder.withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf
114                         (consistencyLevel)));
115             }
116         }
117     }
118
119     private static SSLOptions getSslOptions() {
120
121         Optional<String> trustStorePath = Optional.ofNullable(CassandraUtils.getTruststore());
122         if (!trustStorePath.isPresent()) {
123             throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePath");
124         }
125
126         Optional<String> trustStorePassword = Optional.ofNullable(CassandraUtils.getTruststorePassword());
127         if (!trustStorePassword.isPresent()) {
128             throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePassword");
129         }
130
131         SSLContext context = getSslContext(trustStorePath.get(), trustStorePassword.get());
132         String[] css = new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"};
133         return new SSLOptions(context, css);
134     }
135
136     private static SSLContext getSslContext(String truststorePath, String trustStorePassword) {
137
138         try (FileInputStream tsf = new FileInputStream(truststorePath)) {
139
140             SSLContext ctx = SSLContext.getInstance("SSL");
141
142             KeyStore ts = KeyStore.getInstance("JKS");
143             ts.load(tsf, trustStorePassword.toCharArray());
144             TrustManagerFactory tmf =
145                     TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
146             tmf.init(ts);
147
148             ctx.init(null, tmf.getTrustManagers(), new SecureRandom());
149             return ctx;
150
151         } catch (Exception exception) {
152             throw new SdcConfigurationException("Failed to get SSL Contexts for Cassandra connection", exception);
153         }
154     }
155
156     private static class ReferenceHolder {
157
158         private ReferenceHolder() {
159             // prevent instantiation
160         }
161
162         private static final Session CASSANDRA = newCassandraSession();
163     }
164
165
166 }