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