2 * Copyright © 2016-2017 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.openecomp.core.nosqldb.impl.cassandra;
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.common.session.SessionContextProviderFactory;
30 import org.openecomp.sdc.logging.api.Logger;
31 import org.openecomp.sdc.logging.api.LoggerFactory;
33 import javax.net.ssl.SSLContext;
34 import javax.net.ssl.TrustManagerFactory;
35 import java.io.FileInputStream;
36 import java.security.KeyStore;
37 import java.security.SecureRandom;
38 import java.util.Objects;
39 import java.util.Optional;
41 public class CassandraSessionFactory {
43 private static final Logger LOGGER = LoggerFactory.getLogger(CassandraSessionFactory.class);
45 private CassandraSessionFactory() {
46 // static methods, cannot be instantiated
49 public static Session getSession() {
50 return ReferenceHolder.CASSANDRA;
54 * New cassandra session session.
58 public static Session newCassandraSession() {
59 Cluster.Builder builder = Cluster.builder();
60 String[] addresses = CassandraUtils.getAddresses();
61 for (String address : addresses) {
62 builder.addContactPoint(address);
66 Boolean isSsl = CassandraUtils.isSsl();
68 builder.withSSL(getSslOptions());
70 int port = CassandraUtils.getCassandraPort();
72 builder.withPort(port);
75 Boolean isAuthenticate = CassandraUtils.isAuthenticate();
77 builder.withCredentials(CassandraUtils.getUser(), CassandraUtils.getPassword());
80 setConsistencyLevel(builder, addresses);
82 setLocalDataCenter(builder);
85 Cluster cluster = builder.build();
86 String keyStore = SessionContextProviderFactory.getInstance().createInterface().get()
88 return cluster.connect(keyStore);
91 private static void setLocalDataCenter(Cluster.Builder builder) {
92 String localDataCenter = CassandraUtils.getLocalDataCenter();
93 if (Objects.nonNull(localDataCenter)) {
94 LOGGER.info("localDatacenter was provided, setting Cassndra client to use datacenter: {} as " +
95 "local.", localDataCenter);
97 LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(
98 DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
99 builder.withLoadBalancingPolicy(tokenAwarePolicy);
102 "localDatacenter was provided, the driver will use the datacenter of the first contact " +
103 "point that was reached at initialization");
107 private static void setConsistencyLevel(Cluster.Builder builder, String[] addresses) {
108 if (addresses != null && addresses.length > 1) {
109 String consistencyLevel = CassandraUtils.getConsistencyLevel();
110 if (Objects.nonNull(consistencyLevel)) {
112 "consistencyLevel was provided, setting Cassandra client to use consistencyLevel: {}" +
115 builder.withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf
116 (consistencyLevel)));
121 private static SSLOptions getSslOptions() {
123 Optional<String> trustStorePath = Optional.ofNullable(CassandraUtils.getTruststore());
124 if (!trustStorePath.isPresent()) {
125 throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePath");
128 Optional<String> trustStorePassword = Optional.ofNullable(CassandraUtils.getTruststorePassword());
129 if (!trustStorePassword.isPresent()) {
130 throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePassword");
133 SSLContext context = getSslContext(trustStorePath.get(), trustStorePassword.get());
134 String[] css = new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"};
135 return new SSLOptions(context, css);
138 private static SSLContext getSslContext(String truststorePath, String trustStorePassword) {
140 try (FileInputStream tsf = new FileInputStream(truststorePath)) {
142 SSLContext ctx = SSLContext.getInstance("SSL");
144 KeyStore ts = KeyStore.getInstance("JKS");
145 ts.load(tsf, trustStorePassword.toCharArray());
146 TrustManagerFactory tmf =
147 TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
150 ctx.init(null, tmf.getTrustManagers(), new SecureRandom());
153 } catch (Exception exception) {
154 throw new SdcConfigurationException("Failed to get SSL Contexts for Cassandra connection", exception);
158 private static class ReferenceHolder {
159 private static final Session CASSANDRA = newCassandraSession();
161 private ReferenceHolder() {
162 // prevent instantiation