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