blob: 720cfd6d320da8a0093587cdb6b5fb4447bb1f0c [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) {
Daniel Parke2658ba2018-08-24 22:33:29 +090085 OvsdbClientService client = getOvsdbClient(osNode, ovsdbPort, ovsdbController);
Daniel Parkc4d06402018-05-28 15:57:37 +090086 return deviceService.isAvailable(osNode.ovsdb()) &&
87 client != null &&
88 client.isConnected();
89 }
Jian Li51b844c2018-05-31 10:59:03 +090090
91 /**
Daniel Parke2658ba2018-08-24 22:33:29 +090092 * Gets the ovsdb client with supplied openstack node.
93 *
94 * @param osNode openstack node
95 * @param ovsdbPort ovsdb port
96 * @param ovsdbController ovsdb controller
97 * @return ovsdb client
98 */
99 public static OvsdbClientService getOvsdbClient(OpenstackNode osNode,
100 int ovsdbPort,
101 OvsdbController ovsdbController) {
102 OvsdbNodeId ovsdb = new OvsdbNodeId(osNode.managementIp(), ovsdbPort);
103 return ovsdbController.getOvsdbClient(ovsdb);
104 }
105
106 /**
Jian Li51b844c2018-05-31 10:59:03 +0900107 * Obtains a connected openstack client.
108 *
109 * @param osNode openstack node
110 * @return a connected openstack client
111 */
112 public static OSClient getConnectedClient(OpenstackNode osNode) {
113 OpenstackAuth auth = osNode.authentication();
114 String endpoint = buildEndpoint(osNode);
115 Perspective perspective = auth.perspective();
116
117 Config config = getSslConfig();
118
119 try {
120 if (endpoint.contains(KEYSTONE_V2)) {
121 IOSClientBuilder.V2 builder = OSFactory.builderV2()
122 .endpoint(endpoint)
123 .tenantName(auth.project())
124 .credentials(auth.username(), auth.password())
125 .withConfig(config);
126
127 if (perspective != null) {
128 builder.perspective(getFacing(perspective));
129 }
130
131 return builder.authenticate();
132 } else if (endpoint.contains(KEYSTONE_V3)) {
133
134 Identifier project = Identifier.byName(auth.project());
135 Identifier domain = Identifier.byName(DOMAIN_DEFAULT);
136
137 IOSClientBuilder.V3 builder = OSFactory.builderV3()
138 .endpoint(endpoint)
139 .credentials(auth.username(), auth.password(), domain)
140 .scopeToProject(project, domain)
141 .withConfig(config);
142
143 if (perspective != null) {
144 builder.perspective(getFacing(perspective));
145 }
146
147 return builder.authenticate();
148 } else {
149 log.warn("Unrecognized keystone version type");
150 return null;
151 }
152 } catch (AuthenticationException e) {
153 log.error("Authentication failed due to {}", e.toString());
154 return null;
155 }
156 }
157
158 /**
Jian Li97482c12018-07-03 01:08:23 +0900159 * Gets Boolean property from the propertyName
160 * Return null if propertyName is not found.
161 *
162 * @param properties properties to be looked up
163 * @param propertyName the name of the property to look up
164 * @return value when the propertyName is defined or return null
165 */
166 public static Boolean getBooleanProperty(Dictionary<?, ?> properties,
167 String propertyName) {
168 Boolean value;
169 try {
170 String s = get(properties, propertyName);
171 value = Strings.isNullOrEmpty(s) ? null : Boolean.valueOf(s);
172 } catch (ClassCastException e) {
173 value = null;
174 }
175 return value;
176 }
177
178 /**
Jian Lif1efbe52018-07-17 23:20:16 +0900179 * Prints out the JSON string in pretty format.
180 *
181 * @param mapper Object mapper
182 * @param jsonString JSON string
183 * @return pretty formatted JSON string
184 */
185 public static String prettyJson(ObjectMapper mapper, String jsonString) {
186 try {
187 Object jsonObject = mapper.readValue(jsonString, Object.class);
188 return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
189 } catch (IOException e) {
190 log.debug("Json string parsing exception caused by {}", e);
191 }
192 return null;
193 }
194
195 /**
Jian Lie3141542018-08-13 18:05:43 +0900196 * Generates a DPID (of:0000000000000001) from an index value.
197 *
198 * @param index index value
199 * @return generated DPID
200 */
201 public static String genDpid(long index) {
202 if (index < 0) {
203 return null;
204 }
205
206 String hexStr = Long.toHexString(index);
207
208 StringBuilder zeroPadding = new StringBuilder();
209 for (int i = 0; i < HEX_LENGTH - hexStr.length(); i++) {
210 zeroPadding.append(ZERO);
211 }
212
213 return OF_PREFIX + zeroPadding.toString() + hexStr;
214 }
215
216 /**
Jian Li51b844c2018-05-31 10:59:03 +0900217 * Builds up and a complete endpoint URL from gateway node.
218 *
219 * @param node gateway node
220 * @return a complete endpoint URL
221 */
222 private static String buildEndpoint(OpenstackNode node) {
223
224 OpenstackAuth auth = node.authentication();
225
226 StringBuilder endpointSb = new StringBuilder();
227 endpointSb.append(auth.protocol().name().toLowerCase());
228 endpointSb.append("://");
Jian Li6d410362018-08-17 09:41:08 +0900229 endpointSb.append(node.endpoint());
Jian Li51b844c2018-05-31 10:59:03 +0900230 return endpointSb.toString();
231 }
232
233 /**
234 * Obtains the SSL config without verifying the certification.
235 *
236 * @return SSL config
237 */
238 private static Config getSslConfig() {
239 // we bypass the SSL certification verification for now
240 // TODO: verify server side SSL using a given certification
241 Config config = Config.newConfig().withSSLVerificationDisabled();
242
243 TrustManager[] trustAllCerts = new TrustManager[]{
244 new X509TrustManager() {
245 public X509Certificate[] getAcceptedIssuers() {
246 return null;
247 }
248
249 public void checkClientTrusted(X509Certificate[] certs,
250 String authType) {
251 }
252
253 public void checkServerTrusted(X509Certificate[] certs,
254 String authType) {
255 }
256 }
257 };
258
259 HostnameVerifier allHostsValid = (hostname, session) -> true;
260
261 try {
262 SSLContext sc = SSLContext.getInstance(SSL_TYPE);
263 sc.init(null, trustAllCerts,
264 new java.security.SecureRandom());
265 HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
266 HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
267
268 config.withSSLContext(sc);
269 } catch (Exception e) {
270 log.error("Failed to access OpenStack service due to {}", e.toString());
271 return null;
272 }
273
274 return config;
275 }
276
277 /**
278 * Obtains the facing object with given openstack perspective.
279 *
280 * @param perspective keystone perspective
281 * @return facing object
282 */
283 private static Facing getFacing(Perspective perspective) {
284
285 switch (perspective) {
286 case PUBLIC:
287 return Facing.PUBLIC;
288 case ADMIN:
289 return Facing.ADMIN;
290 case INTERNAL:
291 return Facing.INTERNAL;
292 default:
293 return null;
294 }
295 }
Daniel Parkc4d06402018-05-28 15:57:37 +0900296}