519d7b160bb7392169f3e6189205a27c6489cd30
[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.openecomp.core.nosqldb.util.CassandraUtils;
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.io.IOException;
40 import java.security.KeyManagementException;
41 import java.security.KeyStore;
42 import java.security.KeyStoreException;
43 import java.security.NoSuchAlgorithmException;
44 import java.security.SecureRandom;
45 import java.security.UnrecoverableKeyException;
46 import java.security.cert.CertificateException;
47 import java.util.Objects;
48
49 public class CassandraSessionFactory {
50
51   private static final Logger log = (Logger) LoggerFactory.getLogger
52       (CassandraSessionFactory.class.getName());
53
54   public static Session getSession() {
55     return ReferenceHolder.CASSANDRA;
56   }
57
58   /**
59    * New cassandra session session.
60    *
61    * @return the session
62    */
63   public static Session newCassandraSession() {
64     Cluster.Builder builder = Cluster.builder();
65     String[] addresses = CassandraUtils.getAddresses();
66     for (String address : addresses) {
67       builder.addContactPoint(address);
68     }
69
70     //Check if ssl
71     Boolean isSsl = CassandraUtils.isSsl();
72     if (isSsl) {
73       builder.withSSL(getSslOptions().get());
74     }
75     int port = CassandraUtils.getCassandraPort();
76     if (port > 0) {
77       builder.withPort(port);
78     }
79     //Check if user/pass
80     Boolean isAuthenticate = CassandraUtils.isAuthenticate();
81     if (isAuthenticate) {
82       builder.withCredentials(CassandraUtils.getUser(), CassandraUtils.getPassword());
83     }
84
85     setConsistencyLevel(builder, addresses);
86
87     setLocalDataCenter(builder);
88
89
90     Cluster cluster = builder.build();
91     String keyStore = CassandraUtils.getKeySpace();
92     return cluster.connect(keyStore);
93   }
94
95   private static void setLocalDataCenter(Cluster.Builder builder) {
96     String localDataCenter = CassandraUtils.getLocalDataCenter();
97     if (Objects.nonNull(localDataCenter)) {
98       log.info("localDatacenter was provided, setting Cassndra client to use datacenter: {} as " +
99           "local.", localDataCenter);
100
101       LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(
102           DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
103       builder.withLoadBalancingPolicy(tokenAwarePolicy);
104     } else {
105       log.info(
106           "localDatacenter was provided,  the driver will use the datacenter of the first contact 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         log.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 Optional<SSLOptions> getSslOptions() {
125     Optional<String> truststorePath = Optional.of(CassandraUtils.getTruststore());
126     Optional<String> truststorePassword = Optional.of(CassandraUtils.getTruststorePassword());
127
128     if (truststorePath.isPresent() && truststorePassword.isPresent()) {
129       SSLContext context;
130       try {
131         context = getSslContext(truststorePath.get(), truststorePassword.get());
132       } catch (UnrecoverableKeyException | KeyManagementException
133           | NoSuchAlgorithmException | KeyStoreException | CertificateException
134           | IOException exception) {
135         throw new RuntimeException(exception);
136       }
137       String[] css = new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"};
138       return Optional.of(new SSLOptions(context, css));
139     }
140     return Optional.absent();
141   }
142
143   private static SSLContext getSslContext(String truststorePath, String truststorePassword)
144       throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
145       UnrecoverableKeyException, KeyManagementException {
146     FileInputStream tsf = null;
147     SSLContext ctx = null;
148     try {
149       tsf = new FileInputStream(truststorePath);
150       ctx = SSLContext.getInstance("SSL");
151
152       KeyStore ts = KeyStore.getInstance("JKS");
153       ts.load(tsf, truststorePassword.toCharArray());
154       TrustManagerFactory tmf =
155           TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
156       tmf.init(ts);
157
158       ctx.init(null, tmf.getTrustManagers(), new SecureRandom());
159     } catch (Exception exception) {
160       log.debug("", exception);
161     } finally {
162       if (tsf != null) {
163         tsf.close();
164       }
165     }
166     return ctx;
167   }
168
169   private static class ReferenceHolder {
170     private static final Session CASSANDRA = newCassandraSession();
171   }
172
173
174 }