blob: 0a35e3466e498d33d1dd017a19ebf20cdaffb6e0 [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;
Jian Li51728702019-05-17 18:38:56 +090028import org.apache.commons.lang3.StringUtils;
Jian Lif654dd12020-01-30 17:41:26 +090029import org.apache.commons.net.util.SubnetUtils;
Jian Li63430202018-08-30 16:24:09 +090030import org.apache.http.HttpException;
31import org.apache.http.HttpRequest;
32import org.apache.http.HttpResponse;
33import org.apache.http.impl.io.DefaultHttpRequestParser;
34import org.apache.http.impl.io.DefaultHttpRequestWriter;
35import org.apache.http.impl.io.DefaultHttpResponseParser;
36import org.apache.http.impl.io.DefaultHttpResponseWriter;
37import org.apache.http.impl.io.HttpTransportMetricsImpl;
38import org.apache.http.impl.io.SessionInputBufferImpl;
39import org.apache.http.impl.io.SessionOutputBufferImpl;
40import org.apache.http.io.HttpMessageWriter;
Daniel Parka73c2362018-09-17 17:43:25 +090041import org.apache.sshd.client.SshClient;
42import org.apache.sshd.client.channel.ClientChannel;
43import org.apache.sshd.client.channel.ClientChannelEvent;
44import org.apache.sshd.client.future.OpenFuture;
45import org.apache.sshd.client.session.ClientSession;
46import org.apache.sshd.common.util.io.NoCloseInputStream;
Jian Li7b8c3682019-05-12 13:57:15 +090047import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090048import org.onlab.packet.ARP;
49import org.onlab.packet.Ethernet;
50import org.onlab.packet.Ip4Address;
Daniel Parka73c2362018-09-17 17:43:25 +090051import org.onlab.packet.IpAddress;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090052import org.onlab.packet.MacAddress;
53import org.onlab.packet.VlanId;
Jian Li7f70bb72018-07-06 23:35:30 +090054import org.onosproject.cfg.ConfigProperty;
Jian Li1064e4f2018-05-29 16:16:53 +090055import org.onosproject.net.DeviceId;
Jian Li2d68c192018-12-13 15:52:59 +090056import org.onosproject.net.PortNumber;
Daniel Park95f73312018-07-31 15:48:34 +090057import org.onosproject.net.device.DeviceService;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090058import org.onosproject.net.flow.DefaultTrafficTreatment;
59import org.onosproject.net.flow.TrafficTreatment;
Jian Lie87c2712019-09-11 11:15:16 +090060import org.onosproject.net.group.DefaultGroupKey;
61import org.onosproject.net.group.GroupKey;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090062import org.onosproject.net.packet.DefaultOutboundPacket;
63import org.onosproject.net.packet.PacketService;
Daniel Park7e8c4d82018-08-13 23:47:49 +090064import org.onosproject.openstacknetworking.api.Constants.VnicType;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090065import org.onosproject.openstacknetworking.api.ExternalPeerRouter;
Jian Lia171a432018-06-11 11:52:11 +090066import org.onosproject.openstacknetworking.api.InstancePort;
Jian Li7b8c3682019-05-12 13:57:15 +090067import org.onosproject.openstacknetworking.api.OpenstackHaService;
SONA Project6bc5c4a2018-12-14 23:49:52 +090068import org.onosproject.openstacknetworking.api.OpenstackNetwork.Type;
Jian Li24ec59f2018-05-23 19:01:25 +090069import org.onosproject.openstacknetworking.api.OpenstackNetworkService;
Jian Li7f70bb72018-07-06 23:35:30 +090070import org.onosproject.openstacknetworking.api.OpenstackRouterAdminService;
Jian Liebde74d2018-11-14 00:18:57 +090071import org.onosproject.openstacknetworking.api.OpenstackRouterService;
Jian Liec5c32b2018-07-13 14:28:58 +090072import org.onosproject.openstacknetworking.impl.DefaultInstancePort;
Jian Li51b844c2018-05-31 10:59:03 +090073import org.onosproject.openstacknode.api.OpenstackAuth;
74import org.onosproject.openstacknode.api.OpenstackAuth.Perspective;
Jian Li1064e4f2018-05-29 16:16:53 +090075import org.onosproject.openstacknode.api.OpenstackNode;
Daniel Parka73c2362018-09-17 17:43:25 +090076import org.onosproject.openstacknode.api.OpenstackSshAuth;
Jian Li51728702019-05-17 18:38:56 +090077import org.onosproject.ovsdb.controller.OvsdbClientService;
78import org.onosproject.ovsdb.controller.OvsdbController;
79import org.onosproject.ovsdb.controller.OvsdbNodeId;
Jian Li51b844c2018-05-31 10:59:03 +090080import org.openstack4j.api.OSClient;
81import org.openstack4j.api.client.IOSClientBuilder;
82import org.openstack4j.api.exceptions.AuthenticationException;
83import org.openstack4j.api.types.Facing;
84import org.openstack4j.core.transport.Config;
Jian Li091d8d22018-02-20 10:42:06 +090085import org.openstack4j.core.transport.ObjectMapperSingleton;
86import org.openstack4j.model.ModelEntity;
Jian Li51b844c2018-05-31 10:59:03 +090087import org.openstack4j.model.common.Identifier;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090088import org.openstack4j.model.network.ExternalGateway;
Jian Liecbf10c2019-10-02 20:36:09 +090089import org.openstack4j.model.network.IP;
Jian Li24ec59f2018-05-23 19:01:25 +090090import org.openstack4j.model.network.NetFloatingIP;
91import org.openstack4j.model.network.Network;
Jian Lia171a432018-06-11 11:52:11 +090092import org.openstack4j.model.network.Port;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090093import org.openstack4j.model.network.Router;
Jian Li0b564282018-06-20 00:50:53 +090094import org.openstack4j.model.network.RouterInterface;
Jian Liecbf10c2019-10-02 20:36:09 +090095import org.openstack4j.model.network.SecurityGroup;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090096import org.openstack4j.model.network.Subnet;
Jian Li51b844c2018-05-31 10:59:03 +090097import org.openstack4j.openstack.OSFactory;
Jian Li0b564282018-06-20 00:50:53 +090098import org.openstack4j.openstack.networking.domain.NeutronRouterInterface;
Jian Li091d8d22018-02-20 10:42:06 +090099import org.slf4j.Logger;
100import org.slf4j.LoggerFactory;
101
Jian Li63430202018-08-30 16:24:09 +0900102import javax.crypto.Mac;
103import javax.crypto.spec.SecretKeySpec;
Jian Li51b844c2018-05-31 10:59:03 +0900104import javax.net.ssl.HostnameVerifier;
105import javax.net.ssl.HttpsURLConnection;
106import javax.net.ssl.SSLContext;
107import javax.net.ssl.TrustManager;
108import javax.net.ssl.X509TrustManager;
Jian Li7b8c3682019-05-12 13:57:15 +0900109import javax.ws.rs.client.Client;
110import javax.ws.rs.client.ClientBuilder;
111import javax.ws.rs.client.Entity;
112import javax.ws.rs.client.WebTarget;
113import javax.ws.rs.core.Response;
Jian Li63430202018-08-30 16:24:09 +0900114import java.io.ByteArrayInputStream;
115import java.io.ByteArrayOutputStream;
Jian Li0b564282018-06-20 00:50:53 +0900116import java.io.IOException;
Jian Li091d8d22018-02-20 10:42:06 +0900117import java.io.InputStream;
Daniel Parka73c2362018-09-17 17:43:25 +0900118import java.io.OutputStream;
Daniel Park4fa1f5e2018-10-17 12:41:52 +0900119import java.nio.ByteBuffer;
Jian Li51b844c2018-05-31 10:59:03 +0900120import java.security.cert.X509Certificate;
Daniel Parka73c2362018-09-17 17:43:25 +0900121import java.util.Collection;
Jian Li1064e4f2018-05-29 16:16:53 +0900122import java.util.HashMap;
123import java.util.Iterator;
Jian Liecbf10c2019-10-02 20:36:09 +0900124import java.util.List;
Jian Li1064e4f2018-05-29 16:16:53 +0900125import java.util.Map;
Daniel Park95f73312018-07-31 15:48:34 +0900126import java.util.Objects;
Jian Li7f70bb72018-07-06 23:35:30 +0900127import java.util.Optional;
Jian Li1064e4f2018-05-29 16:16:53 +0900128import java.util.Set;
129import java.util.TreeMap;
Daniel Parka73c2362018-09-17 17:43:25 +0900130import java.util.concurrent.TimeUnit;
Jian Liecbf10c2019-10-02 20:36:09 +0900131import java.util.stream.Collectors;
Jian Li091d8d22018-02-20 10:42:06 +0900132
133import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT;
Daniel Park95f73312018-07-31 15:48:34 +0900134import static com.google.common.base.Preconditions.checkNotNull;
Jian Li7f024de2018-07-07 03:51:02 +0900135import static com.google.common.base.Strings.isNullOrEmpty;
Jian Li7b8c3682019-05-12 13:57:15 +0900136import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE;
137import static org.apache.commons.io.IOUtils.toInputStream;
Jian Li5ecfd1a2018-12-10 11:41:03 +0900138import static org.onlab.packet.Ip4Address.valueOf;
Daniel Park95f73312018-07-31 15:48:34 +0900139import static org.onosproject.net.AnnotationKeys.PORT_NAME;
Daniel Parka73c2362018-09-17 17:43:25 +0900140import static org.onosproject.openstacknetworking.api.Constants.DEFAULT_GATEWAY_MAC_STR;
Jian Lia97cec42019-10-31 22:24:17 +0900141import static org.onosproject.openstacknetworking.api.Constants.DIRECT;
Jian Liecbf10c2019-10-02 20:36:09 +0900142import static org.onosproject.openstacknetworking.api.Constants.FLOATING_IP_FORMAT;
143import static org.onosproject.openstacknetworking.api.Constants.NETWORK_FORMAT;
Jian Li7b8c3682019-05-12 13:57:15 +0900144import static org.onosproject.openstacknetworking.api.Constants.OPENSTACK_NETWORKING_REST_PATH;
Daniel Parkc4d06402018-05-28 15:57:37 +0900145import static org.onosproject.openstacknetworking.api.Constants.PCISLOT;
146import static org.onosproject.openstacknetworking.api.Constants.PCI_VENDOR_INFO;
Jian Liecbf10c2019-10-02 20:36:09 +0900147import static org.onosproject.openstacknetworking.api.Constants.PORT_FORMAT;
Daniel Park7e8c4d82018-08-13 23:47:49 +0900148import static org.onosproject.openstacknetworking.api.Constants.PORT_NAME_PREFIX_VM;
149import static org.onosproject.openstacknetworking.api.Constants.PORT_NAME_VHOST_USER_PREFIX_VM;
Jian Li7b8c3682019-05-12 13:57:15 +0900150import static org.onosproject.openstacknetworking.api.Constants.REST_PASSWORD;
151import static org.onosproject.openstacknetworking.api.Constants.REST_PORT;
152import static org.onosproject.openstacknetworking.api.Constants.REST_USER;
153import static org.onosproject.openstacknetworking.api.Constants.REST_UTF8;
Jian Liecbf10c2019-10-02 20:36:09 +0900154import static org.onosproject.openstacknetworking.api.Constants.ROUTER_FORMAT;
155import static org.onosproject.openstacknetworking.api.Constants.ROUTER_INTF_FORMAT;
156import static org.onosproject.openstacknetworking.api.Constants.SECURITY_GROUP_FORMAT;
157import static org.onosproject.openstacknetworking.api.Constants.SUBNET_FORMAT;
Daniel Parkec9d1132018-08-19 11:18:03 +0900158import static org.onosproject.openstacknetworking.api.Constants.UNSUPPORTED_VENDOR;
Ray Milkey9dc57392018-06-08 08:52:31 -0700159import static org.onosproject.openstacknetworking.api.Constants.portNamePrefixMap;
Jian Li0b564282018-06-20 00:50:53 +0900160import static org.openstack4j.core.transport.ObjectMapperSingleton.getContext;
Jian Li091d8d22018-02-20 10:42:06 +0900161
162/**
163 * An utility that used in openstack networking app.
164 */
Jian Lidea0fdb2018-04-02 19:02:48 +0900165public final class OpenstackNetworkingUtil {
Jian Li091d8d22018-02-20 10:42:06 +0900166
Daniel Park95985382018-07-23 11:38:07 +0900167 private static final Logger log = LoggerFactory.getLogger(OpenstackNetworkingUtil.class);
Jian Li091d8d22018-02-20 10:42:06 +0900168
Daniel Parkc4d06402018-05-28 15:57:37 +0900169 private static final int HEX_RADIX = 16;
Jian Li51b844c2018-05-31 10:59:03 +0900170 private static final String ZERO_FUNCTION_NUMBER = "0";
Daniel Parkc4d06402018-05-28 15:57:37 +0900171 private static final String PREFIX_DEVICE_NUMBER = "s";
172 private static final String PREFIX_FUNCTION_NUMBER = "f";
173
Jian Li51b844c2018-05-31 10:59:03 +0900174 // keystone endpoint related variables
175 private static final String DOMAIN_DEFAULT = "default";
176 private static final String KEYSTONE_V2 = "v2.0";
177 private static final String KEYSTONE_V3 = "v3";
Jian Li51b844c2018-05-31 10:59:03 +0900178 private static final String SSL_TYPE = "SSL";
179
Jian Li7f024de2018-07-07 03:51:02 +0900180 private static final String PROXY_MODE = "proxy";
181 private static final String BROADCAST_MODE = "broadcast";
182
Jian Licad36c72018-09-13 17:44:54 +0900183 private static final String ENABLE = "enable";
184 private static final String DISABLE = "disable";
185
Jian Li63430202018-08-30 16:24:09 +0900186 private static final int HTTP_PAYLOAD_BUFFER = 8 * 1024;
187
188 private static final String HMAC_SHA256 = "HmacSHA256";
189
Jian Li24ec59f2018-05-23 19:01:25 +0900190 private static final String ERR_FLOW = "Failed set flows for floating IP %s: ";
191
Daniel Parka73c2362018-09-17 17:43:25 +0900192 private static final String DL_DST = "dl_dst=";
193 private static final String NW_DST = "nw_dst=";
194 private static final String DEFAULT_REQUEST_STRING = "sudo ovs-appctl ofproto/trace br-int ip";
195 private static final String IN_PORT = "in_port=";
196 private static final String NW_SRC = "nw_src=";
197 private static final String COMMA = ",";
198 private static final String TUN_ID = "tun_id=";
199
Jian Liecbf10c2019-10-02 20:36:09 +0900200 private static final String DEVICE_OWNER_GW = "network:router_gateway";
201 private static final String DEVICE_OWNER_IFACE = "network:router_interface";
202
203 private static final String NOT_AVAILABLE = "N/A";
204
Daniel Parka73c2362018-09-17 17:43:25 +0900205 private static final long TIMEOUT_MS = 5000;
206 private static final long WAIT_OUTPUT_STREAM_SECOND = 2;
207 private static final int SSH_PORT = 22;
208
Jian Li51728702019-05-17 18:38:56 +0900209 private static final int TAP_PORT_LENGTH = 11;
Jian Li62116942019-09-03 23:10:20 +0900210 private static final int PORT_NAME_MAX_LENGTH = 15;
Jian Li51728702019-05-17 18:38:56 +0900211
Jian Li091d8d22018-02-20 10:42:06 +0900212 /**
213 * Prevents object instantiation from external.
214 */
Jian Lidea0fdb2018-04-02 19:02:48 +0900215 private OpenstackNetworkingUtil() {
Jian Li091d8d22018-02-20 10:42:06 +0900216 }
217
218 /**
219 * Interprets JSON string to corresponding openstack model entity object.
220 *
Jian Li7b8c3682019-05-12 13:57:15 +0900221 * @param inputStr JSON string
Jian Li091d8d22018-02-20 10:42:06 +0900222 * @param entityClazz openstack model entity class
223 * @return openstack model entity object
224 */
Jian Li7b8c3682019-05-12 13:57:15 +0900225 public static ModelEntity jsonToModelEntity(String inputStr, Class entityClazz) {
Jian Li091d8d22018-02-20 10:42:06 +0900226 ObjectMapper mapper = new ObjectMapper();
227 try {
Jian Li7b8c3682019-05-12 13:57:15 +0900228 InputStream input = toInputStream(inputStr, REST_UTF8);
Jian Li091d8d22018-02-20 10:42:06 +0900229 JsonNode jsonTree = mapper.enable(INDENT_OUTPUT).readTree(input);
230 log.trace(new ObjectMapper().writeValueAsString(jsonTree));
231 return ObjectMapperSingleton.getContext(entityClazz)
232 .readerFor(entityClazz)
233 .readValue(jsonTree);
234 } catch (Exception e) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900235 log.error("Exception occurred because of {}", e);
Jian Li091d8d22018-02-20 10:42:06 +0900236 throw new IllegalArgumentException();
237 }
238 }
Jian Lieb9f77d2018-02-20 11:25:45 +0900239
240 /**
241 * Converts openstack model entity object into JSON object.
242 *
243 * @param entity openstack model entity object
244 * @param entityClazz openstack model entity class
245 * @return JSON object
246 */
247 public static ObjectNode modelEntityToJson(ModelEntity entity, Class entityClazz) {
248 ObjectMapper mapper = new ObjectMapper();
249 try {
250 String strModelEntity = ObjectMapperSingleton.getContext(entityClazz)
251 .writerFor(entityClazz)
252 .writeValueAsString(entity);
253 log.trace(strModelEntity);
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900254 return (ObjectNode) mapper.readTree(strModelEntity.getBytes(Charsets.UTF_8));
Daniel Park95985382018-07-23 11:38:07 +0900255 } catch (IOException e) {
256 log.error("IOException occurred because of {}", e.toString());
Jian Lieb9f77d2018-02-20 11:25:45 +0900257 throw new IllegalStateException();
258 }
259 }
Jian Li1064e4f2018-05-29 16:16:53 +0900260
261 /**
Jian Li24ec59f2018-05-23 19:01:25 +0900262 * Obtains a floating IP associated with the given instance port.
263 *
264 * @param port instance port
265 * @param fips a collection of floating IPs
266 * @return associated floating IP
267 */
268 public static NetFloatingIP associatedFloatingIp(InstancePort port,
269 Set<NetFloatingIP> fips) {
Daniel Park2ff66b42018-08-01 11:52:45 +0900270 for (NetFloatingIP fip : fips) {
271 if (Strings.isNullOrEmpty(fip.getFixedIpAddress())) {
272 continue;
Jian Li24ec59f2018-05-23 19:01:25 +0900273 }
Daniel Park2ff66b42018-08-01 11:52:45 +0900274 if (Strings.isNullOrEmpty(fip.getFloatingIpAddress())) {
275 continue;
276 }
Jian Li6bc29d92018-10-02 13:55:05 +0900277 if (fip.getFixedIpAddress().equals(port.ipAddress().toString()) &&
278 fip.getPortId().equals(port.portId())) {
Daniel Park2ff66b42018-08-01 11:52:45 +0900279 return fip;
280 }
Jian Li24ec59f2018-05-23 19:01:25 +0900281 }
Daniel Park2ff66b42018-08-01 11:52:45 +0900282
Jian Li24ec59f2018-05-23 19:01:25 +0900283 return null;
284 }
285
286 /**
287 * Checks whether the given floating IP is associated with a VM.
288 *
289 * @param service openstack network service
290 * @param fip floating IP
291 * @return true if the given floating IP associated with a VM, false otherwise
292 */
293 public static boolean isAssociatedWithVM(OpenstackNetworkService service,
294 NetFloatingIP fip) {
295 Port osPort = service.port(fip.getPortId());
296 if (osPort == null) {
297 return false;
298 }
299
300 if (!Strings.isNullOrEmpty(osPort.getDeviceId())) {
301 Network osNet = service.network(osPort.getNetworkId());
302 if (osNet == null) {
303 final String errorFormat = ERR_FLOW + "no network(%s) exists";
304 final String error = String.format(errorFormat,
305 fip.getFloatingIpAddress(), osPort.getNetworkId());
306 throw new IllegalStateException(error);
307 }
308 return true;
309 } else {
310 return false;
311 }
312 }
313
314 /**
Jian Lia171a432018-06-11 11:52:11 +0900315 * Obtains the gateway node by instance port.
316 *
317 * @param gateways a collection of gateway nodes
318 * @param instPort instance port
319 * @return a gateway node
320 */
321 public static OpenstackNode getGwByInstancePort(Set<OpenstackNode> gateways,
322 InstancePort instPort) {
323 OpenstackNode gw = null;
324 if (instPort != null && instPort.deviceId() != null) {
325 gw = getGwByComputeDevId(gateways, instPort.deviceId());
326 }
327 return gw;
328 }
329
330 /**
Jian Li1064e4f2018-05-29 16:16:53 +0900331 * Obtains the gateway node by device in compute node. Note that the gateway
332 * node is determined by device's device identifier.
333 *
334 * @param gws a collection of gateway nodes
335 * @param deviceId device identifier
336 * @return a gateway node
337 */
Jian Li5ecfd1a2018-12-10 11:41:03 +0900338 public static OpenstackNode getGwByComputeDevId(Set<OpenstackNode> gws,
339 DeviceId deviceId) {
Jian Li1064e4f2018-05-29 16:16:53 +0900340 int numOfGw = gws.size();
341
342 if (numOfGw == 0) {
343 return null;
344 }
345
346 int gwIndex = Math.abs(deviceId.hashCode()) % numOfGw;
347
348 return getGwByIndex(gws, gwIndex);
349 }
350
Jian Li51b844c2018-05-31 10:59:03 +0900351 /**
352 * Obtains a connected openstack client.
353 *
354 * @param osNode openstack node
355 * @return a connected openstack client
356 */
357 public static OSClient getConnectedClient(OpenstackNode osNode) {
Jian Lic704b672018-09-04 18:52:53 +0900358 OpenstackAuth auth = osNode.keystoneConfig().authentication();
Jian Li51b844c2018-05-31 10:59:03 +0900359 String endpoint = buildEndpoint(osNode);
360 Perspective perspective = auth.perspective();
Jian Li1064e4f2018-05-29 16:16:53 +0900361
Jian Li51b844c2018-05-31 10:59:03 +0900362 Config config = getSslConfig();
Jian Li1064e4f2018-05-29 16:16:53 +0900363
Jian Li51b844c2018-05-31 10:59:03 +0900364 try {
365 if (endpoint.contains(KEYSTONE_V2)) {
366 IOSClientBuilder.V2 builder = OSFactory.builderV2()
367 .endpoint(endpoint)
368 .tenantName(auth.project())
369 .credentials(auth.username(), auth.password())
370 .withConfig(config);
371
372 if (perspective != null) {
373 builder.perspective(getFacing(perspective));
374 }
375
376 return builder.authenticate();
377 } else if (endpoint.contains(KEYSTONE_V3)) {
378
379 Identifier project = Identifier.byName(auth.project());
380 Identifier domain = Identifier.byName(DOMAIN_DEFAULT);
381
382 IOSClientBuilder.V3 builder = OSFactory.builderV3()
383 .endpoint(endpoint)
384 .credentials(auth.username(), auth.password(), domain)
385 .scopeToProject(project, domain)
386 .withConfig(config);
387
388 if (perspective != null) {
389 builder.perspective(getFacing(perspective));
390 }
391
392 return builder.authenticate();
393 } else {
394 log.warn("Unrecognized keystone version type");
395 return null;
Jian Li1064e4f2018-05-29 16:16:53 +0900396 }
Jian Li51b844c2018-05-31 10:59:03 +0900397 } catch (AuthenticationException e) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900398 log.error("Authentication failed due to {}", e);
Jian Li51b844c2018-05-31 10:59:03 +0900399 return null;
Jian Li1064e4f2018-05-29 16:16:53 +0900400 }
Jian Li1064e4f2018-05-29 16:16:53 +0900401 }
Daniel Parkc4d06402018-05-28 15:57:37 +0900402
403 /**
Jian Lia97cec42019-10-31 22:24:17 +0900404 * Checks whether the given openstack port is smart NIC capable.
405 *
406 * @param port openstack port
407 * @return true if the given port is smart NIC capable, false otherwise
408 */
409 public static boolean isSmartNicCapable(Port port) {
410 if (port.getProfile() != null && port.getvNicType().equals(DIRECT)) {
411 String vendorInfo = String.valueOf(port.getProfile().get(PCI_VENDOR_INFO));
412 if (portNamePrefixMap().containsKey(vendorInfo)) {
413 log.debug("Port {} is a Smart NIC capable port.", port.getId());
414 return true;
415 }
416 return false;
417 }
418 return false;
419 }
420
421 /**
Daniel Parkc4d06402018-05-28 15:57:37 +0900422 * Extract the interface name with the supplied port.
423 *
424 * @param port port
425 * @return interface name
426 */
427 public static String getIntfNameFromPciAddress(Port port) {
Daniel Parkff178ba2018-11-23 15:57:24 +0900428 String intfName;
429
Daniel Park95985382018-07-23 11:38:07 +0900430 if (port.getProfile() == null || port.getProfile().isEmpty()) {
Jian Li51b844c2018-05-31 10:59:03 +0900431 log.error("Port profile is not found");
432 return null;
433 }
434
Daniel Park95985382018-07-23 11:38:07 +0900435 if (!port.getProfile().containsKey(PCISLOT) ||
436 Strings.isNullOrEmpty(port.getProfile().get(PCISLOT).toString())) {
Jian Li5ecfd1a2018-12-10 11:41:03 +0900437 log.error("Failed to retrieve the interface name because of no " +
438 "pci_slot information from the port");
Daniel Parkc4d06402018-05-28 15:57:37 +0900439 return null;
440 }
Jian Li51b844c2018-05-31 10:59:03 +0900441
Daniel Parkff178ba2018-11-23 15:57:24 +0900442 String vendorInfoForPort = String.valueOf(port.getProfile().get(PCI_VENDOR_INFO));
443
444 if (!portNamePrefixMap().containsKey(vendorInfoForPort)) {
445 log.debug("{} is an non-smart NIC prefix.", vendorInfoForPort);
446 return UNSUPPORTED_VENDOR;
447 }
448
449 String portNamePrefix = portNamePrefixMap().get(vendorInfoForPort);
450
Daniel Parkc4d06402018-05-28 15:57:37 +0900451 String busNumHex = port.getProfile().get(PCISLOT).toString().split(":")[1];
452 String busNumDecimal = String.valueOf(Integer.parseInt(busNumHex, HEX_RADIX));
453
454 String deviceNumHex = port.getProfile().get(PCISLOT).toString()
455 .split(":")[2]
456 .split("\\.")[0];
457 String deviceNumDecimal = String.valueOf(Integer.parseInt(deviceNumHex, HEX_RADIX));
458
459 String functionNumHex = port.getProfile().get(PCISLOT).toString()
460 .split(":")[2]
461 .split("\\.")[1];
462 String functionNumDecimal = String.valueOf(Integer.parseInt(functionNumHex, HEX_RADIX));
463
Daniel Parkc4d06402018-05-28 15:57:37 +0900464 if (functionNumDecimal.equals(ZERO_FUNCTION_NUMBER)) {
465 intfName = portNamePrefix + busNumDecimal + PREFIX_DEVICE_NUMBER + deviceNumDecimal;
466 } else {
467 intfName = portNamePrefix + busNumDecimal + PREFIX_DEVICE_NUMBER + deviceNumDecimal
468 + PREFIX_FUNCTION_NUMBER + functionNumDecimal;
469 }
470
471 return intfName;
472 }
Jian Li51b844c2018-05-31 10:59:03 +0900473
474 /**
Daniel Park95f73312018-07-31 15:48:34 +0900475 * Check if the given interface is added to the given device or not.
476 *
477 * @param deviceId device ID
478 * @param intfName interface name
479 * @param deviceService device service
480 * @return true if the given interface is added to the given device or false otherwise
481 */
Jian Li5ecfd1a2018-12-10 11:41:03 +0900482 public static boolean hasIntfAleadyInDevice(DeviceId deviceId,
483 String intfName,
484 DeviceService deviceService) {
Daniel Park95f73312018-07-31 15:48:34 +0900485 checkNotNull(deviceId);
486 checkNotNull(intfName);
487
Jian Li5ecfd1a2018-12-10 11:41:03 +0900488 return deviceService.getPorts(deviceId).stream().anyMatch(port ->
489 Objects.equals(port.annotations().value(PORT_NAME), intfName));
Daniel Park95f73312018-07-31 15:48:34 +0900490 }
491
492 /**
Jian Li0b564282018-06-20 00:50:53 +0900493 * Adds router interfaces to openstack admin service.
Jian Li0b564282018-06-20 00:50:53 +0900494 *
495 * @param osPort port
496 * @param adminService openstack admin service
497 */
Jian Li5ecfd1a2018-12-10 11:41:03 +0900498 public static void addRouterIface(Port osPort,
499 OpenstackRouterAdminService adminService) {
Jian Li0b564282018-06-20 00:50:53 +0900500 osPort.getFixedIps().forEach(p -> {
501 JsonNode jsonTree = new ObjectMapper().createObjectNode()
502 .put("id", osPort.getDeviceId())
503 .put("tenant_id", osPort.getTenantId())
504 .put("subnet_id", p.getSubnetId())
505 .put("port_id", osPort.getId());
506 try {
507 RouterInterface rIface = getContext(NeutronRouterInterface.class)
508 .readerFor(NeutronRouterInterface.class)
509 .readValue(jsonTree);
510 if (adminService.routerInterface(rIface.getPortId()) != null) {
511 adminService.updateRouterInterface(rIface);
512 } else {
513 adminService.addRouterInterface(rIface);
514 }
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900515 } catch (IOException e) {
516 log.error("IOException occurred because of {}", e);
Jian Li0b564282018-06-20 00:50:53 +0900517 }
518 });
519 }
520
521 /**
Jian Liecbf10c2019-10-02 20:36:09 +0900522 * Prints openstack security group.
523 *
524 * @param osSg openstack security group
525 */
526 public static void printSecurityGroup(SecurityGroup osSg) {
527 print(SECURITY_GROUP_FORMAT, osSg.getId(), osSg.getName());
528 }
529
530 /**
531 * Prints openstack network.
532 *
533 * @param osNet openstack network
534 */
535 public static void printNetwork(Network osNet) {
536 final String strNet = String.format(NETWORK_FORMAT,
537 osNet.getId(),
538 osNet.getName(),
539 osNet.getProviderSegID(),
540 osNet.getSubnets());
541 print(strNet);
542 }
543
544 /**
545 * Prints openstack subnet.
546 *
547 * @param osSubnet openstack subnet
548 * @param osNetService openstack network service
549 */
550 public static void printSubnet(Subnet osSubnet,
551 OpenstackNetworkService osNetService) {
552 final Network network = osNetService.network(osSubnet.getNetworkId());
553 final String netName = network == null ? NOT_AVAILABLE : network.getName();
554 final String strSubnet = String.format(SUBNET_FORMAT,
555 osSubnet.getId(),
556 netName,
557 osSubnet.getCidr());
558 print(strSubnet);
559 }
560
561 /**
562 * Prints openstack port.
563 *
564 * @param osPort openstack port
565 * @param osNetService openstack network service
566 */
567 public static void printPort(Port osPort,
568 OpenstackNetworkService osNetService) {
569 List<String> fixedIps = osPort.getFixedIps().stream()
570 .map(IP::getIpAddress)
571 .collect(Collectors.toList());
572 final Network network = osNetService.network(osPort.getNetworkId());
573 final String netName = network == null ? NOT_AVAILABLE : network.getName();
574 final String strPort = String.format(PORT_FORMAT,
575 osPort.getId(),
576 netName,
577 osPort.getMacAddress(),
578 fixedIps.isEmpty() ? "" : fixedIps);
579 print(strPort);
580 }
581
582 /**
583 * Prints openstack router.
584 *
585 * @param osRouter openstack router
586 * @param osNetService openstack network service
587 */
588 public static void printRouter(Router osRouter,
589 OpenstackNetworkService osNetService) {
590 List<String> externals = osNetService.ports().stream()
591 .filter(osPort -> Objects.equals(osPort.getDeviceId(), osRouter.getId()) &&
592 Objects.equals(osPort.getDeviceOwner(), DEVICE_OWNER_GW))
593 .flatMap(osPort -> osPort.getFixedIps().stream())
594 .map(IP::getIpAddress)
595 .collect(Collectors.toList());
596
597 List<String> internals = osNetService.ports().stream()
598 .filter(osPort -> Objects.equals(osPort.getDeviceId(), osRouter.getId()) &&
599 Objects.equals(osPort.getDeviceOwner(), DEVICE_OWNER_IFACE))
600 .flatMap(osPort -> osPort.getFixedIps().stream())
601 .map(IP::getIpAddress)
602 .collect(Collectors.toList());
603
604 final String strRouter = String.format(ROUTER_FORMAT,
605 osRouter.getId(),
606 osRouter.getName(),
607 externals.isEmpty() ? "" : externals,
608 internals.isEmpty() ? "" : internals);
609 print(strRouter);
610 }
611
612 /**
613 * Prints openstack router interface.
614 *
615 * @param osRouterIntf openstack router interface
616 */
617 public static void printRouterIntf(RouterInterface osRouterIntf) {
618 final String strRouterIntf = String.format(ROUTER_INTF_FORMAT,
619 osRouterIntf.getId(),
620 osRouterIntf.getTenantId(),
621 osRouterIntf.getSubnetId());
622 print(strRouterIntf);
623 }
624
625 /**
626 * Prints openstack floating IP.
627 *
628 * @param floatingIp floating IP
629 */
630 public static void printFloatingIp(NetFloatingIP floatingIp) {
631 final String strFloating = String.format(FLOATING_IP_FORMAT,
632 floatingIp.getId(),
633 floatingIp.getFloatingIpAddress(),
634 Strings.isNullOrEmpty(floatingIp.getFixedIpAddress()) ?
635 "" : floatingIp.getFixedIpAddress());
636 print(strFloating);
637 }
638
639 /**
Jian Li7f70bb72018-07-06 23:35:30 +0900640 * Obtains the property value with specified property key name.
641 *
642 * @param properties a collection of properties
643 * @param name key name
644 * @return mapping value
645 */
Jian Li5ecfd1a2018-12-10 11:41:03 +0900646 public static String getPropertyValue(Set<ConfigProperty> properties,
647 String name) {
Jian Li7f70bb72018-07-06 23:35:30 +0900648 Optional<ConfigProperty> property =
649 properties.stream().filter(p -> p.name().equals(name)).findFirst();
650 return property.map(ConfigProperty::value).orElse(null);
651 }
652
653 /**
Jian Li9d35bd62018-10-13 01:43:24 +0900654 * Obtains the boolean property value with specified property key name.
655 *
656 * @param properties a collection of properties
657 * @param name key name
658 * @return mapping value
659 */
Jian Li5ecfd1a2018-12-10 11:41:03 +0900660 public static boolean getPropertyValueAsBoolean(Set<ConfigProperty> properties,
661 String name) {
Jian Li9d35bd62018-10-13 01:43:24 +0900662 Optional<ConfigProperty> property =
663 properties.stream().filter(p -> p.name().equals(name)).findFirst();
664
665 return property.map(ConfigProperty::asBoolean).orElse(false);
666 }
667
668 /**
Jian Lif1efbe52018-07-17 23:20:16 +0900669 * Prints out the JSON string in pretty format.
670 *
671 * @param mapper Object mapper
672 * @param jsonString JSON string
673 * @return pretty formatted JSON string
674 */
675 public static String prettyJson(ObjectMapper mapper, String jsonString) {
676 try {
677 Object jsonObject = mapper.readValue(jsonString, Object.class);
678 return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
Daniel Park2ff66b42018-08-01 11:52:45 +0900679 } catch (JsonParseException e) {
680 log.debug("JsonParseException caused by {}", e);
681 } catch (JsonMappingException e) {
682 log.debug("JsonMappingException caused by {}", e);
683 } catch (JsonProcessingException e) {
684 log.debug("JsonProcessingException caused by {}", e);
Jian Lif1efbe52018-07-17 23:20:16 +0900685 } catch (IOException e) {
Daniel Park2ff66b42018-08-01 11:52:45 +0900686 log.debug("IOException caused by {}", e);
Jian Lif1efbe52018-07-17 23:20:16 +0900687 }
688 return null;
689 }
690
691 /**
Jian Li7f024de2018-07-07 03:51:02 +0900692 * Checks the validity of ARP mode.
693 *
694 * @param arpMode ARP mode
695 * @return returns true if the ARP mode is valid, false otherwise
696 */
697 public static boolean checkArpMode(String arpMode) {
698
699 if (isNullOrEmpty(arpMode)) {
700 return false;
701 } else {
702 return arpMode.equals(PROXY_MODE) || arpMode.equals(BROADCAST_MODE);
703 }
704 }
705
706 /**
Jian Licad36c72018-09-13 17:44:54 +0900707 * Checks the validity of activation flag.
708 *
709 * @param activationFlag activation flag
710 * @return returns true if the activation flag is valid, false otherwise
711 */
712 public static boolean checkActivationFlag(String activationFlag) {
713
714 switch (activationFlag) {
715 case ENABLE:
716 return true;
717 case DISABLE:
718 return false;
719 default:
720 throw new IllegalArgumentException("The given activation flag is not valid!");
721 }
722 }
723
724 /**
Jian Liec5c32b2018-07-13 14:28:58 +0900725 * Swaps current location with old location info.
726 * The revised instance port will be used to mod the flow rules after migration.
727 *
728 * @param instPort instance port
729 * @return location swapped instance port
730 */
731 public static InstancePort swapStaleLocation(InstancePort instPort) {
732 return DefaultInstancePort.builder()
733 .deviceId(instPort.oldDeviceId())
734 .portNumber(instPort.oldPortNumber())
735 .state(instPort.state())
736 .ipAddress(instPort.ipAddress())
737 .macAddress(instPort.macAddress())
738 .networkId(instPort.networkId())
739 .portId(instPort.portId())
740 .build();
741 }
742
743 /**
Daniel Park2ff66b42018-08-01 11:52:45 +0900744 * Compares two router interfaces are equal.
745 * Will be remove this after Openstack4j implements equals.
746 *
747 * @param routerInterface1 router interface
748 * @param routerInterface2 router interface
749 * @return returns true if two router interfaces are equal, false otherwise
750 */
Jian Li63430202018-08-30 16:24:09 +0900751 public static boolean routerInterfacesEquals(RouterInterface routerInterface1,
752 RouterInterface routerInterface2) {
Daniel Park2ff66b42018-08-01 11:52:45 +0900753 return Objects.equals(routerInterface1.getId(), routerInterface2.getId()) &&
754 Objects.equals(routerInterface1.getPortId(), routerInterface2.getPortId()) &&
755 Objects.equals(routerInterface1.getSubnetId(), routerInterface2.getSubnetId()) &&
756 Objects.equals(routerInterface1.getTenantId(), routerInterface2.getTenantId());
757 }
758
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900759 /**
760 * Returns the vnic type of given port.
761 *
762 * @param portName port name
763 * @return vnit type
764 */
Daniel Park7e8c4d82018-08-13 23:47:49 +0900765 public static VnicType vnicType(String portName) {
766 if (portName.startsWith(PORT_NAME_PREFIX_VM) ||
767 portName.startsWith(PORT_NAME_VHOST_USER_PREFIX_VM)) {
768 return VnicType.NORMAL;
769 } else if (isDirectPort(portName)) {
770 return VnicType.DIRECT;
771 } else {
772 return VnicType.UNSUPPORTED;
773 }
774 }
775
Jian Li63430202018-08-30 16:24:09 +0900776 /**
777 * Deserializes raw payload into HttpRequest object.
778 *
779 * @param rawData raw http payload
780 * @return HttpRequest object
781 */
782 public static HttpRequest parseHttpRequest(byte[] rawData) {
783 SessionInputBufferImpl sessionInputBuffer =
784 new SessionInputBufferImpl(
785 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
786 sessionInputBuffer.bind(new ByteArrayInputStream(rawData));
Jian Li5ecfd1a2018-12-10 11:41:03 +0900787 DefaultHttpRequestParser requestParser =
788 new DefaultHttpRequestParser(sessionInputBuffer);
Jian Li63430202018-08-30 16:24:09 +0900789 try {
790 return requestParser.parse();
791 } catch (IOException | HttpException e) {
792 log.warn("Failed to parse HttpRequest, due to {}", e);
793 }
794
795 return null;
796 }
797
798 /**
799 * Serializes HttpRequest object to byte array.
800 *
801 * @param request http request object
802 * @return byte array
803 */
804 public static byte[] unparseHttpRequest(HttpRequest request) {
805 try {
806 SessionOutputBufferImpl sessionOutputBuffer =
807 new SessionOutputBufferImpl(
808 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
809
810 ByteArrayOutputStream baos = new ByteArrayOutputStream();
811 sessionOutputBuffer.bind(baos);
812
Jian Li5ecfd1a2018-12-10 11:41:03 +0900813 HttpMessageWriter<HttpRequest> requestWriter =
814 new DefaultHttpRequestWriter(sessionOutputBuffer);
Jian Li63430202018-08-30 16:24:09 +0900815 requestWriter.write(request);
816 sessionOutputBuffer.flush();
817
818 return baos.toByteArray();
819 } catch (HttpException | IOException e) {
820 log.warn("Failed to unparse HttpRequest, due to {}", e);
821 }
822
823 return null;
824 }
825
826 /**
827 * Deserializes raw payload into HttpResponse object.
828 *
829 * @param rawData raw http payload
830 * @return HttpResponse object
831 */
832 public static HttpResponse parseHttpResponse(byte[] rawData) {
833 SessionInputBufferImpl sessionInputBuffer =
834 new SessionInputBufferImpl(
835 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
836 sessionInputBuffer.bind(new ByteArrayInputStream(rawData));
Jian Li5ecfd1a2018-12-10 11:41:03 +0900837 DefaultHttpResponseParser responseParser =
838 new DefaultHttpResponseParser(sessionInputBuffer);
Jian Li63430202018-08-30 16:24:09 +0900839 try {
840 return responseParser.parse();
841 } catch (IOException | HttpException e) {
842 log.warn("Failed to parse HttpResponse, due to {}", e);
843 }
844
845 return null;
846 }
847
848 /**
849 * Serializes HttpResponse header to byte array.
850 *
851 * @param response http response object
852 * @return byte array
853 */
854 public static byte[] unparseHttpResponseHeader(HttpResponse response) {
855 try {
856 SessionOutputBufferImpl sessionOutputBuffer =
857 new SessionOutputBufferImpl(
858 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
859
860 ByteArrayOutputStream headerBaos = new ByteArrayOutputStream();
861 sessionOutputBuffer.bind(headerBaos);
862
863 HttpMessageWriter<HttpResponse> responseWriter =
864 new DefaultHttpResponseWriter(sessionOutputBuffer);
865 responseWriter.write(response);
866 sessionOutputBuffer.flush();
867
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900868 log.debug(headerBaos.toString(Charsets.UTF_8.name()));
Jian Li63430202018-08-30 16:24:09 +0900869
870 return headerBaos.toByteArray();
871 } catch (IOException | HttpException e) {
872 log.warn("Failed to unparse HttpResponse headers, due to {}", e);
873 }
874
875 return null;
876 }
877
878 /**
879 * Serializes HttpResponse object to byte array.
880 *
881 * @param response http response object
882 * @return byte array
883 */
884 public static byte[] unparseHttpResponseBody(HttpResponse response) {
885 try {
886 ByteArrayOutputStream baos = new ByteArrayOutputStream();
887 response.getEntity().writeTo(baos);
888
889 log.debug(response.toString());
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900890 log.debug(baos.toString(Charsets.UTF_8.name()));
Jian Li63430202018-08-30 16:24:09 +0900891
892 return baos.toByteArray();
893 } catch (IOException e) {
894 log.warn("Failed to unparse HttpResponse, due to {}", e);
895 }
896
897 return null;
898 }
899
900 /**
901 * Encodes the given data using HmacSHA256 encryption method with given secret key.
902 *
903 * @param key secret key
904 * @param data data to be encrypted
905 * @return Hmac256 encrypted data
906 */
907 public static String hmacEncrypt(String key, String data) {
908 try {
909 Mac sha256Hmac = Mac.getInstance(HMAC_SHA256);
910 SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), HMAC_SHA256);
911 sha256Hmac.init(secretKey);
912 return Hex.encodeHexString(sha256Hmac.doFinal(data.getBytes("UTF-8")));
913 } catch (Exception e) {
914 log.warn("Failed to encrypt data {} using key {}, due to {}", data, key, e);
915 }
916 return null;
917 }
918
Daniel Parka73c2362018-09-17 17:43:25 +0900919 /**
920 * Creates flow trace request string.
921 *
922 * @param srcIp src ip address
923 * @param dstIp dst ip address
924 * @param srcInstancePort src instance port
925 * @param osNetService openstack networking service
Daniel Park5aef9822018-09-20 18:04:18 +0900926 * @param uplink true if this request is for uplink
Daniel Parka73c2362018-09-17 17:43:25 +0900927 * @return flow trace request string
928 */
929 public static String traceRequestString(String srcIp,
930 String dstIp,
931 InstancePort srcInstancePort,
Jian Li5ecfd1a2018-12-10 11:41:03 +0900932 OpenstackNetworkService osNetService,
933 boolean uplink) {
Daniel Parka73c2362018-09-17 17:43:25 +0900934
935 StringBuilder requestStringBuilder = new StringBuilder(DEFAULT_REQUEST_STRING);
936
937 if (uplink) {
938
939 requestStringBuilder.append(COMMA)
940 .append(IN_PORT)
941 .append(srcInstancePort.portNumber().toString())
942 .append(COMMA)
943 .append(NW_SRC)
944 .append(srcIp)
945 .append(COMMA);
946
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900947 String modifiedDstIp = dstIp;
Jian Li621f73c2018-12-15 01:49:22 +0900948 Type netType = osNetService.networkType(srcInstancePort.networkId());
949 if (netType == Type.VXLAN || netType == Type.GRE ||
950 netType == Type.VLAN || netType == Type.GENEVE) {
Daniel Parka73c2362018-09-17 17:43:25 +0900951 if (srcIp.equals(dstIp)) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900952 modifiedDstIp = osNetService.gatewayIp(srcInstancePort.portId());
Daniel Parka73c2362018-09-17 17:43:25 +0900953 requestStringBuilder.append(DL_DST)
954 .append(DEFAULT_GATEWAY_MAC_STR).append(COMMA);
Jian Li5ecfd1a2018-12-10 11:41:03 +0900955 } else if (!osNetService.ipPrefix(srcInstancePort.portId()).contains(
956 IpAddress.valueOf(dstIp))) {
Daniel Parka73c2362018-09-17 17:43:25 +0900957 requestStringBuilder.append(DL_DST)
958 .append(DEFAULT_GATEWAY_MAC_STR)
959 .append(COMMA);
960 }
961 } else {
962 if (srcIp.equals(dstIp)) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900963 modifiedDstIp = osNetService.gatewayIp(srcInstancePort.portId());
Daniel Parka73c2362018-09-17 17:43:25 +0900964 }
965 }
966
967 requestStringBuilder.append(NW_DST)
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900968 .append(modifiedDstIp)
Daniel Parka73c2362018-09-17 17:43:25 +0900969 .append("\n");
970 } else {
971 requestStringBuilder.append(COMMA)
972 .append(NW_SRC)
973 .append(dstIp)
974 .append(COMMA);
975
Jian Li621f73c2018-12-15 01:49:22 +0900976 Type netType = osNetService.networkType(srcInstancePort.networkId());
977
978 if (netType == Type.VXLAN || netType == Type.GRE ||
979 netType == Type.VLAN || netType == Type.GENEVE) {
Daniel Parka73c2362018-09-17 17:43:25 +0900980 requestStringBuilder.append(TUN_ID)
981 .append(osNetService.segmentId(srcInstancePort.networkId()))
982 .append(COMMA);
983 }
984 requestStringBuilder.append(NW_DST)
985 .append(srcIp)
986 .append("\n");
Daniel Parka73c2362018-09-17 17:43:25 +0900987 }
988
989 return requestStringBuilder.toString();
990 }
991
992 /**
993 * Sends flow trace string to node.
994 *
995 * @param requestString reqeust string
996 * @param node src node
997 * @return flow trace result in string format
998 */
999 public static String sendTraceRequestToNode(String requestString,
1000 OpenstackNode node) {
1001 String traceResult = null;
1002 OpenstackSshAuth sshAuth = node.sshAuthInfo();
1003
1004 try (SshClient client = SshClient.setUpDefaultClient()) {
1005 client.start();
1006
1007 try (ClientSession session = client
1008 .connect(sshAuth.id(), node.managementIp().getIp4Address().toString(), SSH_PORT)
1009 .verify(TIMEOUT_MS, TimeUnit.SECONDS).getSession()) {
1010 session.addPasswordIdentity(sshAuth.password());
1011 session.auth().verify(TIMEOUT_MS, TimeUnit.SECONDS);
1012
1013
1014 try (ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) {
1015
1016 log.debug("requestString: {}", requestString);
1017 final InputStream inputStream =
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001018 new ByteArrayInputStream(requestString.getBytes(Charsets.UTF_8));
Daniel Parka73c2362018-09-17 17:43:25 +09001019
Jian Li5ecfd1a2018-12-10 11:41:03 +09001020 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Daniel Parka73c2362018-09-17 17:43:25 +09001021 OutputStream errStream = new ByteArrayOutputStream();
1022
1023 channel.setIn(new NoCloseInputStream(inputStream));
1024 channel.setErr(errStream);
1025 channel.setOut(outputStream);
1026
1027 Collection<ClientChannelEvent> eventList = Lists.newArrayList();
1028 eventList.add(ClientChannelEvent.OPENED);
1029
1030 OpenFuture channelFuture = channel.open();
1031
1032 if (channelFuture.await(TIMEOUT_MS, TimeUnit.SECONDS)) {
1033
1034 long timeoutExpiredMs = System.currentTimeMillis() + TIMEOUT_MS;
1035
1036 while (!channelFuture.isOpened()) {
1037 if ((timeoutExpiredMs - System.currentTimeMillis()) <= 0) {
1038 log.error("Failed to open channel");
1039 return null;
1040 }
1041 }
1042 TimeUnit.SECONDS.sleep(WAIT_OUTPUT_STREAM_SECOND);
1043
Jian Li5ecfd1a2018-12-10 11:41:03 +09001044 traceResult = outputStream.toString(Charsets.UTF_8.name());
Daniel Parka73c2362018-09-17 17:43:25 +09001045
1046 channel.close();
1047 }
1048 } finally {
1049 session.close();
1050 }
1051 } finally {
1052 client.stop();
1053 }
1054
1055 } catch (Exception e) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001056 log.error("Exception occurred because of {}", e);
Daniel Parka73c2362018-09-17 17:43:25 +09001057 }
1058
1059 return traceResult;
1060 }
1061
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001062 /**
1063 * Returns the floating ip with supplied instance port.
1064 *
1065 * @param instancePort instance port
1066 * @param osRouterAdminService openstack router admin service
1067 * @return floating ip
1068 */
1069 public static NetFloatingIP floatingIpByInstancePort(InstancePort instancePort,
Jian Li5ecfd1a2018-12-10 11:41:03 +09001070 OpenstackRouterAdminService
1071 osRouterAdminService) {
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001072 return osRouterAdminService.floatingIps().stream()
1073 .filter(netFloatingIP -> netFloatingIP.getPortId() != null)
1074 .filter(netFloatingIP -> netFloatingIP.getPortId().equals(instancePort.portId()))
1075 .findAny().orElse(null);
1076 }
1077
1078 /**
1079 * Sends GARP packet with supplied floating ip information.
1080 *
1081 * @param floatingIP floating ip
1082 * @param instancePort instance port
1083 * @param vlanId vlain id
1084 * @param gatewayNode gateway node
1085 * @param packetService packet service
1086 */
Jian Li32b03622018-11-06 17:54:24 +09001087 public static void processGarpPacketForFloatingIp(NetFloatingIP floatingIP,
1088 InstancePort instancePort,
1089 VlanId vlanId,
1090 OpenstackNode gatewayNode,
1091 PacketService packetService) {
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001092 Ethernet ethernet = buildGratuitousArpPacket(floatingIP, instancePort, vlanId);
1093
1094 TrafficTreatment treatment = DefaultTrafficTreatment.builder()
1095 .setOutput(gatewayNode.uplinkPortNum()).build();
1096
1097 packetService.emit(new DefaultOutboundPacket(gatewayNode.intgBridge(), treatment,
1098 ByteBuffer.wrap(ethernet.serialize())));
1099 }
1100
1101 /**
1102 * Returns the external peer router with supplied network information.
1103 *
1104 * @param network network
1105 * @param osNetworkService openstack network service
1106 * @param osRouterAdminService openstack router admin service
1107 * @return external peer router
1108 */
1109 public static ExternalPeerRouter externalPeerRouterForNetwork(Network network,
Jian Li5ecfd1a2018-12-10 11:41:03 +09001110 OpenstackNetworkService
1111 osNetworkService,
1112 OpenstackRouterAdminService
1113 osRouterAdminService) {
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001114 if (network == null) {
1115 return null;
1116 }
1117
Jian Lie6e609f2019-05-14 17:45:54 +09001118 Subnet subnet = osNetworkService.subnets(network.getId())
1119 .stream().findAny().orElse(null);
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001120
1121 if (subnet == null) {
1122 return null;
1123 }
1124
1125 RouterInterface osRouterIface = osRouterAdminService.routerInterfaces().stream()
1126 .filter(i -> Objects.equals(i.getSubnetId(), subnet.getId()))
1127 .findAny().orElse(null);
1128 if (osRouterIface == null) {
1129 return null;
1130 }
1131
1132 Router osRouter = osRouterAdminService.router(osRouterIface.getId());
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001133 if (osRouter == null || osRouter.getExternalGatewayInfo() == null) {
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001134 return null;
1135 }
1136
1137 ExternalGateway exGatewayInfo = osRouter.getExternalGatewayInfo();
1138 return osNetworkService.externalPeerRouter(exGatewayInfo);
1139
1140 }
1141
Jian Liebde74d2018-11-14 00:18:57 +09001142 /**
1143 * Returns the external peer router with specified subnet information.
1144 *
1145 * @param subnet openstack subnet
1146 * @param osRouterService openstack router service
1147 * @param osNetworkService openstack network service
1148 * @return external peer router
1149 */
Jian Li5ecfd1a2018-12-10 11:41:03 +09001150 public static ExternalPeerRouter externalPeerRouterFromSubnet(Subnet subnet,
1151 OpenstackRouterService
1152 osRouterService,
1153 OpenstackNetworkService
1154 osNetworkService) {
Jian Liebde74d2018-11-14 00:18:57 +09001155 Router osRouter = getRouterFromSubnet(subnet, osRouterService);
1156 if (osRouter == null) {
1157 return null;
1158 }
1159 if (osRouter.getExternalGatewayInfo() == null) {
1160 // this router does not have external connectivity
1161 log.trace("router({}) has no external gateway",
1162 osRouter.getName());
1163 return null;
1164 }
1165
1166 return osNetworkService.externalPeerRouter(osRouter.getExternalGatewayInfo());
1167 }
1168
1169 /**
1170 * Returns the external ip address with specified router information.
1171 *
1172 * @param srcSubnet source subnet
1173 * @param osRouterService openstack router service
1174 * @param osNetworkService openstack network service
1175 * @return external ip address
1176 */
1177 public static IpAddress externalIpFromSubnet(Subnet srcSubnet,
Jian Li5ecfd1a2018-12-10 11:41:03 +09001178 OpenstackRouterService
1179 osRouterService,
1180 OpenstackNetworkService
1181 osNetworkService) {
Jian Liebde74d2018-11-14 00:18:57 +09001182
1183 Router osRouter = getRouterFromSubnet(srcSubnet, osRouterService);
1184
1185 if (osRouter.getExternalGatewayInfo() == null) {
1186 // this router does not have external connectivity
1187 log.trace("router({}) has no external gateway",
1188 osRouter.getName());
1189 return null;
1190 }
1191
1192 return getExternalIp(osRouter, osNetworkService);
1193 }
1194
1195 /**
1196 * Returns the external ip address with specified router information.
1197 *
1198 * @param router openstack router
1199 * @param osNetworkService openstack network service
1200 * @return external ip address
1201 */
Jian Li5ecfd1a2018-12-10 11:41:03 +09001202 public static IpAddress getExternalIp(Router router,
1203 OpenstackNetworkService osNetworkService) {
Jian Liebde74d2018-11-14 00:18:57 +09001204 if (router == null) {
1205 return null;
1206 }
1207
1208 ExternalGateway externalGateway = router.getExternalGatewayInfo();
1209 if (externalGateway == null || !externalGateway.isEnableSnat()) {
Jian Li5ecfd1a2018-12-10 11:41:03 +09001210 log.trace("Failed to get externalIp for router {} because " +
1211 "externalGateway is null or SNAT is disabled",
Jian Liebde74d2018-11-14 00:18:57 +09001212 router.getId());
1213 return null;
1214 }
1215
1216 // TODO fix openstack4j for ExternalGateway provides external fixed IP list
1217 Port exGatewayPort = osNetworkService.ports(externalGateway.getNetworkId())
1218 .stream()
1219 .filter(port -> Objects.equals(port.getDeviceId(), router.getId()))
1220 .findAny().orElse(null);
1221
1222 if (exGatewayPort == null) {
1223 return null;
1224 }
1225
1226 return IpAddress.valueOf(exGatewayPort.getFixedIps().stream()
1227 .findAny().get().getIpAddress());
1228 }
1229
Jian Li2d68c192018-12-13 15:52:59 +09001230 /**
1231 * Returns the tunnel port number with specified net ID and openstack node.
1232 *
1233 * @param netId network ID
1234 * @param netService network service
1235 * @param osNode openstack node
1236 * @return tunnel port number
1237 */
1238 public static PortNumber tunnelPortNumByNetId(String netId,
1239 OpenstackNetworkService netService,
1240 OpenstackNode osNode) {
SONA Project6bc5c4a2018-12-14 23:49:52 +09001241 Type netType = netService.networkType(netId);
Jian Li2d68c192018-12-13 15:52:59 +09001242
1243 if (netType == null) {
1244 return null;
1245 }
1246
1247 return tunnelPortNumByNetType(netType, osNode);
1248 }
1249
1250 /**
1251 * Returns the tunnel port number with specified net type and openstack node.
1252 *
1253 * @param netType network type
1254 * @param osNode openstack node
1255 * @return tunnel port number
1256 */
SONA Project6bc5c4a2018-12-14 23:49:52 +09001257 public static PortNumber tunnelPortNumByNetType(Type netType, OpenstackNode osNode) {
Jian Li2d68c192018-12-13 15:52:59 +09001258 switch (netType) {
1259 case VXLAN:
1260 return osNode.vxlanTunnelPortNum();
1261 case GRE:
1262 return osNode.greTunnelPortNum();
Jian Li621f73c2018-12-15 01:49:22 +09001263 case GENEVE:
1264 return osNode.geneveTunnelPortNum();
Jian Li2d68c192018-12-13 15:52:59 +09001265 default:
1266 return null;
1267 }
1268 }
1269
Jian Li7b8c3682019-05-12 13:57:15 +09001270 /**
1271 * Returns the REST URL of active node.
1272 *
1273 * @param haService openstack HA service
1274 * @return REST URL of active node
1275 */
1276 public static String getActiveUrl(OpenstackHaService haService) {
1277 return "http://" + haService.getActiveIp().toString() + ":" +
1278 REST_PORT + "/" + OPENSTACK_NETWORKING_REST_PATH + "/";
1279 }
1280
1281 /**
1282 * Returns the REST client instance with given resource path.
1283 *
1284 * @param haService openstack HA service
1285 * @param resourcePath resource path
1286 * @return REST client instance
1287 */
1288 public static WebTarget getActiveClient(OpenstackHaService haService,
1289 String resourcePath) {
1290 HttpAuthenticationFeature feature =
1291 HttpAuthenticationFeature.universal(REST_USER, REST_PASSWORD);
1292 Client client = ClientBuilder.newClient().register(feature);
1293 return client.target(getActiveUrl(haService)).path(resourcePath);
1294 }
1295
1296 /**
1297 * Returns the post response from the active node.
1298 *
1299 * @param haService openstack HA service
1300 * @param resourcePath resource path
1301 * @param input input
1302 * @return post response
1303 */
1304 public static Response syncPost(OpenstackHaService haService,
1305 String resourcePath,
1306 String input) {
1307
1308 log.debug("Sync POST request with {} on {}",
1309 haService.getActiveIp().toString(), resourcePath);
1310
1311 return getActiveClient(haService, resourcePath)
1312 .request(APPLICATION_JSON_TYPE)
1313 .post(Entity.json(input));
1314 }
1315
1316 /**
1317 * Returns the put response from the active node.
1318 *
1319 * @param haService openstack HA service
1320 * @param resourcePath resource path
1321 * @param id resource identifier
1322 * @param input input
1323 * @return put response
1324 */
1325 public static Response syncPut(OpenstackHaService haService,
1326 String resourcePath,
1327 String id, String input) {
1328 return syncPut(haService, resourcePath, null, id, input);
1329 }
1330
1331 /**
1332 * Returns the put response from the active node.
1333 *
1334 * @param haService openstack HA service
1335 * @param resourcePath resource path
1336 * @param id resource identifier
1337 * @param suffix resource suffix
1338 * @param input input
1339 * @return put response
1340 */
1341 public static Response syncPut(OpenstackHaService haService,
1342 String resourcePath,
1343 String suffix,
1344 String id, String input) {
1345
1346 log.debug("Sync PUT request with {} on {}",
1347 haService.getActiveIp().toString(), resourcePath);
1348
1349 String pathStr = "/" + id;
1350
1351 if (suffix != null) {
1352 pathStr += "/" + suffix;
1353 }
1354
1355 return getActiveClient(haService, resourcePath)
1356 .path(pathStr)
1357 .request(APPLICATION_JSON_TYPE)
1358 .put(Entity.json(input));
1359 }
1360
1361 /**
1362 * Returns the delete response from the active node.
1363 *
1364 * @param haService openstack HA service
1365 * @param resourcePath resource path
1366 * @param id resource identifier
1367 * @return delete response
1368 */
1369 public static Response syncDelete(OpenstackHaService haService,
1370 String resourcePath,
1371 String id) {
1372
1373 log.debug("Sync DELETE request with {} on {}",
1374 haService.getActiveIp().toString(), resourcePath);
1375
1376 return getActiveClient(haService, resourcePath)
1377 .path("/" + id)
1378 .request(APPLICATION_JSON_TYPE)
1379 .delete();
1380 }
1381
Jian Li51728702019-05-17 18:38:56 +09001382 /**
1383 * Gets the ovsdb client with supplied openstack node.
1384 *
1385 * @param node openstack node
1386 * @param ovsdbPort openvswitch DB port number
1387 * @param controller openvswitch DB controller instance
1388 * @return ovsdb client instance
1389 */
1390 public static OvsdbClientService getOvsdbClient(OpenstackNode node, int ovsdbPort,
1391 OvsdbController controller) {
1392 OvsdbNodeId ovsdb = new OvsdbNodeId(node.managementIp(), ovsdbPort);
1393 return controller.getOvsdbClient(ovsdb);
1394 }
1395
1396 /**
1397 * Obtains the name of interface attached to the openstack VM.
1398 *
1399 * @param portId openstack port identifier
1400 * @return name of interface
1401 */
1402 public static String ifaceNameFromOsPortId(String portId) {
1403 if (portId != null) {
1404 return PORT_NAME_PREFIX_VM + StringUtils.substring(portId, 0, TAP_PORT_LENGTH);
1405 }
1406
1407 return null;
1408 }
1409
Jian Li5ecfd1a2018-12-10 11:41:03 +09001410 private static Router getRouterFromSubnet(Subnet subnet,
1411 OpenstackRouterService osRouterService) {
Jian Liebde74d2018-11-14 00:18:57 +09001412 RouterInterface osRouterIface = osRouterService.routerInterfaces().stream()
1413 .filter(i -> Objects.equals(i.getSubnetId(), subnet.getId()))
1414 .findAny().orElse(null);
1415 if (osRouterIface == null) {
1416 return null;
1417 }
1418
1419 return osRouterService.router(osRouterIface.getId());
1420 }
1421
Daniel Park7e8c4d82018-08-13 23:47:49 +09001422 private static boolean isDirectPort(String portName) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001423 return portNamePrefixMap().values().stream().anyMatch(portName::startsWith);
Daniel Park7e8c4d82018-08-13 23:47:49 +09001424 }
1425
Daniel Park2ff66b42018-08-01 11:52:45 +09001426 /**
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001427 * Returns GARP packet with supplied floating ip and instance port information.
1428 *
1429 * @param floatingIP floating ip
1430 * @param instancePort instance port
1431 * @param vlanId vlan id
1432 * @return GARP packet
1433 */
1434 private static Ethernet buildGratuitousArpPacket(NetFloatingIP floatingIP,
1435 InstancePort instancePort,
1436 VlanId vlanId) {
1437 Ethernet ethernet = new Ethernet();
1438 ethernet.setDestinationMACAddress(MacAddress.BROADCAST);
1439 ethernet.setSourceMACAddress(instancePort.macAddress());
1440 ethernet.setEtherType(Ethernet.TYPE_ARP);
1441 ethernet.setVlanID(vlanId.id());
1442
1443 ARP arp = new ARP();
1444 arp.setOpCode(ARP.OP_REPLY);
1445 arp.setProtocolType(ARP.PROTO_TYPE_IP);
1446 arp.setHardwareType(ARP.HW_TYPE_ETHERNET);
1447
1448 arp.setProtocolAddressLength((byte) Ip4Address.BYTE_LENGTH);
1449 arp.setHardwareAddressLength((byte) Ethernet.DATALAYER_ADDRESS_LENGTH);
1450
1451 arp.setSenderHardwareAddress(instancePort.macAddress().toBytes());
1452 arp.setTargetHardwareAddress(MacAddress.BROADCAST.toBytes());
1453
Jian Li5ecfd1a2018-12-10 11:41:03 +09001454 arp.setSenderProtocolAddress(valueOf(floatingIP.getFloatingIpAddress()).toInt());
1455 arp.setTargetProtocolAddress(valueOf(floatingIP.getFloatingIpAddress()).toInt());
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001456
1457 ethernet.setPayload(arp);
1458
1459 return ethernet;
1460 }
1461
1462 /**
Jian Li62116942019-09-03 23:10:20 +09001463 * Re-structures the OVS port name.
1464 * The length of OVS port name should be not large than 15.
1465 *
1466 * @param portName original port name
1467 * @return re-structured OVS port name
1468 */
1469 public static String structurePortName(String portName) {
1470
1471 // The size of OVS port name should not be larger than 15
1472 if (portName.length() > PORT_NAME_MAX_LENGTH) {
1473 return StringUtils.substring(portName, 0, PORT_NAME_MAX_LENGTH);
1474 }
1475
1476 return portName;
1477 }
1478
1479 /**
Jian Lie87c2712019-09-11 11:15:16 +09001480 * Obtains flow group key from the given id.
1481 *
1482 * @param groupId flow group identifier
1483 * @return flow group key
1484 */
1485 public static GroupKey getGroupKey(int groupId) {
1486 return new DefaultGroupKey((Integer.toString(groupId)).getBytes());
1487 }
1488
1489 /**
Jian Lif654dd12020-01-30 17:41:26 +09001490 * Calculate the broadcast address from given IP address and subnet prefix length.
1491 *
1492 * @param ipAddr IP address
1493 * @param prefixLength subnet prefix length
1494 * @return broadcast address
1495 */
1496 public static String getBroadcastAddr(String ipAddr, int prefixLength) {
1497 String subnet = ipAddr + "/" + prefixLength;
1498 SubnetUtils utils = new SubnetUtils(subnet);
1499 return utils.getInfo().getBroadcastAddress();
1500 }
1501
1502 /**
Jian Li51b844c2018-05-31 10:59:03 +09001503 * Builds up and a complete endpoint URL from gateway node.
1504 *
1505 * @param node gateway node
1506 * @return a complete endpoint URL
1507 */
1508 private static String buildEndpoint(OpenstackNode node) {
1509
Jian Lic704b672018-09-04 18:52:53 +09001510 OpenstackAuth auth = node.keystoneConfig().authentication();
Jian Li51b844c2018-05-31 10:59:03 +09001511
1512 StringBuilder endpointSb = new StringBuilder();
1513 endpointSb.append(auth.protocol().name().toLowerCase());
1514 endpointSb.append("://");
Jian Lic704b672018-09-04 18:52:53 +09001515 endpointSb.append(node.keystoneConfig().endpoint());
Jian Li51b844c2018-05-31 10:59:03 +09001516 return endpointSb.toString();
1517 }
1518
1519 /**
1520 * Obtains the SSL config without verifying the certification.
1521 *
1522 * @return SSL config
1523 */
1524 private static Config getSslConfig() {
1525 // we bypass the SSL certification verification for now
1526 // TODO: verify server side SSL using a given certification
1527 Config config = Config.newConfig().withSSLVerificationDisabled();
1528
1529 TrustManager[] trustAllCerts = new TrustManager[]{
1530 new X509TrustManager() {
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001531 @Override
Jian Li51b844c2018-05-31 10:59:03 +09001532 public X509Certificate[] getAcceptedIssuers() {
1533 return null;
1534 }
1535
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001536 @Override
Jian Li51b844c2018-05-31 10:59:03 +09001537 public void checkClientTrusted(X509Certificate[] certs,
1538 String authType) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001539 return;
Jian Li51b844c2018-05-31 10:59:03 +09001540 }
1541
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001542 @Override
Jian Li51b844c2018-05-31 10:59:03 +09001543 public void checkServerTrusted(X509Certificate[] certs,
1544 String authType) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001545 return;
Jian Li51b844c2018-05-31 10:59:03 +09001546 }
1547 }
1548 };
1549
1550 HostnameVerifier allHostsValid = (hostname, session) -> true;
1551
1552 try {
1553 SSLContext sc = SSLContext.getInstance(SSL_TYPE);
1554 sc.init(null, trustAllCerts,
1555 new java.security.SecureRandom());
1556 HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
1557 HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
1558
1559 config.withSSLContext(sc);
1560 } catch (Exception e) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001561 log.error("Failed to access OpenStack service due to {}", e);
Jian Li51b844c2018-05-31 10:59:03 +09001562 return null;
1563 }
1564
1565 return config;
1566 }
1567
1568 /**
1569 * Obtains the facing object with given openstack perspective.
1570 *
1571 * @param perspective keystone perspective
1572 * @return facing object
1573 */
1574 private static Facing getFacing(Perspective perspective) {
1575
1576 switch (perspective) {
1577 case PUBLIC:
1578 return Facing.PUBLIC;
1579 case ADMIN:
1580 return Facing.ADMIN;
1581 case INTERNAL:
1582 return Facing.INTERNAL;
1583 default:
1584 return null;
1585 }
1586 }
1587
1588 /**
1589 * Obtains gateway instance by giving index number.
1590 *
1591 * @param gws a collection of gateway nodes
1592 * @param index index number
1593 * @return gateway instance
1594 */
1595 private static OpenstackNode getGwByIndex(Set<OpenstackNode> gws, int index) {
1596 Map<String, OpenstackNode> hashMap = new HashMap<>();
1597 gws.forEach(gw -> hashMap.put(gw.hostname(), gw));
1598 TreeMap<String, OpenstackNode> treeMap = new TreeMap<>(hashMap);
1599 Iterator<String> iteratorKey = treeMap.keySet().iterator();
1600
1601 int intIndex = 0;
1602 OpenstackNode gw = null;
1603 while (iteratorKey.hasNext()) {
1604 String key = iteratorKey.next();
1605
1606 if (intIndex == index) {
1607 gw = treeMap.get(key);
1608 }
1609 intIndex++;
1610 }
1611 return gw;
1612 }
Jian Liecbf10c2019-10-02 20:36:09 +09001613
1614 private static void print(String format, Object... args) {
1615 System.out.println(String.format(format, args));
1616 }
Jian Li63430202018-08-30 16:24:09 +09001617}