blob: 65a9e9f87f3023d337b4e01e49f8ec92dd2b78b8 [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;
Daniel Parka73c2362018-09-17 17:43:25 +090024import com.google.common.base.Charsets;
Jian Li24ec59f2018-05-23 19:01:25 +090025import com.google.common.base.Strings;
Daniel Parka73c2362018-09-17 17:43:25 +090026import com.google.common.collect.Lists;
Jian Li63430202018-08-30 16:24:09 +090027import org.apache.commons.codec.binary.Hex;
28import org.apache.http.HttpException;
29import org.apache.http.HttpRequest;
30import org.apache.http.HttpResponse;
31import org.apache.http.impl.io.DefaultHttpRequestParser;
32import org.apache.http.impl.io.DefaultHttpRequestWriter;
33import org.apache.http.impl.io.DefaultHttpResponseParser;
34import org.apache.http.impl.io.DefaultHttpResponseWriter;
35import org.apache.http.impl.io.HttpTransportMetricsImpl;
36import org.apache.http.impl.io.SessionInputBufferImpl;
37import org.apache.http.impl.io.SessionOutputBufferImpl;
38import org.apache.http.io.HttpMessageWriter;
Daniel Parka73c2362018-09-17 17:43:25 +090039import org.apache.sshd.client.SshClient;
40import org.apache.sshd.client.channel.ClientChannel;
41import org.apache.sshd.client.channel.ClientChannelEvent;
42import org.apache.sshd.client.future.OpenFuture;
43import org.apache.sshd.client.session.ClientSession;
44import org.apache.sshd.common.util.io.NoCloseInputStream;
45import org.onlab.packet.IpAddress;
Jian Li7f70bb72018-07-06 23:35:30 +090046import org.onosproject.cfg.ConfigProperty;
Jian Li1064e4f2018-05-29 16:16:53 +090047import org.onosproject.net.DeviceId;
Daniel Park95f73312018-07-31 15:48:34 +090048import org.onosproject.net.device.DeviceService;
Daniel Park7e8c4d82018-08-13 23:47:49 +090049import org.onosproject.openstacknetworking.api.Constants.VnicType;
Jian Lia171a432018-06-11 11:52:11 +090050import org.onosproject.openstacknetworking.api.InstancePort;
Jian Li24ec59f2018-05-23 19:01:25 +090051import org.onosproject.openstacknetworking.api.OpenstackNetworkService;
Jian Li7f70bb72018-07-06 23:35:30 +090052import org.onosproject.openstacknetworking.api.OpenstackRouterAdminService;
Jian Liec5c32b2018-07-13 14:28:58 +090053import org.onosproject.openstacknetworking.impl.DefaultInstancePort;
Jian Li51b844c2018-05-31 10:59:03 +090054import org.onosproject.openstacknode.api.OpenstackAuth;
55import org.onosproject.openstacknode.api.OpenstackAuth.Perspective;
Jian Li1064e4f2018-05-29 16:16:53 +090056import org.onosproject.openstacknode.api.OpenstackNode;
Daniel Parka73c2362018-09-17 17:43:25 +090057import org.onosproject.openstacknode.api.OpenstackSshAuth;
Jian Li51b844c2018-05-31 10:59:03 +090058import org.openstack4j.api.OSClient;
59import org.openstack4j.api.client.IOSClientBuilder;
60import org.openstack4j.api.exceptions.AuthenticationException;
61import org.openstack4j.api.types.Facing;
62import org.openstack4j.core.transport.Config;
Jian Li091d8d22018-02-20 10:42:06 +090063import org.openstack4j.core.transport.ObjectMapperSingleton;
64import org.openstack4j.model.ModelEntity;
Jian Li51b844c2018-05-31 10:59:03 +090065import org.openstack4j.model.common.Identifier;
Jian Li24ec59f2018-05-23 19:01:25 +090066import org.openstack4j.model.network.NetFloatingIP;
67import org.openstack4j.model.network.Network;
Jian Lia171a432018-06-11 11:52:11 +090068import org.openstack4j.model.network.Port;
Jian Li0b564282018-06-20 00:50:53 +090069import org.openstack4j.model.network.RouterInterface;
Jian Li51b844c2018-05-31 10:59:03 +090070import org.openstack4j.openstack.OSFactory;
Jian Li0b564282018-06-20 00:50:53 +090071import org.openstack4j.openstack.networking.domain.NeutronRouterInterface;
Jian Li091d8d22018-02-20 10:42:06 +090072import org.slf4j.Logger;
73import org.slf4j.LoggerFactory;
74
Jian Li63430202018-08-30 16:24:09 +090075import javax.crypto.Mac;
76import javax.crypto.spec.SecretKeySpec;
Jian Li51b844c2018-05-31 10:59:03 +090077import javax.net.ssl.HostnameVerifier;
78import javax.net.ssl.HttpsURLConnection;
79import javax.net.ssl.SSLContext;
80import javax.net.ssl.TrustManager;
81import javax.net.ssl.X509TrustManager;
Jian Li63430202018-08-30 16:24:09 +090082import java.io.ByteArrayInputStream;
83import java.io.ByteArrayOutputStream;
Jian Li0b564282018-06-20 00:50:53 +090084import java.io.IOException;
Jian Li091d8d22018-02-20 10:42:06 +090085import java.io.InputStream;
Daniel Parka73c2362018-09-17 17:43:25 +090086import java.io.OutputStream;
Jian Li51b844c2018-05-31 10:59:03 +090087import java.security.cert.X509Certificate;
Daniel Parka73c2362018-09-17 17:43:25 +090088import java.util.Collection;
Jian Li1064e4f2018-05-29 16:16:53 +090089import java.util.HashMap;
90import java.util.Iterator;
91import java.util.Map;
Daniel Park95f73312018-07-31 15:48:34 +090092import java.util.Objects;
Jian Li7f70bb72018-07-06 23:35:30 +090093import java.util.Optional;
Jian Li1064e4f2018-05-29 16:16:53 +090094import java.util.Set;
95import java.util.TreeMap;
Daniel Parka73c2362018-09-17 17:43:25 +090096import java.util.concurrent.TimeUnit;
Jian Li091d8d22018-02-20 10:42:06 +090097
98import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT;
Daniel Park95f73312018-07-31 15:48:34 +090099import static com.google.common.base.Preconditions.checkNotNull;
Jian Li7f024de2018-07-07 03:51:02 +0900100import static com.google.common.base.Strings.isNullOrEmpty;
Daniel Park95f73312018-07-31 15:48:34 +0900101import static org.onosproject.net.AnnotationKeys.PORT_NAME;
Daniel Parka73c2362018-09-17 17:43:25 +0900102import static org.onosproject.openstacknetworking.api.Constants.DEFAULT_GATEWAY_MAC_STR;
Daniel Parkc4d06402018-05-28 15:57:37 +0900103import static org.onosproject.openstacknetworking.api.Constants.PCISLOT;
104import static org.onosproject.openstacknetworking.api.Constants.PCI_VENDOR_INFO;
Daniel Park7e8c4d82018-08-13 23:47:49 +0900105import static org.onosproject.openstacknetworking.api.Constants.PORT_NAME_PREFIX_VM;
106import static org.onosproject.openstacknetworking.api.Constants.PORT_NAME_VHOST_USER_PREFIX_VM;
Daniel Parkec9d1132018-08-19 11:18:03 +0900107import static org.onosproject.openstacknetworking.api.Constants.UNSUPPORTED_VENDOR;
Ray Milkey9dc57392018-06-08 08:52:31 -0700108import static org.onosproject.openstacknetworking.api.Constants.portNamePrefixMap;
Jian Li0b564282018-06-20 00:50:53 +0900109import static org.openstack4j.core.transport.ObjectMapperSingleton.getContext;
Jian Li091d8d22018-02-20 10:42:06 +0900110
111/**
112 * An utility that used in openstack networking app.
113 */
Jian Lidea0fdb2018-04-02 19:02:48 +0900114public final class OpenstackNetworkingUtil {
Jian Li091d8d22018-02-20 10:42:06 +0900115
Daniel Park95985382018-07-23 11:38:07 +0900116 private static final Logger log = LoggerFactory.getLogger(OpenstackNetworkingUtil.class);
Jian Li091d8d22018-02-20 10:42:06 +0900117
Daniel Parkc4d06402018-05-28 15:57:37 +0900118 private static final int HEX_RADIX = 16;
Jian Li51b844c2018-05-31 10:59:03 +0900119 private static final String ZERO_FUNCTION_NUMBER = "0";
Daniel Parkc4d06402018-05-28 15:57:37 +0900120 private static final String PREFIX_DEVICE_NUMBER = "s";
121 private static final String PREFIX_FUNCTION_NUMBER = "f";
122
Jian Li51b844c2018-05-31 10:59:03 +0900123 // keystone endpoint related variables
124 private static final String DOMAIN_DEFAULT = "default";
125 private static final String KEYSTONE_V2 = "v2.0";
126 private static final String KEYSTONE_V3 = "v3";
Jian Li51b844c2018-05-31 10:59:03 +0900127 private static final String SSL_TYPE = "SSL";
128
Jian Li7f024de2018-07-07 03:51:02 +0900129 private static final String PROXY_MODE = "proxy";
130 private static final String BROADCAST_MODE = "broadcast";
131
Jian Licad36c72018-09-13 17:44:54 +0900132 private static final String ENABLE = "enable";
133 private static final String DISABLE = "disable";
134
Jian Li63430202018-08-30 16:24:09 +0900135 private static final int HTTP_PAYLOAD_BUFFER = 8 * 1024;
136
137 private static final String HMAC_SHA256 = "HmacSHA256";
138
Jian Li24ec59f2018-05-23 19:01:25 +0900139 private static final String ERR_FLOW = "Failed set flows for floating IP %s: ";
140
Daniel Parka73c2362018-09-17 17:43:25 +0900141 private static final String FLAT = "FLAT";
142 private static final String VXLAN = "VXLAN";
143 private static final String VLAN = "VLAN";
144 private static final String DL_DST = "dl_dst=";
145 private static final String NW_DST = "nw_dst=";
146 private static final String DEFAULT_REQUEST_STRING = "sudo ovs-appctl ofproto/trace br-int ip";
147 private static final String IN_PORT = "in_port=";
148 private static final String NW_SRC = "nw_src=";
149 private static final String COMMA = ",";
150 private static final String TUN_ID = "tun_id=";
151
152 private static final long TIMEOUT_MS = 5000;
153 private static final long WAIT_OUTPUT_STREAM_SECOND = 2;
154 private static final int SSH_PORT = 22;
155
Jian Li091d8d22018-02-20 10:42:06 +0900156 /**
157 * Prevents object instantiation from external.
158 */
Jian Lidea0fdb2018-04-02 19:02:48 +0900159 private OpenstackNetworkingUtil() {
Jian Li091d8d22018-02-20 10:42:06 +0900160 }
161
162 /**
163 * Interprets JSON string to corresponding openstack model entity object.
164 *
165 * @param input JSON string
166 * @param entityClazz openstack model entity class
167 * @return openstack model entity object
168 */
169 public static ModelEntity jsonToModelEntity(InputStream input, Class entityClazz) {
170 ObjectMapper mapper = new ObjectMapper();
171 try {
172 JsonNode jsonTree = mapper.enable(INDENT_OUTPUT).readTree(input);
173 log.trace(new ObjectMapper().writeValueAsString(jsonTree));
174 return ObjectMapperSingleton.getContext(entityClazz)
175 .readerFor(entityClazz)
176 .readValue(jsonTree);
177 } catch (Exception e) {
178 throw new IllegalArgumentException();
179 }
180 }
Jian Lieb9f77d2018-02-20 11:25:45 +0900181
182 /**
183 * Converts openstack model entity object into JSON object.
184 *
185 * @param entity openstack model entity object
186 * @param entityClazz openstack model entity class
187 * @return JSON object
188 */
189 public static ObjectNode modelEntityToJson(ModelEntity entity, Class entityClazz) {
190 ObjectMapper mapper = new ObjectMapper();
191 try {
192 String strModelEntity = ObjectMapperSingleton.getContext(entityClazz)
193 .writerFor(entityClazz)
194 .writeValueAsString(entity);
195 log.trace(strModelEntity);
196 return (ObjectNode) mapper.readTree(strModelEntity.getBytes());
Daniel Park95985382018-07-23 11:38:07 +0900197 } catch (IOException e) {
198 log.error("IOException occurred because of {}", e.toString());
Jian Lieb9f77d2018-02-20 11:25:45 +0900199 throw new IllegalStateException();
200 }
201 }
Jian Li1064e4f2018-05-29 16:16:53 +0900202
203 /**
Jian Li24ec59f2018-05-23 19:01:25 +0900204 * Obtains a floating IP associated with the given instance port.
205 *
206 * @param port instance port
207 * @param fips a collection of floating IPs
208 * @return associated floating IP
209 */
210 public static NetFloatingIP associatedFloatingIp(InstancePort port,
211 Set<NetFloatingIP> fips) {
Daniel Park2ff66b42018-08-01 11:52:45 +0900212 for (NetFloatingIP fip : fips) {
213 if (Strings.isNullOrEmpty(fip.getFixedIpAddress())) {
214 continue;
Jian Li24ec59f2018-05-23 19:01:25 +0900215 }
Daniel Park2ff66b42018-08-01 11:52:45 +0900216 if (Strings.isNullOrEmpty(fip.getFloatingIpAddress())) {
217 continue;
218 }
219 if (fip.getFixedIpAddress().equals(port.ipAddress().toString())) {
220 return fip;
221 }
Jian Li24ec59f2018-05-23 19:01:25 +0900222 }
Daniel Park2ff66b42018-08-01 11:52:45 +0900223
Jian Li24ec59f2018-05-23 19:01:25 +0900224 return null;
225 }
226
227 /**
228 * Checks whether the given floating IP is associated with a VM.
229 *
230 * @param service openstack network service
231 * @param fip floating IP
232 * @return true if the given floating IP associated with a VM, false otherwise
233 */
234 public static boolean isAssociatedWithVM(OpenstackNetworkService service,
235 NetFloatingIP fip) {
236 Port osPort = service.port(fip.getPortId());
237 if (osPort == null) {
238 return false;
239 }
240
241 if (!Strings.isNullOrEmpty(osPort.getDeviceId())) {
242 Network osNet = service.network(osPort.getNetworkId());
243 if (osNet == null) {
244 final String errorFormat = ERR_FLOW + "no network(%s) exists";
245 final String error = String.format(errorFormat,
246 fip.getFloatingIpAddress(), osPort.getNetworkId());
247 throw new IllegalStateException(error);
248 }
249 return true;
250 } else {
251 return false;
252 }
253 }
254
255 /**
Jian Lia171a432018-06-11 11:52:11 +0900256 * Obtains the gateway node by instance port.
257 *
258 * @param gateways a collection of gateway nodes
259 * @param instPort instance port
260 * @return a gateway node
261 */
262 public static OpenstackNode getGwByInstancePort(Set<OpenstackNode> gateways,
263 InstancePort instPort) {
264 OpenstackNode gw = null;
265 if (instPort != null && instPort.deviceId() != null) {
266 gw = getGwByComputeDevId(gateways, instPort.deviceId());
267 }
268 return gw;
269 }
270
271 /**
Jian Li1064e4f2018-05-29 16:16:53 +0900272 * Obtains the gateway node by device in compute node. Note that the gateway
273 * node is determined by device's device identifier.
274 *
275 * @param gws a collection of gateway nodes
276 * @param deviceId device identifier
277 * @return a gateway node
278 */
279 public static OpenstackNode getGwByComputeDevId(Set<OpenstackNode> gws, DeviceId deviceId) {
280 int numOfGw = gws.size();
281
282 if (numOfGw == 0) {
283 return null;
284 }
285
286 int gwIndex = Math.abs(deviceId.hashCode()) % numOfGw;
287
288 return getGwByIndex(gws, gwIndex);
289 }
290
Jian Li51b844c2018-05-31 10:59:03 +0900291 /**
292 * Obtains a connected openstack client.
293 *
294 * @param osNode openstack node
295 * @return a connected openstack client
296 */
297 public static OSClient getConnectedClient(OpenstackNode osNode) {
Jian Lic704b672018-09-04 18:52:53 +0900298 OpenstackAuth auth = osNode.keystoneConfig().authentication();
Jian Li51b844c2018-05-31 10:59:03 +0900299 String endpoint = buildEndpoint(osNode);
300 Perspective perspective = auth.perspective();
Jian Li1064e4f2018-05-29 16:16:53 +0900301
Jian Li51b844c2018-05-31 10:59:03 +0900302 Config config = getSslConfig();
Jian Li1064e4f2018-05-29 16:16:53 +0900303
Jian Li51b844c2018-05-31 10:59:03 +0900304 try {
305 if (endpoint.contains(KEYSTONE_V2)) {
306 IOSClientBuilder.V2 builder = OSFactory.builderV2()
307 .endpoint(endpoint)
308 .tenantName(auth.project())
309 .credentials(auth.username(), auth.password())
310 .withConfig(config);
311
312 if (perspective != null) {
313 builder.perspective(getFacing(perspective));
314 }
315
316 return builder.authenticate();
317 } else if (endpoint.contains(KEYSTONE_V3)) {
318
319 Identifier project = Identifier.byName(auth.project());
320 Identifier domain = Identifier.byName(DOMAIN_DEFAULT);
321
322 IOSClientBuilder.V3 builder = OSFactory.builderV3()
323 .endpoint(endpoint)
324 .credentials(auth.username(), auth.password(), domain)
325 .scopeToProject(project, domain)
326 .withConfig(config);
327
328 if (perspective != null) {
329 builder.perspective(getFacing(perspective));
330 }
331
332 return builder.authenticate();
333 } else {
334 log.warn("Unrecognized keystone version type");
335 return null;
Jian Li1064e4f2018-05-29 16:16:53 +0900336 }
Jian Li51b844c2018-05-31 10:59:03 +0900337 } catch (AuthenticationException e) {
338 log.error("Authentication failed due to {}", e.toString());
339 return null;
Jian Li1064e4f2018-05-29 16:16:53 +0900340 }
Jian Li1064e4f2018-05-29 16:16:53 +0900341 }
Daniel Parkc4d06402018-05-28 15:57:37 +0900342
343 /**
344 * Extract the interface name with the supplied port.
345 *
346 * @param port port
347 * @return interface name
348 */
349 public static String getIntfNameFromPciAddress(Port port) {
Daniel Park95985382018-07-23 11:38:07 +0900350 if (port.getProfile() == null || port.getProfile().isEmpty()) {
Jian Li51b844c2018-05-31 10:59:03 +0900351 log.error("Port profile is not found");
352 return null;
353 }
354
Daniel Park95985382018-07-23 11:38:07 +0900355 if (!port.getProfile().containsKey(PCISLOT) ||
356 Strings.isNullOrEmpty(port.getProfile().get(PCISLOT).toString())) {
Daniel Parkc4d06402018-05-28 15:57:37 +0900357 log.error("Failed to retrieve the interface name because of no pci_slot information from the port");
358 return null;
359 }
Jian Li51b844c2018-05-31 10:59:03 +0900360
Daniel Parkc4d06402018-05-28 15:57:37 +0900361 String busNumHex = port.getProfile().get(PCISLOT).toString().split(":")[1];
362 String busNumDecimal = String.valueOf(Integer.parseInt(busNumHex, HEX_RADIX));
363
364 String deviceNumHex = port.getProfile().get(PCISLOT).toString()
365 .split(":")[2]
366 .split("\\.")[0];
367 String deviceNumDecimal = String.valueOf(Integer.parseInt(deviceNumHex, HEX_RADIX));
368
369 String functionNumHex = port.getProfile().get(PCISLOT).toString()
370 .split(":")[2]
371 .split("\\.")[1];
372 String functionNumDecimal = String.valueOf(Integer.parseInt(functionNumHex, HEX_RADIX));
373
374 String intfName;
375
376 String vendorInfoForPort = String.valueOf(port.getProfile().get(PCI_VENDOR_INFO));
377
Daniel Park95985382018-07-23 11:38:07 +0900378 if (!portNamePrefixMap().containsKey(vendorInfoForPort)) {
Daniel Parkec9d1132018-08-19 11:18:03 +0900379 log.warn("Failed to retrieve the interface name because of unsupported prefix for vendor ID {}",
Daniel Park95985382018-07-23 11:38:07 +0900380 vendorInfoForPort);
Daniel Parkec9d1132018-08-19 11:18:03 +0900381 return UNSUPPORTED_VENDOR;
Daniel Parkc4d06402018-05-28 15:57:37 +0900382 }
Ray Milkey9dc57392018-06-08 08:52:31 -0700383 String portNamePrefix = portNamePrefixMap().get(vendorInfoForPort);
Jian Li51b844c2018-05-31 10:59:03 +0900384
Daniel Parkc4d06402018-05-28 15:57:37 +0900385 if (functionNumDecimal.equals(ZERO_FUNCTION_NUMBER)) {
386 intfName = portNamePrefix + busNumDecimal + PREFIX_DEVICE_NUMBER + deviceNumDecimal;
387 } else {
388 intfName = portNamePrefix + busNumDecimal + PREFIX_DEVICE_NUMBER + deviceNumDecimal
389 + PREFIX_FUNCTION_NUMBER + functionNumDecimal;
390 }
391
392 return intfName;
393 }
Jian Li51b844c2018-05-31 10:59:03 +0900394
395 /**
Daniel Park95f73312018-07-31 15:48:34 +0900396 * Check if the given interface is added to the given device or not.
397 *
398 * @param deviceId device ID
399 * @param intfName interface name
400 * @param deviceService device service
401 * @return true if the given interface is added to the given device or false otherwise
402 */
403 public static boolean hasIntfAleadyInDevice(DeviceId deviceId, String intfName, DeviceService deviceService) {
404 checkNotNull(deviceId);
405 checkNotNull(intfName);
406
407 return deviceService.getPorts(deviceId).stream()
408 .anyMatch(port -> Objects.equals(port.annotations().value(PORT_NAME), intfName));
409 }
410
411 /**
Jian Li0b564282018-06-20 00:50:53 +0900412 * Adds router interfaces to openstack admin service.
413 * TODO fix the logic to add router interface to router
414 *
415 * @param osPort port
416 * @param adminService openstack admin service
417 */
418 public static void addRouterIface(Port osPort, OpenstackRouterAdminService adminService) {
419 osPort.getFixedIps().forEach(p -> {
420 JsonNode jsonTree = new ObjectMapper().createObjectNode()
421 .put("id", osPort.getDeviceId())
422 .put("tenant_id", osPort.getTenantId())
423 .put("subnet_id", p.getSubnetId())
424 .put("port_id", osPort.getId());
425 try {
426 RouterInterface rIface = getContext(NeutronRouterInterface.class)
427 .readerFor(NeutronRouterInterface.class)
428 .readValue(jsonTree);
429 if (adminService.routerInterface(rIface.getPortId()) != null) {
430 adminService.updateRouterInterface(rIface);
431 } else {
432 adminService.addRouterInterface(rIface);
433 }
434 } catch (IOException ignore) {
Daniel Park2ff66b42018-08-01 11:52:45 +0900435 log.error("Exception occurred because of {}", ignore.toString());
Jian Li0b564282018-06-20 00:50:53 +0900436 }
437 });
438 }
439
440 /**
Jian Li7f70bb72018-07-06 23:35:30 +0900441 * Obtains the property value with specified property key name.
442 *
443 * @param properties a collection of properties
444 * @param name key name
445 * @return mapping value
446 */
447 public static String getPropertyValue(Set<ConfigProperty> properties, String name) {
448 Optional<ConfigProperty> property =
449 properties.stream().filter(p -> p.name().equals(name)).findFirst();
450 return property.map(ConfigProperty::value).orElse(null);
451 }
452
453 /**
Jian Lif1efbe52018-07-17 23:20:16 +0900454 * Prints out the JSON string in pretty format.
455 *
456 * @param mapper Object mapper
457 * @param jsonString JSON string
458 * @return pretty formatted JSON string
459 */
460 public static String prettyJson(ObjectMapper mapper, String jsonString) {
461 try {
462 Object jsonObject = mapper.readValue(jsonString, Object.class);
463 return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
Daniel Park2ff66b42018-08-01 11:52:45 +0900464 } catch (JsonParseException e) {
465 log.debug("JsonParseException caused by {}", e);
466 } catch (JsonMappingException e) {
467 log.debug("JsonMappingException caused by {}", e);
468 } catch (JsonProcessingException e) {
469 log.debug("JsonProcessingException caused by {}", e);
Jian Lif1efbe52018-07-17 23:20:16 +0900470 } catch (IOException e) {
Daniel Park2ff66b42018-08-01 11:52:45 +0900471 log.debug("IOException caused by {}", e);
Jian Lif1efbe52018-07-17 23:20:16 +0900472 }
473 return null;
474 }
475
476 /**
Jian Li7f024de2018-07-07 03:51:02 +0900477 * Checks the validity of ARP mode.
478 *
479 * @param arpMode ARP mode
480 * @return returns true if the ARP mode is valid, false otherwise
481 */
482 public static boolean checkArpMode(String arpMode) {
483
484 if (isNullOrEmpty(arpMode)) {
485 return false;
486 } else {
487 return arpMode.equals(PROXY_MODE) || arpMode.equals(BROADCAST_MODE);
488 }
489 }
490
491 /**
Jian Licad36c72018-09-13 17:44:54 +0900492 * Checks the validity of activation flag.
493 *
494 * @param activationFlag activation flag
495 * @return returns true if the activation flag is valid, false otherwise
496 */
497 public static boolean checkActivationFlag(String activationFlag) {
498
499 switch (activationFlag) {
500 case ENABLE:
501 return true;
502 case DISABLE:
503 return false;
504 default:
505 throw new IllegalArgumentException("The given activation flag is not valid!");
506 }
507 }
508
509 /**
Jian Liec5c32b2018-07-13 14:28:58 +0900510 * Swaps current location with old location info.
511 * The revised instance port will be used to mod the flow rules after migration.
512 *
513 * @param instPort instance port
514 * @return location swapped instance port
515 */
516 public static InstancePort swapStaleLocation(InstancePort instPort) {
517 return DefaultInstancePort.builder()
518 .deviceId(instPort.oldDeviceId())
519 .portNumber(instPort.oldPortNumber())
520 .state(instPort.state())
521 .ipAddress(instPort.ipAddress())
522 .macAddress(instPort.macAddress())
523 .networkId(instPort.networkId())
524 .portId(instPort.portId())
525 .build();
526 }
527
528 /**
Daniel Park2ff66b42018-08-01 11:52:45 +0900529 * Compares two router interfaces are equal.
530 * Will be remove this after Openstack4j implements equals.
531 *
532 * @param routerInterface1 router interface
533 * @param routerInterface2 router interface
534 * @return returns true if two router interfaces are equal, false otherwise
535 */
Jian Li63430202018-08-30 16:24:09 +0900536 public static boolean routerInterfacesEquals(RouterInterface routerInterface1,
537 RouterInterface routerInterface2) {
Daniel Park2ff66b42018-08-01 11:52:45 +0900538 return Objects.equals(routerInterface1.getId(), routerInterface2.getId()) &&
539 Objects.equals(routerInterface1.getPortId(), routerInterface2.getPortId()) &&
540 Objects.equals(routerInterface1.getSubnetId(), routerInterface2.getSubnetId()) &&
541 Objects.equals(routerInterface1.getTenantId(), routerInterface2.getTenantId());
542 }
543
Daniel Park7e8c4d82018-08-13 23:47:49 +0900544 public static VnicType vnicType(String portName) {
545 if (portName.startsWith(PORT_NAME_PREFIX_VM) ||
546 portName.startsWith(PORT_NAME_VHOST_USER_PREFIX_VM)) {
547 return VnicType.NORMAL;
548 } else if (isDirectPort(portName)) {
549 return VnicType.DIRECT;
550 } else {
551 return VnicType.UNSUPPORTED;
552 }
553 }
554
Jian Li63430202018-08-30 16:24:09 +0900555 /**
556 * Deserializes raw payload into HttpRequest object.
557 *
558 * @param rawData raw http payload
559 * @return HttpRequest object
560 */
561 public static HttpRequest parseHttpRequest(byte[] rawData) {
562 SessionInputBufferImpl sessionInputBuffer =
563 new SessionInputBufferImpl(
564 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
565 sessionInputBuffer.bind(new ByteArrayInputStream(rawData));
566 DefaultHttpRequestParser requestParser = new DefaultHttpRequestParser(sessionInputBuffer);
567 try {
568 return requestParser.parse();
569 } catch (IOException | HttpException e) {
570 log.warn("Failed to parse HttpRequest, due to {}", e);
571 }
572
573 return null;
574 }
575
576 /**
577 * Serializes HttpRequest object to byte array.
578 *
579 * @param request http request object
580 * @return byte array
581 */
582 public static byte[] unparseHttpRequest(HttpRequest request) {
583 try {
584 SessionOutputBufferImpl sessionOutputBuffer =
585 new SessionOutputBufferImpl(
586 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
587
588 ByteArrayOutputStream baos = new ByteArrayOutputStream();
589 sessionOutputBuffer.bind(baos);
590
591 HttpMessageWriter<HttpRequest> requestWriter = new DefaultHttpRequestWriter(
592 sessionOutputBuffer);
593 requestWriter.write(request);
594 sessionOutputBuffer.flush();
595
596 return baos.toByteArray();
597 } catch (HttpException | IOException e) {
598 log.warn("Failed to unparse HttpRequest, due to {}", e);
599 }
600
601 return null;
602 }
603
604 /**
605 * Deserializes raw payload into HttpResponse object.
606 *
607 * @param rawData raw http payload
608 * @return HttpResponse object
609 */
610 public static HttpResponse parseHttpResponse(byte[] rawData) {
611 SessionInputBufferImpl sessionInputBuffer =
612 new SessionInputBufferImpl(
613 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
614 sessionInputBuffer.bind(new ByteArrayInputStream(rawData));
615 DefaultHttpResponseParser responseParser = new DefaultHttpResponseParser(sessionInputBuffer);
616 try {
617 return responseParser.parse();
618 } catch (IOException | HttpException e) {
619 log.warn("Failed to parse HttpResponse, due to {}", e);
620 }
621
622 return null;
623 }
624
625 /**
626 * Serializes HttpResponse header to byte array.
627 *
628 * @param response http response object
629 * @return byte array
630 */
631 public static byte[] unparseHttpResponseHeader(HttpResponse response) {
632 try {
633 SessionOutputBufferImpl sessionOutputBuffer =
634 new SessionOutputBufferImpl(
635 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
636
637 ByteArrayOutputStream headerBaos = new ByteArrayOutputStream();
638 sessionOutputBuffer.bind(headerBaos);
639
640 HttpMessageWriter<HttpResponse> responseWriter =
641 new DefaultHttpResponseWriter(sessionOutputBuffer);
642 responseWriter.write(response);
643 sessionOutputBuffer.flush();
644
645 log.debug(headerBaos.toString());
646
647 return headerBaos.toByteArray();
648 } catch (IOException | HttpException e) {
649 log.warn("Failed to unparse HttpResponse headers, due to {}", e);
650 }
651
652 return null;
653 }
654
655 /**
656 * Serializes HttpResponse object to byte array.
657 *
658 * @param response http response object
659 * @return byte array
660 */
661 public static byte[] unparseHttpResponseBody(HttpResponse response) {
662 try {
663 ByteArrayOutputStream baos = new ByteArrayOutputStream();
664 response.getEntity().writeTo(baos);
665
666 log.debug(response.toString());
667 log.debug(baos.toString());
668
669 return baos.toByteArray();
670 } catch (IOException e) {
671 log.warn("Failed to unparse HttpResponse, due to {}", e);
672 }
673
674 return null;
675 }
676
677 /**
678 * Encodes the given data using HmacSHA256 encryption method with given secret key.
679 *
680 * @param key secret key
681 * @param data data to be encrypted
682 * @return Hmac256 encrypted data
683 */
684 public static String hmacEncrypt(String key, String data) {
685 try {
686 Mac sha256Hmac = Mac.getInstance(HMAC_SHA256);
687 SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), HMAC_SHA256);
688 sha256Hmac.init(secretKey);
689 return Hex.encodeHexString(sha256Hmac.doFinal(data.getBytes("UTF-8")));
690 } catch (Exception e) {
691 log.warn("Failed to encrypt data {} using key {}, due to {}", data, key, e);
692 }
693 return null;
694 }
695
Daniel Parka73c2362018-09-17 17:43:25 +0900696 /**
697 * Creates flow trace request string.
698 *
699 * @param srcIp src ip address
700 * @param dstIp dst ip address
701 * @param srcInstancePort src instance port
702 * @param osNetService openstack networking service
Daniel Park4e037f52018-09-20 18:04:18 +0900703 * @param uplink true if this request is for uplink
Daniel Parka73c2362018-09-17 17:43:25 +0900704 * @return flow trace request string
705 */
706 public static String traceRequestString(String srcIp,
707 String dstIp,
708 InstancePort srcInstancePort,
709 OpenstackNetworkService osNetService, boolean uplink) {
710
711 StringBuilder requestStringBuilder = new StringBuilder(DEFAULT_REQUEST_STRING);
712
713 if (uplink) {
714
715 requestStringBuilder.append(COMMA)
716 .append(IN_PORT)
717 .append(srcInstancePort.portNumber().toString())
718 .append(COMMA)
719 .append(NW_SRC)
720 .append(srcIp)
721 .append(COMMA);
722
723 if (osNetService.networkType(srcInstancePort.networkId()).equals(VXLAN) ||
724 osNetService.networkType(srcInstancePort.networkId()).equals(VLAN)) {
725 if (srcIp.equals(dstIp)) {
726 dstIp = osNetService.gatewayIp(srcInstancePort.portId());
727 requestStringBuilder.append(DL_DST)
728 .append(DEFAULT_GATEWAY_MAC_STR).append(COMMA);
729 } else if (!osNetService.ipPrefix(srcInstancePort.portId()).contains(IpAddress.valueOf(dstIp))) {
730 requestStringBuilder.append(DL_DST)
731 .append(DEFAULT_GATEWAY_MAC_STR)
732 .append(COMMA);
733 }
734 } else {
735 if (srcIp.equals(dstIp)) {
736 dstIp = osNetService.gatewayIp(srcInstancePort.portId());
737 }
738 }
739
740 requestStringBuilder.append(NW_DST)
741 .append(dstIp)
742 .append("\n");
743 } else {
744 requestStringBuilder.append(COMMA)
745 .append(NW_SRC)
746 .append(dstIp)
747 .append(COMMA);
748
749 if (osNetService.networkType(srcInstancePort.networkId()).equals(VXLAN) ||
750 osNetService.networkType(srcInstancePort.networkId()).equals(VLAN)) {
751 requestStringBuilder.append(TUN_ID)
752 .append(osNetService.segmentId(srcInstancePort.networkId()))
753 .append(COMMA);
754 }
755 requestStringBuilder.append(NW_DST)
756 .append(srcIp)
757 .append("\n");
758
759 }
760
761 return requestStringBuilder.toString();
762 }
763
764 /**
765 * Sends flow trace string to node.
766 *
767 * @param requestString reqeust string
768 * @param node src node
769 * @return flow trace result in string format
770 */
771 public static String sendTraceRequestToNode(String requestString,
772 OpenstackNode node) {
773 String traceResult = null;
774 OpenstackSshAuth sshAuth = node.sshAuthInfo();
775
776 try (SshClient client = SshClient.setUpDefaultClient()) {
777 client.start();
778
779 try (ClientSession session = client
780 .connect(sshAuth.id(), node.managementIp().getIp4Address().toString(), SSH_PORT)
781 .verify(TIMEOUT_MS, TimeUnit.SECONDS).getSession()) {
782 session.addPasswordIdentity(sshAuth.password());
783 session.auth().verify(TIMEOUT_MS, TimeUnit.SECONDS);
784
785
786 try (ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) {
787
788 log.debug("requestString: {}", requestString);
789 final InputStream inputStream =
790 new ByteArrayInputStream(requestString.getBytes());
791
792 OutputStream outputStream = new ByteArrayOutputStream();
793 OutputStream errStream = new ByteArrayOutputStream();
794
795 channel.setIn(new NoCloseInputStream(inputStream));
796 channel.setErr(errStream);
797 channel.setOut(outputStream);
798
799 Collection<ClientChannelEvent> eventList = Lists.newArrayList();
800 eventList.add(ClientChannelEvent.OPENED);
801
802 OpenFuture channelFuture = channel.open();
803
804 if (channelFuture.await(TIMEOUT_MS, TimeUnit.SECONDS)) {
805
806 long timeoutExpiredMs = System.currentTimeMillis() + TIMEOUT_MS;
807
808 while (!channelFuture.isOpened()) {
809 if ((timeoutExpiredMs - System.currentTimeMillis()) <= 0) {
810 log.error("Failed to open channel");
811 return null;
812 }
813 }
814 TimeUnit.SECONDS.sleep(WAIT_OUTPUT_STREAM_SECOND);
815
816 traceResult = ((ByteArrayOutputStream) outputStream).toString(Charsets.UTF_8.name());
817
818 channel.close();
819 }
820 } finally {
821 session.close();
822 }
823 } finally {
824 client.stop();
825 }
826
827 } catch (Exception e) {
828 log.error("Exception occurred because of {}", e.toString());
829 }
830
831 return traceResult;
832 }
833
Daniel Park7e8c4d82018-08-13 23:47:49 +0900834 private static boolean isDirectPort(String portName) {
Daniel Parkec9d1132018-08-19 11:18:03 +0900835 return portNamePrefixMap().values().stream().anyMatch(p -> portName.startsWith(p));
Daniel Park7e8c4d82018-08-13 23:47:49 +0900836 }
837
Daniel Park2ff66b42018-08-01 11:52:45 +0900838 /**
Jian Li51b844c2018-05-31 10:59:03 +0900839 * Builds up and a complete endpoint URL from gateway node.
840 *
841 * @param node gateway node
842 * @return a complete endpoint URL
843 */
844 private static String buildEndpoint(OpenstackNode node) {
845
Jian Lic704b672018-09-04 18:52:53 +0900846 OpenstackAuth auth = node.keystoneConfig().authentication();
Jian Li51b844c2018-05-31 10:59:03 +0900847
848 StringBuilder endpointSb = new StringBuilder();
849 endpointSb.append(auth.protocol().name().toLowerCase());
850 endpointSb.append("://");
Jian Lic704b672018-09-04 18:52:53 +0900851 endpointSb.append(node.keystoneConfig().endpoint());
Jian Li51b844c2018-05-31 10:59:03 +0900852 return endpointSb.toString();
853 }
854
855 /**
856 * Obtains the SSL config without verifying the certification.
857 *
858 * @return SSL config
859 */
860 private static Config getSslConfig() {
861 // we bypass the SSL certification verification for now
862 // TODO: verify server side SSL using a given certification
863 Config config = Config.newConfig().withSSLVerificationDisabled();
864
865 TrustManager[] trustAllCerts = new TrustManager[]{
866 new X509TrustManager() {
867 public X509Certificate[] getAcceptedIssuers() {
868 return null;
869 }
870
871 public void checkClientTrusted(X509Certificate[] certs,
872 String authType) {
873 }
874
875 public void checkServerTrusted(X509Certificate[] certs,
876 String authType) {
877 }
878 }
879 };
880
881 HostnameVerifier allHostsValid = (hostname, session) -> true;
882
883 try {
884 SSLContext sc = SSLContext.getInstance(SSL_TYPE);
885 sc.init(null, trustAllCerts,
886 new java.security.SecureRandom());
887 HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
888 HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
889
890 config.withSSLContext(sc);
891 } catch (Exception e) {
892 log.error("Failed to access OpenStack service due to {}", e.toString());
893 return null;
894 }
895
896 return config;
897 }
898
899 /**
900 * Obtains the facing object with given openstack perspective.
901 *
902 * @param perspective keystone perspective
903 * @return facing object
904 */
905 private static Facing getFacing(Perspective perspective) {
906
907 switch (perspective) {
908 case PUBLIC:
909 return Facing.PUBLIC;
910 case ADMIN:
911 return Facing.ADMIN;
912 case INTERNAL:
913 return Facing.INTERNAL;
914 default:
915 return null;
916 }
917 }
918
919 /**
920 * Obtains gateway instance by giving index number.
921 *
922 * @param gws a collection of gateway nodes
923 * @param index index number
924 * @return gateway instance
925 */
926 private static OpenstackNode getGwByIndex(Set<OpenstackNode> gws, int index) {
927 Map<String, OpenstackNode> hashMap = new HashMap<>();
928 gws.forEach(gw -> hashMap.put(gw.hostname(), gw));
929 TreeMap<String, OpenstackNode> treeMap = new TreeMap<>(hashMap);
930 Iterator<String> iteratorKey = treeMap.keySet().iterator();
931
932 int intIndex = 0;
933 OpenstackNode gw = null;
934 while (iteratorKey.hasNext()) {
935 String key = iteratorKey.next();
936
937 if (intIndex == index) {
938 gw = treeMap.get(key);
939 }
940 intIndex++;
941 }
942 return gw;
943 }
Jian Li63430202018-08-30 16:24:09 +0900944}