Onboarding foundation changes
[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.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;
32
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;
40
41 public class CassandraSessionFactory {
42
43     private static final Logger LOGGER = LoggerFactory.getLogger(CassandraSessionFactory.class);
44
45     private CassandraSessionFactory() {
46         // static methods, cannot be instantiated
47     }
48
49     public static Session getSession() {
50         return ReferenceHolder.CASSANDRA;
51     }
52
53     /**
54      * New cassandra session session.
55      *
56      * @return the session
57      */
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);
63         }
64
65         //Check if ssl
66         Boolean isSsl = CassandraUtils.isSsl();
67         if (isSsl) {
68             builder.withSSL(getSslOptions());
69         }
70         int port = CassandraUtils.getCassandraPort();
71         if (port > 0) {
72             builder.withPort(port);
73         }
74         //Check if user/pass
75         Boolean isAuthenticate = CassandraUtils.isAuthenticate();
76         if (isAuthenticate) {
77             builder.withCredentials(CassandraUtils.getUser(), CassandraUtils.getPassword());
78         }
79
80         setConsistencyLevel(builder, addresses);
81
82         setLocalDataCenter(builder);
83
84
85         Cluster cluster = builder.build();
86         String keyStore = SessionContextProviderFactory.getInstance().createInterface().get()
87             .getTenant();
88         return cluster.connect(keyStore);
89     }
90
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);
96
97             LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(
98                     DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
99             builder.withLoadBalancingPolicy(tokenAwarePolicy);
100         } else {
101             LOGGER.info(
102                     "localDatacenter was provided,  the driver will use the datacenter of the first contact " +
103                             "point that was reached at initialization");
104         }
105     }
106
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)) {
111                 LOGGER.info(
112                         "consistencyLevel was provided, setting Cassandra client to use consistencyLevel: {}" +
113                                 " as "
114                         , consistencyLevel);
115                 builder.withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf
116                         (consistencyLevel)));
117             }
118         }
119     }
120
121     private static SSLOptions getSslOptions() {
122
123         Optional<String> trustStorePath = Optional.ofNullable(CassandraUtils.getTruststore());
124         if (!trustStorePath.isPresent()) {
125             throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePath");
126         }
127
128         Optional<String> trustStorePassword = Optional.ofNullable(CassandraUtils.getTruststorePassword());
129         if (!trustStorePassword.isPresent()) {
130             throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePassword");
131         }
132
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);
136     }
137
138     private static SSLContext getSslContext(String truststorePath, String trustStorePassword) {
139
140         try (FileInputStream tsf = new FileInputStream(truststorePath)) {
141
142             SSLContext ctx = SSLContext.getInstance("SSL");
143
144             KeyStore ts = KeyStore.getInstance("JKS");
145             ts.load(tsf, trustStorePassword.toCharArray());
146             TrustManagerFactory tmf =
147                     TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
148             tmf.init(ts);
149
150             ctx.init(null, tmf.getTrustManagers(), new SecureRandom());
151             return ctx;
152
153         } catch (Exception exception) {
154             throw new SdcConfigurationException("Failed to get SSL Contexts for Cassandra connection", exception);
155         }
156     }
157
158     private static class ReferenceHolder {
159         private static final Session CASSANDRA = newCassandraSession();
160
161         private ReferenceHolder() {
162             // prevent instantiation
163         }
164     }
165
166
167 }