blob: e970b2b5ffc645647ff71ab76b35fc3a378e55ad [file] [log] [blame]
Daniel Parkc4d06402018-05-28 15:57:37 +09001/*
2 * Copyright 2018-present Open Networking Foundation
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 */
16package org.onosproject.openstacknode.util;
17
Jian Lif1efbe52018-07-17 23:20:16 +090018import com.fasterxml.jackson.databind.ObjectMapper;
Jian Li97482c12018-07-03 01:08:23 +090019import com.google.common.base.Strings;
Daniel Parkc4d06402018-05-28 15:57:37 +090020import org.onosproject.net.device.DeviceService;
Jian Li51b844c2018-05-31 10:59:03 +090021import org.onosproject.openstacknode.api.OpenstackAuth;
22import org.onosproject.openstacknode.api.OpenstackAuth.Perspective;
Daniel Parkc4d06402018-05-28 15:57:37 +090023import org.onosproject.openstacknode.api.OpenstackNode;
24import org.onosproject.ovsdb.controller.OvsdbClientService;
25import org.onosproject.ovsdb.controller.OvsdbController;
26import org.onosproject.ovsdb.controller.OvsdbNodeId;
Jian Li51b844c2018-05-31 10:59:03 +090027import org.openstack4j.api.OSClient;
28import org.openstack4j.api.client.IOSClientBuilder;
29import org.openstack4j.api.exceptions.AuthenticationException;
30import org.openstack4j.api.types.Facing;
31import org.openstack4j.core.transport.Config;
32import org.openstack4j.model.common.Identifier;
33import org.openstack4j.openstack.OSFactory;
Daniel Parkc4d06402018-05-28 15:57:37 +090034import org.slf4j.Logger;
35import org.slf4j.LoggerFactory;
36
Jian Li51b844c2018-05-31 10:59:03 +090037import javax.net.ssl.HostnameVerifier;
38import javax.net.ssl.HttpsURLConnection;
39import javax.net.ssl.SSLContext;
40import javax.net.ssl.TrustManager;
41import javax.net.ssl.X509TrustManager;
Jian Lif1efbe52018-07-17 23:20:16 +090042import java.io.IOException;
Jian Li51b844c2018-05-31 10:59:03 +090043import java.security.cert.X509Certificate;
Jian Li97482c12018-07-03 01:08:23 +090044import java.util.Dictionary;
45
46import static org.onlab.util.Tools.get;
Jian Li51b844c2018-05-31 10:59:03 +090047
Daniel Parkc4d06402018-05-28 15:57:37 +090048/**
49 * An utility that used in openstack node app.
50 */
51public final class OpenstackNodeUtil {
Daniel Park95985382018-07-23 11:38:07 +090052 private static final Logger log = LoggerFactory.getLogger(OpenstackNodeUtil.class);
Daniel Parkc4d06402018-05-28 15:57:37 +090053
Jian Li51b844c2018-05-31 10:59:03 +090054 // keystone endpoint related variables
55 private static final String DOMAIN_DEFAULT = "default";
56 private static final String KEYSTONE_V2 = "v2.0";
57 private static final String KEYSTONE_V3 = "v3";
58 private static final String IDENTITY_PATH = "identity/";
59 private static final String SSL_TYPE = "SSL";
60
Jian Lie3141542018-08-13 18:05:43 +090061 private static final int HEX_LENGTH = 16;
62 private static final String OF_PREFIX = "of:";
63 private static final String ZERO = "0";
64
Daniel Parkc4d06402018-05-28 15:57:37 +090065 /**
Jian Li51b844c2018-05-31 10:59:03 +090066 * Prevents object installation from external.
Daniel Parkc4d06402018-05-28 15:57:37 +090067 */
68 private OpenstackNodeUtil() {
69 }
70
71 /**
72 * Checks whether the controller has a connection with an OVSDB that resides
73 * inside the given openstack node.
74 *
75 * @param osNode openstack node
76 * @param ovsdbPort ovsdb port
77 * @param ovsdbController ovsdb controller
78 * @param deviceService device service
79 * @return true if the controller is connected to the OVSDB, false otherwise
80 */
81 public static boolean isOvsdbConnected(OpenstackNode osNode,
82 int ovsdbPort,
83 OvsdbController ovsdbController,
84 DeviceService deviceService) {
85 OvsdbNodeId ovsdb = new OvsdbNodeId(osNode.managementIp(), ovsdbPort);
86 OvsdbClientService client = ovsdbController.getOvsdbClient(ovsdb);
87 return deviceService.isAvailable(osNode.ovsdb()) &&
88 client != null &&
89 client.isConnected();
90 }
Jian Li51b844c2018-05-31 10:59:03 +090091
92 /**
93 * Obtains a connected openstack client.
94 *
95 * @param osNode openstack node
96 * @return a connected openstack client
97 */
98 public static OSClient getConnectedClient(OpenstackNode osNode) {
99 OpenstackAuth auth = osNode.authentication();
100 String endpoint = buildEndpoint(osNode);
101 Perspective perspective = auth.perspective();
102
103 Config config = getSslConfig();
104
105 try {
106 if (endpoint.contains(KEYSTONE_V2)) {
107 IOSClientBuilder.V2 builder = OSFactory.builderV2()
108 .endpoint(endpoint)
109 .tenantName(auth.project())
110 .credentials(auth.username(), auth.password())
111 .withConfig(config);
112
113 if (perspective != null) {
114 builder.perspective(getFacing(perspective));
115 }
116
117 return builder.authenticate();
118 } else if (endpoint.contains(KEYSTONE_V3)) {
119
120 Identifier project = Identifier.byName(auth.project());
121 Identifier domain = Identifier.byName(DOMAIN_DEFAULT);
122
123 IOSClientBuilder.V3 builder = OSFactory.builderV3()
124 .endpoint(endpoint)
125 .credentials(auth.username(), auth.password(), domain)
126 .scopeToProject(project, domain)
127 .withConfig(config);
128
129 if (perspective != null) {
130 builder.perspective(getFacing(perspective));
131 }
132
133 return builder.authenticate();
134 } else {
135 log.warn("Unrecognized keystone version type");
136 return null;
137 }
138 } catch (AuthenticationException e) {
139 log.error("Authentication failed due to {}", e.toString());
140 return null;
141 }
142 }
143
144 /**
Jian Li97482c12018-07-03 01:08:23 +0900145 * Gets Boolean property from the propertyName
146 * Return null if propertyName is not found.
147 *
148 * @param properties properties to be looked up
149 * @param propertyName the name of the property to look up
150 * @return value when the propertyName is defined or return null
151 */
152 public static Boolean getBooleanProperty(Dictionary<?, ?> properties,
153 String propertyName) {
154 Boolean value;
155 try {
156 String s = get(properties, propertyName);
157 value = Strings.isNullOrEmpty(s) ? null : Boolean.valueOf(s);
158 } catch (ClassCastException e) {
159 value = null;
160 }
161 return value;
162 }
163
164 /**
Jian Lif1efbe52018-07-17 23:20:16 +0900165 * Prints out the JSON string in pretty format.
166 *
167 * @param mapper Object mapper
168 * @param jsonString JSON string
169 * @return pretty formatted JSON string
170 */
171 public static String prettyJson(ObjectMapper mapper, String jsonString) {
172 try {
173 Object jsonObject = mapper.readValue(jsonString, Object.class);
174 return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
175 } catch (IOException e) {
176 log.debug("Json string parsing exception caused by {}", e);
177 }
178 return null;
179 }
180
181 /**
Jian Lie3141542018-08-13 18:05:43 +0900182 * Generates a DPID (of:0000000000000001) from an index value.
183 *
184 * @param index index value
185 * @return generated DPID
186 */
187 public static String genDpid(long index) {
188 if (index < 0) {
189 return null;
190 }
191
192 String hexStr = Long.toHexString(index);
193
194 StringBuilder zeroPadding = new StringBuilder();
195 for (int i = 0; i < HEX_LENGTH - hexStr.length(); i++) {
196 zeroPadding.append(ZERO);
197 }
198
199 return OF_PREFIX + zeroPadding.toString() + hexStr;
200 }
201
202 /**
Jian Li51b844c2018-05-31 10:59:03 +0900203 * Builds up and a complete endpoint URL from gateway node.
204 *
205 * @param node gateway node
206 * @return a complete endpoint URL
207 */
208 private static String buildEndpoint(OpenstackNode node) {
209
210 OpenstackAuth auth = node.authentication();
211
212 StringBuilder endpointSb = new StringBuilder();
213 endpointSb.append(auth.protocol().name().toLowerCase());
214 endpointSb.append("://");
215 endpointSb.append(node.endPoint());
216 endpointSb.append(":");
217 endpointSb.append(auth.port());
218 endpointSb.append("/");
219
220 // in case the version is v3, we need to append identity path into endpoint
221 if (auth.version().equals(KEYSTONE_V3)) {
222 endpointSb.append(IDENTITY_PATH);
223 }
224
225 endpointSb.append(auth.version());
226 return endpointSb.toString();
227 }
228
229 /**
230 * Obtains the SSL config without verifying the certification.
231 *
232 * @return SSL config
233 */
234 private static Config getSslConfig() {
235 // we bypass the SSL certification verification for now
236 // TODO: verify server side SSL using a given certification
237 Config config = Config.newConfig().withSSLVerificationDisabled();
238
239 TrustManager[] trustAllCerts = new TrustManager[]{
240 new X509TrustManager() {
241 public X509Certificate[] getAcceptedIssuers() {
242 return null;
243 }
244
245 public void checkClientTrusted(X509Certificate[] certs,
246 String authType) {
247 }
248
249 public void checkServerTrusted(X509Certificate[] certs,
250 String authType) {
251 }
252 }
253 };
254
255 HostnameVerifier allHostsValid = (hostname, session) -> true;
256
257 try {
258 SSLContext sc = SSLContext.getInstance(SSL_TYPE);
259 sc.init(null, trustAllCerts,
260 new java.security.SecureRandom());
261 HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
262 HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
263
264 config.withSSLContext(sc);
265 } catch (Exception e) {
266 log.error("Failed to access OpenStack service due to {}", e.toString());
267 return null;
268 }
269
270 return config;
271 }
272
273 /**
274 * Obtains the facing object with given openstack perspective.
275 *
276 * @param perspective keystone perspective
277 * @return facing object
278 */
279 private static Facing getFacing(Perspective perspective) {
280
281 switch (perspective) {
282 case PUBLIC:
283 return Facing.PUBLIC;
284 case ADMIN:
285 return Facing.ADMIN;
286 case INTERNAL:
287 return Facing.INTERNAL;
288 default:
289 return null;
290 }
291 }
Daniel Parkc4d06402018-05-28 15:57:37 +0900292}