Make Cassandra port configurable.
[sdc.git] / openecomp-be / lib / openecomp-core-lib / openecomp-nosqldb-lib / openecomp-nosqldb-core / src / main / java / org / openecomp / core / nosqldb / impl / cassandra / CassandraSessionFactory.java
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
26
27 import com.datastax.driver.core.policies.*;
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         String[] addresses = CassandraUtils.getAddresses();
61         int cassandraPort = CassandraUtils.getCassandraPort();
62         Long reconnectTimeout = CassandraUtils.getReconnectTimeout();
63
64         Cluster.Builder builder = Cluster.builder();
65
66         if(null != reconnectTimeout) {
67             builder.withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectTimeout))
68                     .withRetryPolicy(DefaultRetryPolicy.INSTANCE);
69         }
70
71         builder.withPort(cassandraPort);
72
73         for (String address : addresses) {
74             builder.addContactPoint(address);
75         }
76
77         //Check if ssl
78         Boolean isSsl = CassandraUtils.isSsl();
79         if (isSsl) {
80             builder.withSSL(getSslOptions());
81         }
82
83         //Check if user/pass
84         Boolean isAuthenticate = CassandraUtils.isAuthenticate();
85         if (isAuthenticate) {
86             builder.withCredentials(CassandraUtils.getUser(), CassandraUtils.getPassword());
87         }
88
89         setConsistencyLevel(builder, addresses);
90
91         setLocalDataCenter(builder);
92
93         Cluster cluster = builder.build();
94         String keyStore = SessionContextProviderFactory.getInstance().createInterface().get()
95             .getTenant();
96         LOGGER.info("Cassandra client created hosts: {} port: {} SSL enabled: {} reconnectTimeout",
97                 addresses, cassandraPort, isSsl, reconnectTimeout);
98         return cluster.connect(keyStore);
99     }
100
101     private static void setLocalDataCenter(Cluster.Builder builder) {
102         String localDataCenter = CassandraUtils.getLocalDataCenter();
103         if (Objects.nonNull(localDataCenter)) {
104             LOGGER.info("localDatacenter was provided, setting Cassndra client to use datacenter: {} as local.",
105                     localDataCenter);
106
107             LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(
108                     DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
109             builder.withLoadBalancingPolicy(tokenAwarePolicy);
110         } else {
111             LOGGER.info(
112                     "localDatacenter was provided,  the driver will use the datacenter of the first contact " +
113                             "point that was reached at initialization");
114         }
115     }
116
117     private static void setConsistencyLevel(Cluster.Builder builder, String[] addresses) {
118         if (addresses != null && addresses.length > 1) {
119             String consistencyLevel = CassandraUtils.getConsistencyLevel();
120             if (Objects.nonNull(consistencyLevel)) {
121                 LOGGER.info(
122                         "consistencyLevel was provided, setting Cassandra client to use consistencyLevel: {}" +
123                                 " as "
124                         , consistencyLevel);
125                 builder.withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf
126                         (consistencyLevel)));
127             }
128         }
129     }
130
131     private static SSLOptions getSslOptions() {
132
133         Optional<String> trustStorePath = Optional.ofNullable(CassandraUtils.getTruststore());
134         if (!trustStorePath.isPresent()) {
135             throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePath");
136         }
137
138         Optional<String> trustStorePassword = Optional.ofNullable(CassandraUtils.getTruststorePassword());
139         if (!trustStorePassword.isPresent()) {
140             throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePassword");
141         }
142
143         SSLContext context = getSslContext(trustStorePath.get(), trustStorePassword.get());
144         String[] css = new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"};
145         return RemoteEndpointAwareJdkSSLOptions.builder().withSSLContext(context).withCipherSuites(css).build();
146     }
147
148     private static SSLContext getSslContext(String truststorePath, String trustStorePassword) {
149
150         try (FileInputStream tsf = new FileInputStream(truststorePath)) {
151
152             SSLContext ctx = SSLContext.getInstance("SSL");
153
154             KeyStore ts = KeyStore.getInstance("JKS");
155             ts.load(tsf, trustStorePassword.toCharArray());
156             TrustManagerFactory tmf =
157                     TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
158             tmf.init(ts);
159
160             ctx.init(null, tmf.getTrustManagers(), new SecureRandom());
161             return ctx;
162
163         } catch (Exception exception) {
164             throw new SdcConfigurationException("Failed to get SSL Contexts for Cassandra connection", exception);
165         }
166     }
167
168     private static class ReferenceHolder {
169         private static final Session CASSANDRA = newCassandraSession();
170
171         private ReferenceHolder() {
172             // prevent instantiation
173         }
174     }
175 }