blob: 8c972e89c27c302b318d93fa1cd1db66c9fcce52 [file] [log] [blame]
Jian Li091d8d22018-02-20 10:42:06 +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.openstacknetworking.util;
17
Daniel Park2ff66b42018-08-01 11:52:45 +090018import com.fasterxml.jackson.core.JsonParseException;
19import com.fasterxml.jackson.core.JsonProcessingException;
20import com.fasterxml.jackson.databind.JsonMappingException;
Jian Li091d8d22018-02-20 10:42:06 +090021import com.fasterxml.jackson.databind.JsonNode;
22import com.fasterxml.jackson.databind.ObjectMapper;
Jian Lieb9f77d2018-02-20 11:25:45 +090023import com.fasterxml.jackson.databind.node.ObjectNode;
Jian Li24ec59f2018-05-23 19:01:25 +090024import com.google.common.base.Strings;
Jian Li63430202018-08-30 16:24:09 +090025import org.apache.commons.codec.binary.Hex;
26import org.apache.http.HttpException;
27import org.apache.http.HttpRequest;
28import org.apache.http.HttpResponse;
29import org.apache.http.impl.io.DefaultHttpRequestParser;
30import org.apache.http.impl.io.DefaultHttpRequestWriter;
31import org.apache.http.impl.io.DefaultHttpResponseParser;
32import org.apache.http.impl.io.DefaultHttpResponseWriter;
33import org.apache.http.impl.io.HttpTransportMetricsImpl;
34import org.apache.http.impl.io.SessionInputBufferImpl;
35import org.apache.http.impl.io.SessionOutputBufferImpl;
36import org.apache.http.io.HttpMessageWriter;
Jian Li7f70bb72018-07-06 23:35:30 +090037import org.onosproject.cfg.ConfigProperty;
Jian Li1064e4f2018-05-29 16:16:53 +090038import org.onosproject.net.DeviceId;
Daniel Park95f73312018-07-31 15:48:34 +090039import org.onosproject.net.device.DeviceService;
Daniel Park7e8c4d82018-08-13 23:47:49 +090040import org.onosproject.openstacknetworking.api.Constants.VnicType;
Jian Lia171a432018-06-11 11:52:11 +090041import org.onosproject.openstacknetworking.api.InstancePort;
Jian Li24ec59f2018-05-23 19:01:25 +090042import org.onosproject.openstacknetworking.api.OpenstackNetworkService;
Jian Li7f70bb72018-07-06 23:35:30 +090043import org.onosproject.openstacknetworking.api.OpenstackRouterAdminService;
Jian Liec5c32b2018-07-13 14:28:58 +090044import org.onosproject.openstacknetworking.impl.DefaultInstancePort;
Jian Li51b844c2018-05-31 10:59:03 +090045import org.onosproject.openstacknode.api.OpenstackAuth;
46import org.onosproject.openstacknode.api.OpenstackAuth.Perspective;
Jian Li1064e4f2018-05-29 16:16:53 +090047import org.onosproject.openstacknode.api.OpenstackNode;
Jian Li51b844c2018-05-31 10:59:03 +090048import org.openstack4j.api.OSClient;
49import org.openstack4j.api.client.IOSClientBuilder;
50import org.openstack4j.api.exceptions.AuthenticationException;
51import org.openstack4j.api.types.Facing;
52import org.openstack4j.core.transport.Config;
Jian Li091d8d22018-02-20 10:42:06 +090053import org.openstack4j.core.transport.ObjectMapperSingleton;
54import org.openstack4j.model.ModelEntity;
Jian Li51b844c2018-05-31 10:59:03 +090055import org.openstack4j.model.common.Identifier;
Jian Li24ec59f2018-05-23 19:01:25 +090056import org.openstack4j.model.network.NetFloatingIP;
57import org.openstack4j.model.network.Network;
Jian Lia171a432018-06-11 11:52:11 +090058import org.openstack4j.model.network.Port;
Jian Li0b564282018-06-20 00:50:53 +090059import org.openstack4j.model.network.RouterInterface;
Jian Li51b844c2018-05-31 10:59:03 +090060import org.openstack4j.openstack.OSFactory;
Jian Li0b564282018-06-20 00:50:53 +090061import org.openstack4j.openstack.networking.domain.NeutronRouterInterface;
Jian Li091d8d22018-02-20 10:42:06 +090062import org.slf4j.Logger;
63import org.slf4j.LoggerFactory;
64
Jian Li63430202018-08-30 16:24:09 +090065import javax.crypto.Mac;
66import javax.crypto.spec.SecretKeySpec;
Jian Li51b844c2018-05-31 10:59:03 +090067import javax.net.ssl.HostnameVerifier;
68import javax.net.ssl.HttpsURLConnection;
69import javax.net.ssl.SSLContext;
70import javax.net.ssl.TrustManager;
71import javax.net.ssl.X509TrustManager;
Jian Li63430202018-08-30 16:24:09 +090072import java.io.ByteArrayInputStream;
73import java.io.ByteArrayOutputStream;
Jian Li0b564282018-06-20 00:50:53 +090074import java.io.IOException;
Jian Li091d8d22018-02-20 10:42:06 +090075import java.io.InputStream;
Jian Li51b844c2018-05-31 10:59:03 +090076import java.security.cert.X509Certificate;
Jian Li1064e4f2018-05-29 16:16:53 +090077import java.util.HashMap;
78import java.util.Iterator;
79import java.util.Map;
Daniel Park95f73312018-07-31 15:48:34 +090080import java.util.Objects;
Jian Li7f70bb72018-07-06 23:35:30 +090081import java.util.Optional;
Jian Li1064e4f2018-05-29 16:16:53 +090082import java.util.Set;
83import java.util.TreeMap;
Jian Li091d8d22018-02-20 10:42:06 +090084
85import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT;
Daniel Park95f73312018-07-31 15:48:34 +090086import static com.google.common.base.Preconditions.checkNotNull;
Jian Li7f024de2018-07-07 03:51:02 +090087import static com.google.common.base.Strings.isNullOrEmpty;
Daniel Park95f73312018-07-31 15:48:34 +090088import static org.onosproject.net.AnnotationKeys.PORT_NAME;
Daniel Parkc4d06402018-05-28 15:57:37 +090089import static org.onosproject.openstacknetworking.api.Constants.PCISLOT;
90import static org.onosproject.openstacknetworking.api.Constants.PCI_VENDOR_INFO;
Daniel Park7e8c4d82018-08-13 23:47:49 +090091import static org.onosproject.openstacknetworking.api.Constants.PORT_NAME_PREFIX_VM;
92import static org.onosproject.openstacknetworking.api.Constants.PORT_NAME_VHOST_USER_PREFIX_VM;
Daniel Parkec9d1132018-08-19 11:18:03 +090093import static org.onosproject.openstacknetworking.api.Constants.UNSUPPORTED_VENDOR;
Ray Milkey9dc57392018-06-08 08:52:31 -070094import static org.onosproject.openstacknetworking.api.Constants.portNamePrefixMap;
Jian Li0b564282018-06-20 00:50:53 +090095import static org.openstack4j.core.transport.ObjectMapperSingleton.getContext;
Jian Li091d8d22018-02-20 10:42:06 +090096
97/**
98 * An utility that used in openstack networking app.
99 */
Jian Lidea0fdb2018-04-02 19:02:48 +0900100public final class OpenstackNetworkingUtil {
Jian Li091d8d22018-02-20 10:42:06 +0900101
Daniel Park95985382018-07-23 11:38:07 +0900102 private static final Logger log = LoggerFactory.getLogger(OpenstackNetworkingUtil.class);
Jian Li091d8d22018-02-20 10:42:06 +0900103
Daniel Parkc4d06402018-05-28 15:57:37 +0900104 private static final int HEX_RADIX = 16;
Jian Li51b844c2018-05-31 10:59:03 +0900105 private static final String ZERO_FUNCTION_NUMBER = "0";
Daniel Parkc4d06402018-05-28 15:57:37 +0900106 private static final String PREFIX_DEVICE_NUMBER = "s";
107 private static final String PREFIX_FUNCTION_NUMBER = "f";
108
Jian Li51b844c2018-05-31 10:59:03 +0900109 // keystone endpoint related variables
110 private static final String DOMAIN_DEFAULT = "default";
111 private static final String KEYSTONE_V2 = "v2.0";
112 private static final String KEYSTONE_V3 = "v3";
Jian Li51b844c2018-05-31 10:59:03 +0900113 private static final String SSL_TYPE = "SSL";
114
Jian Li7f024de2018-07-07 03:51:02 +0900115 private static final String PROXY_MODE = "proxy";
116 private static final String BROADCAST_MODE = "broadcast";
117
Jian Li63430202018-08-30 16:24:09 +0900118 private static final int HTTP_PAYLOAD_BUFFER = 8 * 1024;
119
120 private static final String HMAC_SHA256 = "HmacSHA256";
121
Jian Li24ec59f2018-05-23 19:01:25 +0900122 private static final String ERR_FLOW = "Failed set flows for floating IP %s: ";
123
Jian Li091d8d22018-02-20 10:42:06 +0900124 /**
125 * Prevents object instantiation from external.
126 */
Jian Lidea0fdb2018-04-02 19:02:48 +0900127 private OpenstackNetworkingUtil() {
Jian Li091d8d22018-02-20 10:42:06 +0900128 }
129
130 /**
131 * Interprets JSON string to corresponding openstack model entity object.
132 *
133 * @param input JSON string
134 * @param entityClazz openstack model entity class
135 * @return openstack model entity object
136 */
137 public static ModelEntity jsonToModelEntity(InputStream input, Class entityClazz) {
138 ObjectMapper mapper = new ObjectMapper();
139 try {
140 JsonNode jsonTree = mapper.enable(INDENT_OUTPUT).readTree(input);
141 log.trace(new ObjectMapper().writeValueAsString(jsonTree));
142 return ObjectMapperSingleton.getContext(entityClazz)
143 .readerFor(entityClazz)
144 .readValue(jsonTree);
145 } catch (Exception e) {
146 throw new IllegalArgumentException();
147 }
148 }
Jian Lieb9f77d2018-02-20 11:25:45 +0900149
150 /**
151 * Converts openstack model entity object into JSON object.
152 *
153 * @param entity openstack model entity object
154 * @param entityClazz openstack model entity class
155 * @return JSON object
156 */
157 public static ObjectNode modelEntityToJson(ModelEntity entity, Class entityClazz) {
158 ObjectMapper mapper = new ObjectMapper();
159 try {
160 String strModelEntity = ObjectMapperSingleton.getContext(entityClazz)
161 .writerFor(entityClazz)
162 .writeValueAsString(entity);
163 log.trace(strModelEntity);
164 return (ObjectNode) mapper.readTree(strModelEntity.getBytes());
Daniel Park95985382018-07-23 11:38:07 +0900165 } catch (IOException e) {
166 log.error("IOException occurred because of {}", e.toString());
Jian Lieb9f77d2018-02-20 11:25:45 +0900167 throw new IllegalStateException();
168 }
169 }
Jian Li1064e4f2018-05-29 16:16:53 +0900170
171 /**
Jian Li24ec59f2018-05-23 19:01:25 +0900172 * Obtains a floating IP associated with the given instance port.
173 *
174 * @param port instance port
175 * @param fips a collection of floating IPs
176 * @return associated floating IP
177 */
178 public static NetFloatingIP associatedFloatingIp(InstancePort port,
179 Set<NetFloatingIP> fips) {
Daniel Park2ff66b42018-08-01 11:52:45 +0900180 for (NetFloatingIP fip : fips) {
181 if (Strings.isNullOrEmpty(fip.getFixedIpAddress())) {
182 continue;
Jian Li24ec59f2018-05-23 19:01:25 +0900183 }
Daniel Park2ff66b42018-08-01 11:52:45 +0900184 if (Strings.isNullOrEmpty(fip.getFloatingIpAddress())) {
185 continue;
186 }
187 if (fip.getFixedIpAddress().equals(port.ipAddress().toString())) {
188 return fip;
189 }
Jian Li24ec59f2018-05-23 19:01:25 +0900190 }
Daniel Park2ff66b42018-08-01 11:52:45 +0900191
Jian Li24ec59f2018-05-23 19:01:25 +0900192 return null;
193 }
194
195 /**
196 * Checks whether the given floating IP is associated with a VM.
197 *
198 * @param service openstack network service
199 * @param fip floating IP
200 * @return true if the given floating IP associated with a VM, false otherwise
201 */
202 public static boolean isAssociatedWithVM(OpenstackNetworkService service,
203 NetFloatingIP fip) {
204 Port osPort = service.port(fip.getPortId());
205 if (osPort == null) {
206 return false;
207 }
208
209 if (!Strings.isNullOrEmpty(osPort.getDeviceId())) {
210 Network osNet = service.network(osPort.getNetworkId());
211 if (osNet == null) {
212 final String errorFormat = ERR_FLOW + "no network(%s) exists";
213 final String error = String.format(errorFormat,
214 fip.getFloatingIpAddress(), osPort.getNetworkId());
215 throw new IllegalStateException(error);
216 }
217 return true;
218 } else {
219 return false;
220 }
221 }
222
223 /**
Jian Lia171a432018-06-11 11:52:11 +0900224 * Obtains the gateway node by instance port.
225 *
226 * @param gateways a collection of gateway nodes
227 * @param instPort instance port
228 * @return a gateway node
229 */
230 public static OpenstackNode getGwByInstancePort(Set<OpenstackNode> gateways,
231 InstancePort instPort) {
232 OpenstackNode gw = null;
233 if (instPort != null && instPort.deviceId() != null) {
234 gw = getGwByComputeDevId(gateways, instPort.deviceId());
235 }
236 return gw;
237 }
238
239 /**
Jian Li1064e4f2018-05-29 16:16:53 +0900240 * Obtains the gateway node by device in compute node. Note that the gateway
241 * node is determined by device's device identifier.
242 *
243 * @param gws a collection of gateway nodes
244 * @param deviceId device identifier
245 * @return a gateway node
246 */
247 public static OpenstackNode getGwByComputeDevId(Set<OpenstackNode> gws, DeviceId deviceId) {
248 int numOfGw = gws.size();
249
250 if (numOfGw == 0) {
251 return null;
252 }
253
254 int gwIndex = Math.abs(deviceId.hashCode()) % numOfGw;
255
256 return getGwByIndex(gws, gwIndex);
257 }
258
Jian Li51b844c2018-05-31 10:59:03 +0900259 /**
260 * Obtains a connected openstack client.
261 *
262 * @param osNode openstack node
263 * @return a connected openstack client
264 */
265 public static OSClient getConnectedClient(OpenstackNode osNode) {
266 OpenstackAuth auth = osNode.authentication();
267 String endpoint = buildEndpoint(osNode);
268 Perspective perspective = auth.perspective();
Jian Li1064e4f2018-05-29 16:16:53 +0900269
Jian Li51b844c2018-05-31 10:59:03 +0900270 Config config = getSslConfig();
Jian Li1064e4f2018-05-29 16:16:53 +0900271
Jian Li51b844c2018-05-31 10:59:03 +0900272 try {
273 if (endpoint.contains(KEYSTONE_V2)) {
274 IOSClientBuilder.V2 builder = OSFactory.builderV2()
275 .endpoint(endpoint)
276 .tenantName(auth.project())
277 .credentials(auth.username(), auth.password())
278 .withConfig(config);
279
280 if (perspective != null) {
281 builder.perspective(getFacing(perspective));
282 }
283
284 return builder.authenticate();
285 } else if (endpoint.contains(KEYSTONE_V3)) {
286
287 Identifier project = Identifier.byName(auth.project());
288 Identifier domain = Identifier.byName(DOMAIN_DEFAULT);
289
290 IOSClientBuilder.V3 builder = OSFactory.builderV3()
291 .endpoint(endpoint)
292 .credentials(auth.username(), auth.password(), domain)
293 .scopeToProject(project, domain)
294 .withConfig(config);
295
296 if (perspective != null) {
297 builder.perspective(getFacing(perspective));
298 }
299
300 return builder.authenticate();
301 } else {
302 log.warn("Unrecognized keystone version type");
303 return null;
Jian Li1064e4f2018-05-29 16:16:53 +0900304 }
Jian Li51b844c2018-05-31 10:59:03 +0900305 } catch (AuthenticationException e) {
306 log.error("Authentication failed due to {}", e.toString());
307 return null;
Jian Li1064e4f2018-05-29 16:16:53 +0900308 }
Jian Li1064e4f2018-05-29 16:16:53 +0900309 }
Daniel Parkc4d06402018-05-28 15:57:37 +0900310
311 /**
312 * Extract the interface name with the supplied port.
313 *
314 * @param port port
315 * @return interface name
316 */
317 public static String getIntfNameFromPciAddress(Port port) {
Daniel Park95985382018-07-23 11:38:07 +0900318 if (port.getProfile() == null || port.getProfile().isEmpty()) {
Jian Li51b844c2018-05-31 10:59:03 +0900319 log.error("Port profile is not found");
320 return null;
321 }
322
Daniel Park95985382018-07-23 11:38:07 +0900323 if (!port.getProfile().containsKey(PCISLOT) ||
324 Strings.isNullOrEmpty(port.getProfile().get(PCISLOT).toString())) {
Daniel Parkc4d06402018-05-28 15:57:37 +0900325 log.error("Failed to retrieve the interface name because of no pci_slot information from the port");
326 return null;
327 }
Jian Li51b844c2018-05-31 10:59:03 +0900328
Daniel Parkc4d06402018-05-28 15:57:37 +0900329 String busNumHex = port.getProfile().get(PCISLOT).toString().split(":")[1];
330 String busNumDecimal = String.valueOf(Integer.parseInt(busNumHex, HEX_RADIX));
331
332 String deviceNumHex = port.getProfile().get(PCISLOT).toString()
333 .split(":")[2]
334 .split("\\.")[0];
335 String deviceNumDecimal = String.valueOf(Integer.parseInt(deviceNumHex, HEX_RADIX));
336
337 String functionNumHex = port.getProfile().get(PCISLOT).toString()
338 .split(":")[2]
339 .split("\\.")[1];
340 String functionNumDecimal = String.valueOf(Integer.parseInt(functionNumHex, HEX_RADIX));
341
342 String intfName;
343
344 String vendorInfoForPort = String.valueOf(port.getProfile().get(PCI_VENDOR_INFO));
345
Daniel Park95985382018-07-23 11:38:07 +0900346 if (!portNamePrefixMap().containsKey(vendorInfoForPort)) {
Daniel Parkec9d1132018-08-19 11:18:03 +0900347 log.warn("Failed to retrieve the interface name because of unsupported prefix for vendor ID {}",
Daniel Park95985382018-07-23 11:38:07 +0900348 vendorInfoForPort);
Daniel Parkec9d1132018-08-19 11:18:03 +0900349 return UNSUPPORTED_VENDOR;
Daniel Parkc4d06402018-05-28 15:57:37 +0900350 }
Ray Milkey9dc57392018-06-08 08:52:31 -0700351 String portNamePrefix = portNamePrefixMap().get(vendorInfoForPort);
Jian Li51b844c2018-05-31 10:59:03 +0900352
Daniel Parkc4d06402018-05-28 15:57:37 +0900353 if (functionNumDecimal.equals(ZERO_FUNCTION_NUMBER)) {
354 intfName = portNamePrefix + busNumDecimal + PREFIX_DEVICE_NUMBER + deviceNumDecimal;
355 } else {
356 intfName = portNamePrefix + busNumDecimal + PREFIX_DEVICE_NUMBER + deviceNumDecimal
357 + PREFIX_FUNCTION_NUMBER + functionNumDecimal;
358 }
359
360 return intfName;
361 }
Jian Li51b844c2018-05-31 10:59:03 +0900362
363 /**
Daniel Park95f73312018-07-31 15:48:34 +0900364 * Check if the given interface is added to the given device or not.
365 *
366 * @param deviceId device ID
367 * @param intfName interface name
368 * @param deviceService device service
369 * @return true if the given interface is added to the given device or false otherwise
370 */
371 public static boolean hasIntfAleadyInDevice(DeviceId deviceId, String intfName, DeviceService deviceService) {
372 checkNotNull(deviceId);
373 checkNotNull(intfName);
374
375 return deviceService.getPorts(deviceId).stream()
376 .anyMatch(port -> Objects.equals(port.annotations().value(PORT_NAME), intfName));
377 }
378
379 /**
Jian Li0b564282018-06-20 00:50:53 +0900380 * Adds router interfaces to openstack admin service.
381 * TODO fix the logic to add router interface to router
382 *
383 * @param osPort port
384 * @param adminService openstack admin service
385 */
386 public static void addRouterIface(Port osPort, OpenstackRouterAdminService adminService) {
387 osPort.getFixedIps().forEach(p -> {
388 JsonNode jsonTree = new ObjectMapper().createObjectNode()
389 .put("id", osPort.getDeviceId())
390 .put("tenant_id", osPort.getTenantId())
391 .put("subnet_id", p.getSubnetId())
392 .put("port_id", osPort.getId());
393 try {
394 RouterInterface rIface = getContext(NeutronRouterInterface.class)
395 .readerFor(NeutronRouterInterface.class)
396 .readValue(jsonTree);
397 if (adminService.routerInterface(rIface.getPortId()) != null) {
398 adminService.updateRouterInterface(rIface);
399 } else {
400 adminService.addRouterInterface(rIface);
401 }
402 } catch (IOException ignore) {
Daniel Park2ff66b42018-08-01 11:52:45 +0900403 log.error("Exception occurred because of {}", ignore.toString());
Jian Li0b564282018-06-20 00:50:53 +0900404 }
405 });
406 }
407
408 /**
Jian Li7f70bb72018-07-06 23:35:30 +0900409 * Obtains the property value with specified property key name.
410 *
411 * @param properties a collection of properties
412 * @param name key name
413 * @return mapping value
414 */
415 public static String getPropertyValue(Set<ConfigProperty> properties, String name) {
416 Optional<ConfigProperty> property =
417 properties.stream().filter(p -> p.name().equals(name)).findFirst();
418 return property.map(ConfigProperty::value).orElse(null);
419 }
420
421 /**
Jian Lif1efbe52018-07-17 23:20:16 +0900422 * Prints out the JSON string in pretty format.
423 *
424 * @param mapper Object mapper
425 * @param jsonString JSON string
426 * @return pretty formatted JSON string
427 */
428 public static String prettyJson(ObjectMapper mapper, String jsonString) {
429 try {
430 Object jsonObject = mapper.readValue(jsonString, Object.class);
431 return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
Daniel Park2ff66b42018-08-01 11:52:45 +0900432 } catch (JsonParseException e) {
433 log.debug("JsonParseException caused by {}", e);
434 } catch (JsonMappingException e) {
435 log.debug("JsonMappingException caused by {}", e);
436 } catch (JsonProcessingException e) {
437 log.debug("JsonProcessingException caused by {}", e);
Jian Lif1efbe52018-07-17 23:20:16 +0900438 } catch (IOException e) {
Daniel Park2ff66b42018-08-01 11:52:45 +0900439 log.debug("IOException caused by {}", e);
Jian Lif1efbe52018-07-17 23:20:16 +0900440 }
441 return null;
442 }
443
444 /**
Jian Li7f024de2018-07-07 03:51:02 +0900445 * Checks the validity of ARP mode.
446 *
447 * @param arpMode ARP mode
448 * @return returns true if the ARP mode is valid, false otherwise
449 */
450 public static boolean checkArpMode(String arpMode) {
451
452 if (isNullOrEmpty(arpMode)) {
453 return false;
454 } else {
455 return arpMode.equals(PROXY_MODE) || arpMode.equals(BROADCAST_MODE);
456 }
457 }
458
459 /**
Jian Liec5c32b2018-07-13 14:28:58 +0900460 * Swaps current location with old location info.
461 * The revised instance port will be used to mod the flow rules after migration.
462 *
463 * @param instPort instance port
464 * @return location swapped instance port
465 */
466 public static InstancePort swapStaleLocation(InstancePort instPort) {
467 return DefaultInstancePort.builder()
468 .deviceId(instPort.oldDeviceId())
469 .portNumber(instPort.oldPortNumber())
470 .state(instPort.state())
471 .ipAddress(instPort.ipAddress())
472 .macAddress(instPort.macAddress())
473 .networkId(instPort.networkId())
474 .portId(instPort.portId())
475 .build();
476 }
477
478 /**
Daniel Park2ff66b42018-08-01 11:52:45 +0900479 * Compares two router interfaces are equal.
480 * Will be remove this after Openstack4j implements equals.
481 *
482 * @param routerInterface1 router interface
483 * @param routerInterface2 router interface
484 * @return returns true if two router interfaces are equal, false otherwise
485 */
Jian Li63430202018-08-30 16:24:09 +0900486 public static boolean routerInterfacesEquals(RouterInterface routerInterface1,
487 RouterInterface routerInterface2) {
Daniel Park2ff66b42018-08-01 11:52:45 +0900488 return Objects.equals(routerInterface1.getId(), routerInterface2.getId()) &&
489 Objects.equals(routerInterface1.getPortId(), routerInterface2.getPortId()) &&
490 Objects.equals(routerInterface1.getSubnetId(), routerInterface2.getSubnetId()) &&
491 Objects.equals(routerInterface1.getTenantId(), routerInterface2.getTenantId());
492 }
493
Daniel Park7e8c4d82018-08-13 23:47:49 +0900494 public static VnicType vnicType(String portName) {
495 if (portName.startsWith(PORT_NAME_PREFIX_VM) ||
496 portName.startsWith(PORT_NAME_VHOST_USER_PREFIX_VM)) {
497 return VnicType.NORMAL;
498 } else if (isDirectPort(portName)) {
499 return VnicType.DIRECT;
500 } else {
501 return VnicType.UNSUPPORTED;
502 }
503 }
504
Jian Li63430202018-08-30 16:24:09 +0900505 /**
506 * Deserializes raw payload into HttpRequest object.
507 *
508 * @param rawData raw http payload
509 * @return HttpRequest object
510 */
511 public static HttpRequest parseHttpRequest(byte[] rawData) {
512 SessionInputBufferImpl sessionInputBuffer =
513 new SessionInputBufferImpl(
514 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
515 sessionInputBuffer.bind(new ByteArrayInputStream(rawData));
516 DefaultHttpRequestParser requestParser = new DefaultHttpRequestParser(sessionInputBuffer);
517 try {
518 return requestParser.parse();
519 } catch (IOException | HttpException e) {
520 log.warn("Failed to parse HttpRequest, due to {}", e);
521 }
522
523 return null;
524 }
525
526 /**
527 * Serializes HttpRequest object to byte array.
528 *
529 * @param request http request object
530 * @return byte array
531 */
532 public static byte[] unparseHttpRequest(HttpRequest request) {
533 try {
534 SessionOutputBufferImpl sessionOutputBuffer =
535 new SessionOutputBufferImpl(
536 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
537
538 ByteArrayOutputStream baos = new ByteArrayOutputStream();
539 sessionOutputBuffer.bind(baos);
540
541 HttpMessageWriter<HttpRequest> requestWriter = new DefaultHttpRequestWriter(
542 sessionOutputBuffer);
543 requestWriter.write(request);
544 sessionOutputBuffer.flush();
545
546 return baos.toByteArray();
547 } catch (HttpException | IOException e) {
548 log.warn("Failed to unparse HttpRequest, due to {}", e);
549 }
550
551 return null;
552 }
553
554 /**
555 * Deserializes raw payload into HttpResponse object.
556 *
557 * @param rawData raw http payload
558 * @return HttpResponse object
559 */
560 public static HttpResponse parseHttpResponse(byte[] rawData) {
561 SessionInputBufferImpl sessionInputBuffer =
562 new SessionInputBufferImpl(
563 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
564 sessionInputBuffer.bind(new ByteArrayInputStream(rawData));
565 DefaultHttpResponseParser responseParser = new DefaultHttpResponseParser(sessionInputBuffer);
566 try {
567 return responseParser.parse();
568 } catch (IOException | HttpException e) {
569 log.warn("Failed to parse HttpResponse, due to {}", e);
570 }
571
572 return null;
573 }
574
575 /**
576 * Serializes HttpResponse header to byte array.
577 *
578 * @param response http response object
579 * @return byte array
580 */
581 public static byte[] unparseHttpResponseHeader(HttpResponse response) {
582 try {
583 SessionOutputBufferImpl sessionOutputBuffer =
584 new SessionOutputBufferImpl(
585 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
586
587 ByteArrayOutputStream headerBaos = new ByteArrayOutputStream();
588 sessionOutputBuffer.bind(headerBaos);
589
590 HttpMessageWriter<HttpResponse> responseWriter =
591 new DefaultHttpResponseWriter(sessionOutputBuffer);
592 responseWriter.write(response);
593 sessionOutputBuffer.flush();
594
595 log.debug(headerBaos.toString());
596
597 return headerBaos.toByteArray();
598 } catch (IOException | HttpException e) {
599 log.warn("Failed to unparse HttpResponse headers, due to {}", e);
600 }
601
602 return null;
603 }
604
605 /**
606 * Serializes HttpResponse object to byte array.
607 *
608 * @param response http response object
609 * @return byte array
610 */
611 public static byte[] unparseHttpResponseBody(HttpResponse response) {
612 try {
613 ByteArrayOutputStream baos = new ByteArrayOutputStream();
614 response.getEntity().writeTo(baos);
615
616 log.debug(response.toString());
617 log.debug(baos.toString());
618
619 return baos.toByteArray();
620 } catch (IOException e) {
621 log.warn("Failed to unparse HttpResponse, due to {}", e);
622 }
623
624 return null;
625 }
626
627 /**
628 * Encodes the given data using HmacSHA256 encryption method with given secret key.
629 *
630 * @param key secret key
631 * @param data data to be encrypted
632 * @return Hmac256 encrypted data
633 */
634 public static String hmacEncrypt(String key, String data) {
635 try {
636 Mac sha256Hmac = Mac.getInstance(HMAC_SHA256);
637 SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), HMAC_SHA256);
638 sha256Hmac.init(secretKey);
639 return Hex.encodeHexString(sha256Hmac.doFinal(data.getBytes("UTF-8")));
640 } catch (Exception e) {
641 log.warn("Failed to encrypt data {} using key {}, due to {}", data, key, e);
642 }
643 return null;
644 }
645
Daniel Park7e8c4d82018-08-13 23:47:49 +0900646 private static boolean isDirectPort(String portName) {
Daniel Parkec9d1132018-08-19 11:18:03 +0900647 return portNamePrefixMap().values().stream().anyMatch(p -> portName.startsWith(p));
Daniel Park7e8c4d82018-08-13 23:47:49 +0900648 }
649
Daniel Park2ff66b42018-08-01 11:52:45 +0900650 /**
Jian Li51b844c2018-05-31 10:59:03 +0900651 * Builds up and a complete endpoint URL from gateway node.
652 *
653 * @param node gateway node
654 * @return a complete endpoint URL
655 */
656 private static String buildEndpoint(OpenstackNode node) {
657
658 OpenstackAuth auth = node.authentication();
659
660 StringBuilder endpointSb = new StringBuilder();
661 endpointSb.append(auth.protocol().name().toLowerCase());
662 endpointSb.append("://");
Jian Li6d410362018-08-17 09:41:08 +0900663 endpointSb.append(node.endpoint());
Jian Li51b844c2018-05-31 10:59:03 +0900664 return endpointSb.toString();
665 }
666
667 /**
668 * Obtains the SSL config without verifying the certification.
669 *
670 * @return SSL config
671 */
672 private static Config getSslConfig() {
673 // we bypass the SSL certification verification for now
674 // TODO: verify server side SSL using a given certification
675 Config config = Config.newConfig().withSSLVerificationDisabled();
676
677 TrustManager[] trustAllCerts = new TrustManager[]{
678 new X509TrustManager() {
679 public X509Certificate[] getAcceptedIssuers() {
680 return null;
681 }
682
683 public void checkClientTrusted(X509Certificate[] certs,
684 String authType) {
685 }
686
687 public void checkServerTrusted(X509Certificate[] certs,
688 String authType) {
689 }
690 }
691 };
692
693 HostnameVerifier allHostsValid = (hostname, session) -> true;
694
695 try {
696 SSLContext sc = SSLContext.getInstance(SSL_TYPE);
697 sc.init(null, trustAllCerts,
698 new java.security.SecureRandom());
699 HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
700 HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
701
702 config.withSSLContext(sc);
703 } catch (Exception e) {
704 log.error("Failed to access OpenStack service due to {}", e.toString());
705 return null;
706 }
707
708 return config;
709 }
710
711 /**
712 * Obtains the facing object with given openstack perspective.
713 *
714 * @param perspective keystone perspective
715 * @return facing object
716 */
717 private static Facing getFacing(Perspective perspective) {
718
719 switch (perspective) {
720 case PUBLIC:
721 return Facing.PUBLIC;
722 case ADMIN:
723 return Facing.ADMIN;
724 case INTERNAL:
725 return Facing.INTERNAL;
726 default:
727 return null;
728 }
729 }
730
731 /**
732 * Obtains gateway instance by giving index number.
733 *
734 * @param gws a collection of gateway nodes
735 * @param index index number
736 * @return gateway instance
737 */
738 private static OpenstackNode getGwByIndex(Set<OpenstackNode> gws, int index) {
739 Map<String, OpenstackNode> hashMap = new HashMap<>();
740 gws.forEach(gw -> hashMap.put(gw.hostname(), gw));
741 TreeMap<String, OpenstackNode> treeMap = new TreeMap<>(hashMap);
742 Iterator<String> iteratorKey = treeMap.keySet().iterator();
743
744 int intIndex = 0;
745 OpenstackNode gw = null;
746 while (iteratorKey.hasNext()) {
747 String key = iteratorKey.next();
748
749 if (intIndex == index) {
750 gw = treeMap.get(key);
751 }
752 intIndex++;
753 }
754 return gw;
755 }
Jian Li63430202018-08-30 16:24:09 +0900756}