blob: 80d18b395b0cd4b33b023ec8d7b17125efeb75d6 [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 Li63430202018-08-30 16:24:09 +090029import org.apache.http.HttpException;
30import org.apache.http.HttpRequest;
31import org.apache.http.HttpResponse;
32import org.apache.http.impl.io.DefaultHttpRequestParser;
33import org.apache.http.impl.io.DefaultHttpRequestWriter;
34import org.apache.http.impl.io.DefaultHttpResponseParser;
35import org.apache.http.impl.io.DefaultHttpResponseWriter;
36import org.apache.http.impl.io.HttpTransportMetricsImpl;
37import org.apache.http.impl.io.SessionInputBufferImpl;
38import org.apache.http.impl.io.SessionOutputBufferImpl;
39import org.apache.http.io.HttpMessageWriter;
Daniel Parka73c2362018-09-17 17:43:25 +090040import org.apache.sshd.client.SshClient;
41import org.apache.sshd.client.channel.ClientChannel;
42import org.apache.sshd.client.channel.ClientChannelEvent;
43import org.apache.sshd.client.future.OpenFuture;
44import org.apache.sshd.client.session.ClientSession;
45import org.apache.sshd.common.util.io.NoCloseInputStream;
Jian Li7b8c3682019-05-12 13:57:15 +090046import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090047import org.onlab.packet.ARP;
48import org.onlab.packet.Ethernet;
49import org.onlab.packet.Ip4Address;
Daniel Parka73c2362018-09-17 17:43:25 +090050import org.onlab.packet.IpAddress;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090051import org.onlab.packet.MacAddress;
52import org.onlab.packet.VlanId;
Jian Li7f70bb72018-07-06 23:35:30 +090053import org.onosproject.cfg.ConfigProperty;
Jian Li1064e4f2018-05-29 16:16:53 +090054import org.onosproject.net.DeviceId;
Jian Li2d68c192018-12-13 15:52:59 +090055import org.onosproject.net.PortNumber;
Daniel Park95f73312018-07-31 15:48:34 +090056import org.onosproject.net.device.DeviceService;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090057import org.onosproject.net.flow.DefaultTrafficTreatment;
58import org.onosproject.net.flow.TrafficTreatment;
Jian Lid5727622019-09-11 11:15:16 +090059import org.onosproject.net.group.DefaultGroupKey;
60import org.onosproject.net.group.GroupKey;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090061import org.onosproject.net.packet.DefaultOutboundPacket;
62import org.onosproject.net.packet.PacketService;
Daniel Park7e8c4d82018-08-13 23:47:49 +090063import org.onosproject.openstacknetworking.api.Constants.VnicType;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090064import org.onosproject.openstacknetworking.api.ExternalPeerRouter;
Jian Lia171a432018-06-11 11:52:11 +090065import org.onosproject.openstacknetworking.api.InstancePort;
Jian Li7b8c3682019-05-12 13:57:15 +090066import org.onosproject.openstacknetworking.api.OpenstackHaService;
SONA Project6bc5c4a2018-12-14 23:49:52 +090067import org.onosproject.openstacknetworking.api.OpenstackNetwork.Type;
Jian Li24ec59f2018-05-23 19:01:25 +090068import org.onosproject.openstacknetworking.api.OpenstackNetworkService;
Jian Li7f70bb72018-07-06 23:35:30 +090069import org.onosproject.openstacknetworking.api.OpenstackRouterAdminService;
Jian Liebde74d2018-11-14 00:18:57 +090070import org.onosproject.openstacknetworking.api.OpenstackRouterService;
Jian Liec5c32b2018-07-13 14:28:58 +090071import org.onosproject.openstacknetworking.impl.DefaultInstancePort;
Jian Li51b844c2018-05-31 10:59:03 +090072import org.onosproject.openstacknode.api.OpenstackAuth;
73import org.onosproject.openstacknode.api.OpenstackAuth.Perspective;
Jian Li1064e4f2018-05-29 16:16:53 +090074import org.onosproject.openstacknode.api.OpenstackNode;
Daniel Parka73c2362018-09-17 17:43:25 +090075import org.onosproject.openstacknode.api.OpenstackSshAuth;
Jian Li51728702019-05-17 18:38:56 +090076import org.onosproject.ovsdb.controller.OvsdbClientService;
77import org.onosproject.ovsdb.controller.OvsdbController;
78import org.onosproject.ovsdb.controller.OvsdbNodeId;
Jian Li51b844c2018-05-31 10:59:03 +090079import org.openstack4j.api.OSClient;
80import org.openstack4j.api.client.IOSClientBuilder;
81import org.openstack4j.api.exceptions.AuthenticationException;
82import org.openstack4j.api.types.Facing;
83import org.openstack4j.core.transport.Config;
Jian Li091d8d22018-02-20 10:42:06 +090084import org.openstack4j.core.transport.ObjectMapperSingleton;
85import org.openstack4j.model.ModelEntity;
Jian Li51b844c2018-05-31 10:59:03 +090086import org.openstack4j.model.common.Identifier;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090087import org.openstack4j.model.network.ExternalGateway;
Jian Li40f032a2019-10-02 20:36:09 +090088import org.openstack4j.model.network.IP;
Jian Li24ec59f2018-05-23 19:01:25 +090089import org.openstack4j.model.network.NetFloatingIP;
90import org.openstack4j.model.network.Network;
Jian Lia171a432018-06-11 11:52:11 +090091import org.openstack4j.model.network.Port;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090092import org.openstack4j.model.network.Router;
Jian Li0b564282018-06-20 00:50:53 +090093import org.openstack4j.model.network.RouterInterface;
Jian Li40f032a2019-10-02 20:36:09 +090094import org.openstack4j.model.network.SecurityGroup;
Daniel Park4fa1f5e2018-10-17 12:41:52 +090095import org.openstack4j.model.network.Subnet;
Jian Li51b844c2018-05-31 10:59:03 +090096import org.openstack4j.openstack.OSFactory;
Jian Li0b564282018-06-20 00:50:53 +090097import org.openstack4j.openstack.networking.domain.NeutronRouterInterface;
Jian Li091d8d22018-02-20 10:42:06 +090098import org.slf4j.Logger;
99import org.slf4j.LoggerFactory;
100
Jian Li63430202018-08-30 16:24:09 +0900101import javax.crypto.Mac;
102import javax.crypto.spec.SecretKeySpec;
Jian Li51b844c2018-05-31 10:59:03 +0900103import javax.net.ssl.HostnameVerifier;
104import javax.net.ssl.HttpsURLConnection;
105import javax.net.ssl.SSLContext;
106import javax.net.ssl.TrustManager;
107import javax.net.ssl.X509TrustManager;
Jian Li7b8c3682019-05-12 13:57:15 +0900108import javax.ws.rs.client.Client;
109import javax.ws.rs.client.ClientBuilder;
110import javax.ws.rs.client.Entity;
111import javax.ws.rs.client.WebTarget;
112import javax.ws.rs.core.Response;
Jian Li63430202018-08-30 16:24:09 +0900113import java.io.ByteArrayInputStream;
114import java.io.ByteArrayOutputStream;
Jian Li0b564282018-06-20 00:50:53 +0900115import java.io.IOException;
Jian Li091d8d22018-02-20 10:42:06 +0900116import java.io.InputStream;
Daniel Parka73c2362018-09-17 17:43:25 +0900117import java.io.OutputStream;
Daniel Park4fa1f5e2018-10-17 12:41:52 +0900118import java.nio.ByteBuffer;
Jian Li51b844c2018-05-31 10:59:03 +0900119import java.security.cert.X509Certificate;
Daniel Parka73c2362018-09-17 17:43:25 +0900120import java.util.Collection;
Jian Li1064e4f2018-05-29 16:16:53 +0900121import java.util.HashMap;
122import java.util.Iterator;
Jian Li40f032a2019-10-02 20:36:09 +0900123import java.util.List;
Jian Li1064e4f2018-05-29 16:16:53 +0900124import java.util.Map;
Daniel Park95f73312018-07-31 15:48:34 +0900125import java.util.Objects;
Jian Li7f70bb72018-07-06 23:35:30 +0900126import java.util.Optional;
Jian Li1064e4f2018-05-29 16:16:53 +0900127import java.util.Set;
128import java.util.TreeMap;
Daniel Parka73c2362018-09-17 17:43:25 +0900129import java.util.concurrent.TimeUnit;
Jian Li40f032a2019-10-02 20:36:09 +0900130import java.util.stream.Collectors;
Jian Li091d8d22018-02-20 10:42:06 +0900131
132import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT;
Daniel Park95f73312018-07-31 15:48:34 +0900133import static com.google.common.base.Preconditions.checkNotNull;
Jian Li7f024de2018-07-07 03:51:02 +0900134import static com.google.common.base.Strings.isNullOrEmpty;
Jian Li7b8c3682019-05-12 13:57:15 +0900135import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE;
136import static org.apache.commons.io.IOUtils.toInputStream;
Jian Li5ecfd1a2018-12-10 11:41:03 +0900137import static org.onlab.packet.Ip4Address.valueOf;
Daniel Park95f73312018-07-31 15:48:34 +0900138import static org.onosproject.net.AnnotationKeys.PORT_NAME;
Daniel Parka73c2362018-09-17 17:43:25 +0900139import static org.onosproject.openstacknetworking.api.Constants.DEFAULT_GATEWAY_MAC_STR;
Jian Licda74c82019-10-31 22:24:17 +0900140import static org.onosproject.openstacknetworking.api.Constants.DIRECT;
Jian Li40f032a2019-10-02 20:36:09 +0900141import static org.onosproject.openstacknetworking.api.Constants.FLOATING_IP_FORMAT;
142import static org.onosproject.openstacknetworking.api.Constants.NETWORK_FORMAT;
Jian Li7b8c3682019-05-12 13:57:15 +0900143import static org.onosproject.openstacknetworking.api.Constants.OPENSTACK_NETWORKING_REST_PATH;
Daniel Parkc4d06402018-05-28 15:57:37 +0900144import static org.onosproject.openstacknetworking.api.Constants.PCISLOT;
145import static org.onosproject.openstacknetworking.api.Constants.PCI_VENDOR_INFO;
Jian Li40f032a2019-10-02 20:36:09 +0900146import static org.onosproject.openstacknetworking.api.Constants.PORT_FORMAT;
Daniel Park7e8c4d82018-08-13 23:47:49 +0900147import static org.onosproject.openstacknetworking.api.Constants.PORT_NAME_PREFIX_VM;
148import static org.onosproject.openstacknetworking.api.Constants.PORT_NAME_VHOST_USER_PREFIX_VM;
Jian Li7b8c3682019-05-12 13:57:15 +0900149import static org.onosproject.openstacknetworking.api.Constants.REST_PASSWORD;
150import static org.onosproject.openstacknetworking.api.Constants.REST_PORT;
151import static org.onosproject.openstacknetworking.api.Constants.REST_USER;
152import static org.onosproject.openstacknetworking.api.Constants.REST_UTF8;
Jian Li40f032a2019-10-02 20:36:09 +0900153import static org.onosproject.openstacknetworking.api.Constants.ROUTER_FORMAT;
154import static org.onosproject.openstacknetworking.api.Constants.ROUTER_INTF_FORMAT;
155import static org.onosproject.openstacknetworking.api.Constants.SECURITY_GROUP_FORMAT;
156import static org.onosproject.openstacknetworking.api.Constants.SUBNET_FORMAT;
Daniel Parkec9d1132018-08-19 11:18:03 +0900157import static org.onosproject.openstacknetworking.api.Constants.UNSUPPORTED_VENDOR;
Ray Milkey9dc57392018-06-08 08:52:31 -0700158import static org.onosproject.openstacknetworking.api.Constants.portNamePrefixMap;
Jian Li0b564282018-06-20 00:50:53 +0900159import static org.openstack4j.core.transport.ObjectMapperSingleton.getContext;
Jian Li091d8d22018-02-20 10:42:06 +0900160
161/**
162 * An utility that used in openstack networking app.
163 */
Jian Lidea0fdb2018-04-02 19:02:48 +0900164public final class OpenstackNetworkingUtil {
Jian Li091d8d22018-02-20 10:42:06 +0900165
Daniel Park95985382018-07-23 11:38:07 +0900166 private static final Logger log = LoggerFactory.getLogger(OpenstackNetworkingUtil.class);
Jian Li091d8d22018-02-20 10:42:06 +0900167
Daniel Parkc4d06402018-05-28 15:57:37 +0900168 private static final int HEX_RADIX = 16;
Jian Li51b844c2018-05-31 10:59:03 +0900169 private static final String ZERO_FUNCTION_NUMBER = "0";
Daniel Parkc4d06402018-05-28 15:57:37 +0900170 private static final String PREFIX_DEVICE_NUMBER = "s";
171 private static final String PREFIX_FUNCTION_NUMBER = "f";
172
Jian Li51b844c2018-05-31 10:59:03 +0900173 // keystone endpoint related variables
174 private static final String DOMAIN_DEFAULT = "default";
175 private static final String KEYSTONE_V2 = "v2.0";
176 private static final String KEYSTONE_V3 = "v3";
Jian Li51b844c2018-05-31 10:59:03 +0900177 private static final String SSL_TYPE = "SSL";
178
Jian Li7f024de2018-07-07 03:51:02 +0900179 private static final String PROXY_MODE = "proxy";
180 private static final String BROADCAST_MODE = "broadcast";
181
Jian Licad36c72018-09-13 17:44:54 +0900182 private static final String ENABLE = "enable";
183 private static final String DISABLE = "disable";
184
Jian Li63430202018-08-30 16:24:09 +0900185 private static final int HTTP_PAYLOAD_BUFFER = 8 * 1024;
186
187 private static final String HMAC_SHA256 = "HmacSHA256";
188
Jian Li24ec59f2018-05-23 19:01:25 +0900189 private static final String ERR_FLOW = "Failed set flows for floating IP %s: ";
190
Daniel Parka73c2362018-09-17 17:43:25 +0900191 private static final String DL_DST = "dl_dst=";
192 private static final String NW_DST = "nw_dst=";
193 private static final String DEFAULT_REQUEST_STRING = "sudo ovs-appctl ofproto/trace br-int ip";
194 private static final String IN_PORT = "in_port=";
195 private static final String NW_SRC = "nw_src=";
196 private static final String COMMA = ",";
197 private static final String TUN_ID = "tun_id=";
198
Jian Li40f032a2019-10-02 20:36:09 +0900199 private static final String DEVICE_OWNER_GW = "network:router_gateway";
200 private static final String DEVICE_OWNER_IFACE = "network:router_interface";
201
202 private static final String NOT_AVAILABLE = "N/A";
203
Daniel Parka73c2362018-09-17 17:43:25 +0900204 private static final long TIMEOUT_MS = 5000;
205 private static final long WAIT_OUTPUT_STREAM_SECOND = 2;
206 private static final int SSH_PORT = 22;
207
Jian Li51728702019-05-17 18:38:56 +0900208 private static final int TAP_PORT_LENGTH = 11;
Jian Lia271b3c2019-09-03 23:10:20 +0900209 private static final int PORT_NAME_MAX_LENGTH = 15;
Jian Li51728702019-05-17 18:38:56 +0900210
Jian Li091d8d22018-02-20 10:42:06 +0900211 /**
212 * Prevents object instantiation from external.
213 */
Jian Lidea0fdb2018-04-02 19:02:48 +0900214 private OpenstackNetworkingUtil() {
Jian Li091d8d22018-02-20 10:42:06 +0900215 }
216
217 /**
218 * Interprets JSON string to corresponding openstack model entity object.
219 *
Jian Li7b8c3682019-05-12 13:57:15 +0900220 * @param inputStr JSON string
Jian Li091d8d22018-02-20 10:42:06 +0900221 * @param entityClazz openstack model entity class
222 * @return openstack model entity object
223 */
Jian Li7b8c3682019-05-12 13:57:15 +0900224 public static ModelEntity jsonToModelEntity(String inputStr, Class entityClazz) {
Jian Li091d8d22018-02-20 10:42:06 +0900225 ObjectMapper mapper = new ObjectMapper();
226 try {
Jian Li7b8c3682019-05-12 13:57:15 +0900227 InputStream input = toInputStream(inputStr, REST_UTF8);
Jian Li091d8d22018-02-20 10:42:06 +0900228 JsonNode jsonTree = mapper.enable(INDENT_OUTPUT).readTree(input);
229 log.trace(new ObjectMapper().writeValueAsString(jsonTree));
230 return ObjectMapperSingleton.getContext(entityClazz)
231 .readerFor(entityClazz)
232 .readValue(jsonTree);
233 } catch (Exception e) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900234 log.error("Exception occurred because of {}", e);
Jian Li091d8d22018-02-20 10:42:06 +0900235 throw new IllegalArgumentException();
236 }
237 }
Jian Lieb9f77d2018-02-20 11:25:45 +0900238
239 /**
240 * Converts openstack model entity object into JSON object.
241 *
242 * @param entity openstack model entity object
243 * @param entityClazz openstack model entity class
244 * @return JSON object
245 */
246 public static ObjectNode modelEntityToJson(ModelEntity entity, Class entityClazz) {
247 ObjectMapper mapper = new ObjectMapper();
248 try {
249 String strModelEntity = ObjectMapperSingleton.getContext(entityClazz)
250 .writerFor(entityClazz)
251 .writeValueAsString(entity);
252 log.trace(strModelEntity);
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900253 return (ObjectNode) mapper.readTree(strModelEntity.getBytes(Charsets.UTF_8));
Daniel Park95985382018-07-23 11:38:07 +0900254 } catch (IOException e) {
255 log.error("IOException occurred because of {}", e.toString());
Jian Lieb9f77d2018-02-20 11:25:45 +0900256 throw new IllegalStateException();
257 }
258 }
Jian Li1064e4f2018-05-29 16:16:53 +0900259
260 /**
Jian Li24ec59f2018-05-23 19:01:25 +0900261 * Obtains a floating IP associated with the given instance port.
262 *
263 * @param port instance port
264 * @param fips a collection of floating IPs
265 * @return associated floating IP
266 */
267 public static NetFloatingIP associatedFloatingIp(InstancePort port,
268 Set<NetFloatingIP> fips) {
Daniel Park2ff66b42018-08-01 11:52:45 +0900269 for (NetFloatingIP fip : fips) {
270 if (Strings.isNullOrEmpty(fip.getFixedIpAddress())) {
271 continue;
Jian Li24ec59f2018-05-23 19:01:25 +0900272 }
Daniel Park2ff66b42018-08-01 11:52:45 +0900273 if (Strings.isNullOrEmpty(fip.getFloatingIpAddress())) {
274 continue;
275 }
Jian Li6bc29d92018-10-02 13:55:05 +0900276 if (fip.getFixedIpAddress().equals(port.ipAddress().toString()) &&
277 fip.getPortId().equals(port.portId())) {
Daniel Park2ff66b42018-08-01 11:52:45 +0900278 return fip;
279 }
Jian Li24ec59f2018-05-23 19:01:25 +0900280 }
Daniel Park2ff66b42018-08-01 11:52:45 +0900281
Jian Li24ec59f2018-05-23 19:01:25 +0900282 return null;
283 }
284
285 /**
286 * Checks whether the given floating IP is associated with a VM.
287 *
288 * @param service openstack network service
289 * @param fip floating IP
290 * @return true if the given floating IP associated with a VM, false otherwise
291 */
292 public static boolean isAssociatedWithVM(OpenstackNetworkService service,
293 NetFloatingIP fip) {
294 Port osPort = service.port(fip.getPortId());
295 if (osPort == null) {
296 return false;
297 }
298
299 if (!Strings.isNullOrEmpty(osPort.getDeviceId())) {
300 Network osNet = service.network(osPort.getNetworkId());
301 if (osNet == null) {
302 final String errorFormat = ERR_FLOW + "no network(%s) exists";
303 final String error = String.format(errorFormat,
304 fip.getFloatingIpAddress(), osPort.getNetworkId());
305 throw new IllegalStateException(error);
306 }
307 return true;
308 } else {
309 return false;
310 }
311 }
312
313 /**
Jian Lia171a432018-06-11 11:52:11 +0900314 * Obtains the gateway node by instance port.
315 *
316 * @param gateways a collection of gateway nodes
317 * @param instPort instance port
318 * @return a gateway node
319 */
320 public static OpenstackNode getGwByInstancePort(Set<OpenstackNode> gateways,
321 InstancePort instPort) {
322 OpenstackNode gw = null;
323 if (instPort != null && instPort.deviceId() != null) {
324 gw = getGwByComputeDevId(gateways, instPort.deviceId());
325 }
326 return gw;
327 }
328
329 /**
Jian Li1064e4f2018-05-29 16:16:53 +0900330 * Obtains the gateway node by device in compute node. Note that the gateway
331 * node is determined by device's device identifier.
332 *
333 * @param gws a collection of gateway nodes
334 * @param deviceId device identifier
335 * @return a gateway node
336 */
Jian Li5ecfd1a2018-12-10 11:41:03 +0900337 public static OpenstackNode getGwByComputeDevId(Set<OpenstackNode> gws,
338 DeviceId deviceId) {
Jian Li1064e4f2018-05-29 16:16:53 +0900339 int numOfGw = gws.size();
340
341 if (numOfGw == 0) {
342 return null;
343 }
344
345 int gwIndex = Math.abs(deviceId.hashCode()) % numOfGw;
346
347 return getGwByIndex(gws, gwIndex);
348 }
349
Jian Li51b844c2018-05-31 10:59:03 +0900350 /**
351 * Obtains a connected openstack client.
352 *
353 * @param osNode openstack node
354 * @return a connected openstack client
355 */
356 public static OSClient getConnectedClient(OpenstackNode osNode) {
Jian Lic704b672018-09-04 18:52:53 +0900357 OpenstackAuth auth = osNode.keystoneConfig().authentication();
Jian Li51b844c2018-05-31 10:59:03 +0900358 String endpoint = buildEndpoint(osNode);
359 Perspective perspective = auth.perspective();
Jian Li1064e4f2018-05-29 16:16:53 +0900360
Jian Li51b844c2018-05-31 10:59:03 +0900361 Config config = getSslConfig();
Jian Li1064e4f2018-05-29 16:16:53 +0900362
Jian Li51b844c2018-05-31 10:59:03 +0900363 try {
364 if (endpoint.contains(KEYSTONE_V2)) {
365 IOSClientBuilder.V2 builder = OSFactory.builderV2()
366 .endpoint(endpoint)
367 .tenantName(auth.project())
368 .credentials(auth.username(), auth.password())
369 .withConfig(config);
370
371 if (perspective != null) {
372 builder.perspective(getFacing(perspective));
373 }
374
375 return builder.authenticate();
376 } else if (endpoint.contains(KEYSTONE_V3)) {
377
378 Identifier project = Identifier.byName(auth.project());
379 Identifier domain = Identifier.byName(DOMAIN_DEFAULT);
380
381 IOSClientBuilder.V3 builder = OSFactory.builderV3()
382 .endpoint(endpoint)
383 .credentials(auth.username(), auth.password(), domain)
384 .scopeToProject(project, domain)
385 .withConfig(config);
386
387 if (perspective != null) {
388 builder.perspective(getFacing(perspective));
389 }
390
391 return builder.authenticate();
392 } else {
393 log.warn("Unrecognized keystone version type");
394 return null;
Jian Li1064e4f2018-05-29 16:16:53 +0900395 }
Jian Li51b844c2018-05-31 10:59:03 +0900396 } catch (AuthenticationException e) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900397 log.error("Authentication failed due to {}", e);
Jian Li51b844c2018-05-31 10:59:03 +0900398 return null;
Jian Li1064e4f2018-05-29 16:16:53 +0900399 }
Jian Li1064e4f2018-05-29 16:16:53 +0900400 }
Daniel Parkc4d06402018-05-28 15:57:37 +0900401
402 /**
Jian Licda74c82019-10-31 22:24:17 +0900403 * Checks whether the given openstack port is smart NIC capable.
404 *
405 * @param port openstack port
406 * @return true if the given port is smart NIC capable, false otherwise
407 */
408 public static boolean isSmartNicCapable(Port port) {
409 if (port.getProfile() != null && port.getvNicType().equals(DIRECT)) {
410 String vendorInfo = String.valueOf(port.getProfile().get(PCI_VENDOR_INFO));
411 if (portNamePrefixMap().containsKey(vendorInfo)) {
412 log.debug("Port {} is a Smart NIC capable port.", port.getId());
413 return true;
414 }
415 return false;
416 }
417 return false;
418 }
419
420 /**
Daniel Parkc4d06402018-05-28 15:57:37 +0900421 * Extract the interface name with the supplied port.
422 *
423 * @param port port
424 * @return interface name
425 */
426 public static String getIntfNameFromPciAddress(Port port) {
Daniel Parkff178ba2018-11-23 15:57:24 +0900427 String intfName;
428
Daniel Park95985382018-07-23 11:38:07 +0900429 if (port.getProfile() == null || port.getProfile().isEmpty()) {
Jian Li51b844c2018-05-31 10:59:03 +0900430 log.error("Port profile is not found");
431 return null;
432 }
433
Daniel Park95985382018-07-23 11:38:07 +0900434 if (!port.getProfile().containsKey(PCISLOT) ||
435 Strings.isNullOrEmpty(port.getProfile().get(PCISLOT).toString())) {
Jian Li5ecfd1a2018-12-10 11:41:03 +0900436 log.error("Failed to retrieve the interface name because of no " +
437 "pci_slot information from the port");
Daniel Parkc4d06402018-05-28 15:57:37 +0900438 return null;
439 }
Jian Li51b844c2018-05-31 10:59:03 +0900440
Daniel Parkff178ba2018-11-23 15:57:24 +0900441 String vendorInfoForPort = String.valueOf(port.getProfile().get(PCI_VENDOR_INFO));
442
443 if (!portNamePrefixMap().containsKey(vendorInfoForPort)) {
444 log.debug("{} is an non-smart NIC prefix.", vendorInfoForPort);
445 return UNSUPPORTED_VENDOR;
446 }
447
448 String portNamePrefix = portNamePrefixMap().get(vendorInfoForPort);
449
Daniel Parkc4d06402018-05-28 15:57:37 +0900450 String busNumHex = port.getProfile().get(PCISLOT).toString().split(":")[1];
451 String busNumDecimal = String.valueOf(Integer.parseInt(busNumHex, HEX_RADIX));
452
453 String deviceNumHex = port.getProfile().get(PCISLOT).toString()
454 .split(":")[2]
455 .split("\\.")[0];
456 String deviceNumDecimal = String.valueOf(Integer.parseInt(deviceNumHex, HEX_RADIX));
457
458 String functionNumHex = port.getProfile().get(PCISLOT).toString()
459 .split(":")[2]
460 .split("\\.")[1];
461 String functionNumDecimal = String.valueOf(Integer.parseInt(functionNumHex, HEX_RADIX));
462
Daniel Parkc4d06402018-05-28 15:57:37 +0900463 if (functionNumDecimal.equals(ZERO_FUNCTION_NUMBER)) {
464 intfName = portNamePrefix + busNumDecimal + PREFIX_DEVICE_NUMBER + deviceNumDecimal;
465 } else {
466 intfName = portNamePrefix + busNumDecimal + PREFIX_DEVICE_NUMBER + deviceNumDecimal
467 + PREFIX_FUNCTION_NUMBER + functionNumDecimal;
468 }
469
470 return intfName;
471 }
Jian Li51b844c2018-05-31 10:59:03 +0900472
473 /**
Daniel Park95f73312018-07-31 15:48:34 +0900474 * Check if the given interface is added to the given device or not.
475 *
476 * @param deviceId device ID
477 * @param intfName interface name
478 * @param deviceService device service
479 * @return true if the given interface is added to the given device or false otherwise
480 */
Jian Li5ecfd1a2018-12-10 11:41:03 +0900481 public static boolean hasIntfAleadyInDevice(DeviceId deviceId,
482 String intfName,
483 DeviceService deviceService) {
Daniel Park95f73312018-07-31 15:48:34 +0900484 checkNotNull(deviceId);
485 checkNotNull(intfName);
486
Jian Li5ecfd1a2018-12-10 11:41:03 +0900487 return deviceService.getPorts(deviceId).stream().anyMatch(port ->
488 Objects.equals(port.annotations().value(PORT_NAME), intfName));
Daniel Park95f73312018-07-31 15:48:34 +0900489 }
490
491 /**
Jian Li0b564282018-06-20 00:50:53 +0900492 * Adds router interfaces to openstack admin service.
Jian Li0b564282018-06-20 00:50:53 +0900493 *
494 * @param osPort port
495 * @param adminService openstack admin service
496 */
Jian Li5ecfd1a2018-12-10 11:41:03 +0900497 public static void addRouterIface(Port osPort,
498 OpenstackRouterAdminService adminService) {
Jian Li0b564282018-06-20 00:50:53 +0900499 osPort.getFixedIps().forEach(p -> {
500 JsonNode jsonTree = new ObjectMapper().createObjectNode()
501 .put("id", osPort.getDeviceId())
502 .put("tenant_id", osPort.getTenantId())
503 .put("subnet_id", p.getSubnetId())
504 .put("port_id", osPort.getId());
505 try {
506 RouterInterface rIface = getContext(NeutronRouterInterface.class)
507 .readerFor(NeutronRouterInterface.class)
508 .readValue(jsonTree);
509 if (adminService.routerInterface(rIface.getPortId()) != null) {
510 adminService.updateRouterInterface(rIface);
511 } else {
512 adminService.addRouterInterface(rIface);
513 }
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900514 } catch (IOException e) {
515 log.error("IOException occurred because of {}", e);
Jian Li0b564282018-06-20 00:50:53 +0900516 }
517 });
518 }
519
520 /**
Jian Li40f032a2019-10-02 20:36:09 +0900521 * Prints openstack security group.
522 *
523 * @param osSg openstack security group
524 */
525 public static void printSecurityGroup(SecurityGroup osSg) {
526 print(SECURITY_GROUP_FORMAT, osSg.getId(), osSg.getName());
527 }
528
529 /**
530 * Prints openstack network.
531 *
532 * @param osNet openstack network
533 */
534 public static void printNetwork(Network osNet) {
535 final String strNet = String.format(NETWORK_FORMAT,
536 osNet.getId(),
537 osNet.getName(),
538 osNet.getProviderSegID(),
539 osNet.getSubnets());
540 print(strNet);
541 }
542
543 /**
544 * Prints openstack subnet.
545 *
546 * @param osSubnet openstack subnet
547 * @param osNetService openstack network service
548 */
549 public static void printSubnet(Subnet osSubnet,
550 OpenstackNetworkService osNetService) {
551 final Network network = osNetService.network(osSubnet.getNetworkId());
552 final String netName = network == null ? NOT_AVAILABLE : network.getName();
553 final String strSubnet = String.format(SUBNET_FORMAT,
554 osSubnet.getId(),
555 netName,
556 osSubnet.getCidr());
557 print(strSubnet);
558 }
559
560 /**
561 * Prints openstack port.
562 *
563 * @param osPort openstack port
564 * @param osNetService openstack network service
565 */
566 public static void printPort(Port osPort,
567 OpenstackNetworkService osNetService) {
568 List<String> fixedIps = osPort.getFixedIps().stream()
569 .map(IP::getIpAddress)
570 .collect(Collectors.toList());
571 final Network network = osNetService.network(osPort.getNetworkId());
572 final String netName = network == null ? NOT_AVAILABLE : network.getName();
573 final String strPort = String.format(PORT_FORMAT,
574 osPort.getId(),
575 netName,
576 osPort.getMacAddress(),
577 fixedIps.isEmpty() ? "" : fixedIps);
578 print(strPort);
579 }
580
581 /**
582 * Prints openstack router.
583 *
584 * @param osRouter openstack router
585 * @param osNetService openstack network service
586 */
587 public static void printRouter(Router osRouter,
588 OpenstackNetworkService osNetService) {
589 List<String> externals = osNetService.ports().stream()
590 .filter(osPort -> Objects.equals(osPort.getDeviceId(), osRouter.getId()) &&
591 Objects.equals(osPort.getDeviceOwner(), DEVICE_OWNER_GW))
592 .flatMap(osPort -> osPort.getFixedIps().stream())
593 .map(IP::getIpAddress)
594 .collect(Collectors.toList());
595
596 List<String> internals = osNetService.ports().stream()
597 .filter(osPort -> Objects.equals(osPort.getDeviceId(), osRouter.getId()) &&
598 Objects.equals(osPort.getDeviceOwner(), DEVICE_OWNER_IFACE))
599 .flatMap(osPort -> osPort.getFixedIps().stream())
600 .map(IP::getIpAddress)
601 .collect(Collectors.toList());
602
603 final String strRouter = String.format(ROUTER_FORMAT,
604 osRouter.getId(),
605 osRouter.getName(),
606 externals.isEmpty() ? "" : externals,
607 internals.isEmpty() ? "" : internals);
608 print(strRouter);
609 }
610
611 /**
612 * Prints openstack router interface.
613 *
614 * @param osRouterIntf openstack router interface
615 */
616 public static void printRouterIntf(RouterInterface osRouterIntf) {
617 final String strRouterIntf = String.format(ROUTER_INTF_FORMAT,
618 osRouterIntf.getId(),
619 osRouterIntf.getTenantId(),
620 osRouterIntf.getSubnetId());
621 print(strRouterIntf);
622 }
623
624 /**
625 * Prints openstack floating IP.
626 *
627 * @param floatingIp floating IP
628 */
629 public static void printFloatingIp(NetFloatingIP floatingIp) {
630 final String strFloating = String.format(FLOATING_IP_FORMAT,
631 floatingIp.getId(),
632 floatingIp.getFloatingIpAddress(),
633 Strings.isNullOrEmpty(floatingIp.getFixedIpAddress()) ?
634 "" : floatingIp.getFixedIpAddress());
635 print(strFloating);
636 }
637
638 /**
Jian Li7f70bb72018-07-06 23:35:30 +0900639 * Obtains the property value with specified property key name.
640 *
641 * @param properties a collection of properties
642 * @param name key name
643 * @return mapping value
644 */
Jian Li5ecfd1a2018-12-10 11:41:03 +0900645 public static String getPropertyValue(Set<ConfigProperty> properties,
646 String name) {
Jian Li7f70bb72018-07-06 23:35:30 +0900647 Optional<ConfigProperty> property =
648 properties.stream().filter(p -> p.name().equals(name)).findFirst();
649 return property.map(ConfigProperty::value).orElse(null);
650 }
651
652 /**
Jian Li9d35bd62018-10-13 01:43:24 +0900653 * Obtains the boolean property value with specified property key name.
654 *
655 * @param properties a collection of properties
656 * @param name key name
657 * @return mapping value
658 */
Jian Li5ecfd1a2018-12-10 11:41:03 +0900659 public static boolean getPropertyValueAsBoolean(Set<ConfigProperty> properties,
660 String name) {
Jian Li9d35bd62018-10-13 01:43:24 +0900661 Optional<ConfigProperty> property =
662 properties.stream().filter(p -> p.name().equals(name)).findFirst();
663
664 return property.map(ConfigProperty::asBoolean).orElse(false);
665 }
666
667 /**
Jian Lif1efbe52018-07-17 23:20:16 +0900668 * Prints out the JSON string in pretty format.
669 *
670 * @param mapper Object mapper
671 * @param jsonString JSON string
672 * @return pretty formatted JSON string
673 */
674 public static String prettyJson(ObjectMapper mapper, String jsonString) {
675 try {
676 Object jsonObject = mapper.readValue(jsonString, Object.class);
677 return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
Daniel Park2ff66b42018-08-01 11:52:45 +0900678 } catch (JsonParseException e) {
679 log.debug("JsonParseException caused by {}", e);
680 } catch (JsonMappingException e) {
681 log.debug("JsonMappingException caused by {}", e);
682 } catch (JsonProcessingException e) {
683 log.debug("JsonProcessingException caused by {}", e);
Jian Lif1efbe52018-07-17 23:20:16 +0900684 }
685 return null;
686 }
687
688 /**
Jian Li7f024de2018-07-07 03:51:02 +0900689 * Checks the validity of ARP mode.
690 *
691 * @param arpMode ARP mode
692 * @return returns true if the ARP mode is valid, false otherwise
693 */
694 public static boolean checkArpMode(String arpMode) {
695
696 if (isNullOrEmpty(arpMode)) {
697 return false;
698 } else {
699 return arpMode.equals(PROXY_MODE) || arpMode.equals(BROADCAST_MODE);
700 }
701 }
702
703 /**
Jian Licad36c72018-09-13 17:44:54 +0900704 * Checks the validity of activation flag.
705 *
706 * @param activationFlag activation flag
707 * @return returns true if the activation flag is valid, false otherwise
708 */
709 public static boolean checkActivationFlag(String activationFlag) {
710
711 switch (activationFlag) {
712 case ENABLE:
713 return true;
714 case DISABLE:
715 return false;
716 default:
717 throw new IllegalArgumentException("The given activation flag is not valid!");
718 }
719 }
720
721 /**
Jian Liec5c32b2018-07-13 14:28:58 +0900722 * Swaps current location with old location info.
723 * The revised instance port will be used to mod the flow rules after migration.
724 *
725 * @param instPort instance port
726 * @return location swapped instance port
727 */
728 public static InstancePort swapStaleLocation(InstancePort instPort) {
729 return DefaultInstancePort.builder()
730 .deviceId(instPort.oldDeviceId())
731 .portNumber(instPort.oldPortNumber())
732 .state(instPort.state())
733 .ipAddress(instPort.ipAddress())
734 .macAddress(instPort.macAddress())
735 .networkId(instPort.networkId())
736 .portId(instPort.portId())
737 .build();
738 }
739
740 /**
Daniel Park2ff66b42018-08-01 11:52:45 +0900741 * Compares two router interfaces are equal.
742 * Will be remove this after Openstack4j implements equals.
743 *
744 * @param routerInterface1 router interface
745 * @param routerInterface2 router interface
746 * @return returns true if two router interfaces are equal, false otherwise
747 */
Jian Li63430202018-08-30 16:24:09 +0900748 public static boolean routerInterfacesEquals(RouterInterface routerInterface1,
749 RouterInterface routerInterface2) {
Daniel Park2ff66b42018-08-01 11:52:45 +0900750 return Objects.equals(routerInterface1.getId(), routerInterface2.getId()) &&
751 Objects.equals(routerInterface1.getPortId(), routerInterface2.getPortId()) &&
752 Objects.equals(routerInterface1.getSubnetId(), routerInterface2.getSubnetId()) &&
753 Objects.equals(routerInterface1.getTenantId(), routerInterface2.getTenantId());
754 }
755
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900756 /**
757 * Returns the vnic type of given port.
758 *
759 * @param portName port name
760 * @return vnit type
761 */
Daniel Park7e8c4d82018-08-13 23:47:49 +0900762 public static VnicType vnicType(String portName) {
763 if (portName.startsWith(PORT_NAME_PREFIX_VM) ||
764 portName.startsWith(PORT_NAME_VHOST_USER_PREFIX_VM)) {
765 return VnicType.NORMAL;
766 } else if (isDirectPort(portName)) {
767 return VnicType.DIRECT;
768 } else {
769 return VnicType.UNSUPPORTED;
770 }
771 }
772
Jian Li63430202018-08-30 16:24:09 +0900773 /**
774 * Deserializes raw payload into HttpRequest object.
775 *
776 * @param rawData raw http payload
777 * @return HttpRequest object
778 */
779 public static HttpRequest parseHttpRequest(byte[] rawData) {
780 SessionInputBufferImpl sessionInputBuffer =
781 new SessionInputBufferImpl(
782 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
783 sessionInputBuffer.bind(new ByteArrayInputStream(rawData));
Jian Li5ecfd1a2018-12-10 11:41:03 +0900784 DefaultHttpRequestParser requestParser =
785 new DefaultHttpRequestParser(sessionInputBuffer);
Jian Li63430202018-08-30 16:24:09 +0900786 try {
787 return requestParser.parse();
788 } catch (IOException | HttpException e) {
789 log.warn("Failed to parse HttpRequest, due to {}", e);
790 }
791
792 return null;
793 }
794
795 /**
796 * Serializes HttpRequest object to byte array.
797 *
798 * @param request http request object
799 * @return byte array
800 */
801 public static byte[] unparseHttpRequest(HttpRequest request) {
802 try {
803 SessionOutputBufferImpl sessionOutputBuffer =
804 new SessionOutputBufferImpl(
805 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
806
807 ByteArrayOutputStream baos = new ByteArrayOutputStream();
808 sessionOutputBuffer.bind(baos);
809
Jian Li5ecfd1a2018-12-10 11:41:03 +0900810 HttpMessageWriter<HttpRequest> requestWriter =
811 new DefaultHttpRequestWriter(sessionOutputBuffer);
Jian Li63430202018-08-30 16:24:09 +0900812 requestWriter.write(request);
813 sessionOutputBuffer.flush();
814
815 return baos.toByteArray();
816 } catch (HttpException | IOException e) {
817 log.warn("Failed to unparse HttpRequest, due to {}", e);
818 }
819
820 return null;
821 }
822
823 /**
824 * Deserializes raw payload into HttpResponse object.
825 *
826 * @param rawData raw http payload
827 * @return HttpResponse object
828 */
829 public static HttpResponse parseHttpResponse(byte[] rawData) {
830 SessionInputBufferImpl sessionInputBuffer =
831 new SessionInputBufferImpl(
832 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
833 sessionInputBuffer.bind(new ByteArrayInputStream(rawData));
Jian Li5ecfd1a2018-12-10 11:41:03 +0900834 DefaultHttpResponseParser responseParser =
835 new DefaultHttpResponseParser(sessionInputBuffer);
Jian Li63430202018-08-30 16:24:09 +0900836 try {
837 return responseParser.parse();
838 } catch (IOException | HttpException e) {
839 log.warn("Failed to parse HttpResponse, due to {}", e);
840 }
841
842 return null;
843 }
844
845 /**
846 * Serializes HttpResponse header to byte array.
847 *
848 * @param response http response object
849 * @return byte array
850 */
851 public static byte[] unparseHttpResponseHeader(HttpResponse response) {
852 try {
853 SessionOutputBufferImpl sessionOutputBuffer =
854 new SessionOutputBufferImpl(
855 new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER);
856
857 ByteArrayOutputStream headerBaos = new ByteArrayOutputStream();
858 sessionOutputBuffer.bind(headerBaos);
859
860 HttpMessageWriter<HttpResponse> responseWriter =
861 new DefaultHttpResponseWriter(sessionOutputBuffer);
862 responseWriter.write(response);
863 sessionOutputBuffer.flush();
864
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900865 log.debug(headerBaos.toString(Charsets.UTF_8.name()));
Jian Li63430202018-08-30 16:24:09 +0900866
867 return headerBaos.toByteArray();
868 } catch (IOException | HttpException e) {
869 log.warn("Failed to unparse HttpResponse headers, due to {}", e);
870 }
871
872 return null;
873 }
874
875 /**
876 * Serializes HttpResponse object to byte array.
877 *
878 * @param response http response object
879 * @return byte array
880 */
881 public static byte[] unparseHttpResponseBody(HttpResponse response) {
882 try {
883 ByteArrayOutputStream baos = new ByteArrayOutputStream();
884 response.getEntity().writeTo(baos);
885
886 log.debug(response.toString());
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900887 log.debug(baos.toString(Charsets.UTF_8.name()));
Jian Li63430202018-08-30 16:24:09 +0900888
889 return baos.toByteArray();
890 } catch (IOException e) {
891 log.warn("Failed to unparse HttpResponse, due to {}", e);
892 }
893
894 return null;
895 }
896
897 /**
898 * Encodes the given data using HmacSHA256 encryption method with given secret key.
899 *
900 * @param key secret key
901 * @param data data to be encrypted
902 * @return Hmac256 encrypted data
903 */
904 public static String hmacEncrypt(String key, String data) {
905 try {
906 Mac sha256Hmac = Mac.getInstance(HMAC_SHA256);
907 SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), HMAC_SHA256);
908 sha256Hmac.init(secretKey);
909 return Hex.encodeHexString(sha256Hmac.doFinal(data.getBytes("UTF-8")));
910 } catch (Exception e) {
911 log.warn("Failed to encrypt data {} using key {}, due to {}", data, key, e);
912 }
913 return null;
914 }
915
Daniel Parka73c2362018-09-17 17:43:25 +0900916 /**
917 * Creates flow trace request string.
918 *
919 * @param srcIp src ip address
920 * @param dstIp dst ip address
921 * @param srcInstancePort src instance port
922 * @param osNetService openstack networking service
Daniel Park5aef9822018-09-20 18:04:18 +0900923 * @param uplink true if this request is for uplink
Daniel Parka73c2362018-09-17 17:43:25 +0900924 * @return flow trace request string
925 */
926 public static String traceRequestString(String srcIp,
927 String dstIp,
928 InstancePort srcInstancePort,
Jian Li5ecfd1a2018-12-10 11:41:03 +0900929 OpenstackNetworkService osNetService,
930 boolean uplink) {
Daniel Parka73c2362018-09-17 17:43:25 +0900931
932 StringBuilder requestStringBuilder = new StringBuilder(DEFAULT_REQUEST_STRING);
933
934 if (uplink) {
935
936 requestStringBuilder.append(COMMA)
937 .append(IN_PORT)
938 .append(srcInstancePort.portNumber().toString())
939 .append(COMMA)
940 .append(NW_SRC)
941 .append(srcIp)
942 .append(COMMA);
943
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900944 String modifiedDstIp = dstIp;
Jian Li621f73c2018-12-15 01:49:22 +0900945 Type netType = osNetService.networkType(srcInstancePort.networkId());
946 if (netType == Type.VXLAN || netType == Type.GRE ||
947 netType == Type.VLAN || netType == Type.GENEVE) {
Daniel Parka73c2362018-09-17 17:43:25 +0900948 if (srcIp.equals(dstIp)) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900949 modifiedDstIp = osNetService.gatewayIp(srcInstancePort.portId());
Daniel Parka73c2362018-09-17 17:43:25 +0900950 requestStringBuilder.append(DL_DST)
951 .append(DEFAULT_GATEWAY_MAC_STR).append(COMMA);
Jian Li5ecfd1a2018-12-10 11:41:03 +0900952 } else if (!osNetService.ipPrefix(srcInstancePort.portId()).contains(
953 IpAddress.valueOf(dstIp))) {
Daniel Parka73c2362018-09-17 17:43:25 +0900954 requestStringBuilder.append(DL_DST)
955 .append(DEFAULT_GATEWAY_MAC_STR)
956 .append(COMMA);
957 }
958 } else {
959 if (srcIp.equals(dstIp)) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900960 modifiedDstIp = osNetService.gatewayIp(srcInstancePort.portId());
Daniel Parka73c2362018-09-17 17:43:25 +0900961 }
962 }
963
964 requestStringBuilder.append(NW_DST)
Daniel Parka3ffbdb2018-11-28 13:51:39 +0900965 .append(modifiedDstIp)
Daniel Parka73c2362018-09-17 17:43:25 +0900966 .append("\n");
967 } else {
968 requestStringBuilder.append(COMMA)
969 .append(NW_SRC)
970 .append(dstIp)
971 .append(COMMA);
972
Jian Li621f73c2018-12-15 01:49:22 +0900973 Type netType = osNetService.networkType(srcInstancePort.networkId());
974
975 if (netType == Type.VXLAN || netType == Type.GRE ||
976 netType == Type.VLAN || netType == Type.GENEVE) {
Daniel Parka73c2362018-09-17 17:43:25 +0900977 requestStringBuilder.append(TUN_ID)
978 .append(osNetService.segmentId(srcInstancePort.networkId()))
979 .append(COMMA);
980 }
981 requestStringBuilder.append(NW_DST)
982 .append(srcIp)
983 .append("\n");
Daniel Parka73c2362018-09-17 17:43:25 +0900984 }
985
986 return requestStringBuilder.toString();
987 }
988
989 /**
990 * Sends flow trace string to node.
991 *
992 * @param requestString reqeust string
993 * @param node src node
994 * @return flow trace result in string format
995 */
996 public static String sendTraceRequestToNode(String requestString,
997 OpenstackNode node) {
998 String traceResult = null;
999 OpenstackSshAuth sshAuth = node.sshAuthInfo();
1000
1001 try (SshClient client = SshClient.setUpDefaultClient()) {
1002 client.start();
1003
1004 try (ClientSession session = client
1005 .connect(sshAuth.id(), node.managementIp().getIp4Address().toString(), SSH_PORT)
1006 .verify(TIMEOUT_MS, TimeUnit.SECONDS).getSession()) {
1007 session.addPasswordIdentity(sshAuth.password());
1008 session.auth().verify(TIMEOUT_MS, TimeUnit.SECONDS);
1009
1010
1011 try (ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) {
1012
1013 log.debug("requestString: {}", requestString);
1014 final InputStream inputStream =
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001015 new ByteArrayInputStream(requestString.getBytes(Charsets.UTF_8));
Daniel Parka73c2362018-09-17 17:43:25 +09001016
Jian Li5ecfd1a2018-12-10 11:41:03 +09001017 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Daniel Parka73c2362018-09-17 17:43:25 +09001018 OutputStream errStream = new ByteArrayOutputStream();
1019
1020 channel.setIn(new NoCloseInputStream(inputStream));
1021 channel.setErr(errStream);
1022 channel.setOut(outputStream);
1023
1024 Collection<ClientChannelEvent> eventList = Lists.newArrayList();
1025 eventList.add(ClientChannelEvent.OPENED);
1026
1027 OpenFuture channelFuture = channel.open();
1028
1029 if (channelFuture.await(TIMEOUT_MS, TimeUnit.SECONDS)) {
1030
1031 long timeoutExpiredMs = System.currentTimeMillis() + TIMEOUT_MS;
1032
1033 while (!channelFuture.isOpened()) {
1034 if ((timeoutExpiredMs - System.currentTimeMillis()) <= 0) {
1035 log.error("Failed to open channel");
1036 return null;
1037 }
1038 }
1039 TimeUnit.SECONDS.sleep(WAIT_OUTPUT_STREAM_SECOND);
1040
Jian Li5ecfd1a2018-12-10 11:41:03 +09001041 traceResult = outputStream.toString(Charsets.UTF_8.name());
Daniel Parka73c2362018-09-17 17:43:25 +09001042
1043 channel.close();
1044 }
1045 } finally {
1046 session.close();
1047 }
1048 } finally {
1049 client.stop();
1050 }
1051
1052 } catch (Exception e) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001053 log.error("Exception occurred because of {}", e);
Daniel Parka73c2362018-09-17 17:43:25 +09001054 }
1055
1056 return traceResult;
1057 }
1058
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001059 /**
1060 * Returns the floating ip with supplied instance port.
1061 *
1062 * @param instancePort instance port
1063 * @param osRouterAdminService openstack router admin service
1064 * @return floating ip
1065 */
1066 public static NetFloatingIP floatingIpByInstancePort(InstancePort instancePort,
Jian Li5ecfd1a2018-12-10 11:41:03 +09001067 OpenstackRouterAdminService
1068 osRouterAdminService) {
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001069 return osRouterAdminService.floatingIps().stream()
1070 .filter(netFloatingIP -> netFloatingIP.getPortId() != null)
1071 .filter(netFloatingIP -> netFloatingIP.getPortId().equals(instancePort.portId()))
1072 .findAny().orElse(null);
1073 }
1074
1075 /**
1076 * Sends GARP packet with supplied floating ip information.
1077 *
1078 * @param floatingIP floating ip
1079 * @param instancePort instance port
1080 * @param vlanId vlain id
1081 * @param gatewayNode gateway node
1082 * @param packetService packet service
1083 */
Jian Li32b03622018-11-06 17:54:24 +09001084 public static void processGarpPacketForFloatingIp(NetFloatingIP floatingIP,
1085 InstancePort instancePort,
1086 VlanId vlanId,
1087 OpenstackNode gatewayNode,
1088 PacketService packetService) {
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001089 Ethernet ethernet = buildGratuitousArpPacket(floatingIP, instancePort, vlanId);
1090
1091 TrafficTreatment treatment = DefaultTrafficTreatment.builder()
1092 .setOutput(gatewayNode.uplinkPortNum()).build();
1093
1094 packetService.emit(new DefaultOutboundPacket(gatewayNode.intgBridge(), treatment,
1095 ByteBuffer.wrap(ethernet.serialize())));
1096 }
1097
1098 /**
1099 * Returns the external peer router with supplied network information.
1100 *
1101 * @param network network
1102 * @param osNetworkService openstack network service
1103 * @param osRouterAdminService openstack router admin service
1104 * @return external peer router
1105 */
1106 public static ExternalPeerRouter externalPeerRouterForNetwork(Network network,
Jian Li5ecfd1a2018-12-10 11:41:03 +09001107 OpenstackNetworkService
1108 osNetworkService,
1109 OpenstackRouterAdminService
1110 osRouterAdminService) {
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001111 if (network == null) {
1112 return null;
1113 }
1114
Jian Lie6e609f2019-05-14 17:45:54 +09001115 Subnet subnet = osNetworkService.subnets(network.getId())
1116 .stream().findAny().orElse(null);
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001117
1118 if (subnet == null) {
1119 return null;
1120 }
1121
1122 RouterInterface osRouterIface = osRouterAdminService.routerInterfaces().stream()
1123 .filter(i -> Objects.equals(i.getSubnetId(), subnet.getId()))
1124 .findAny().orElse(null);
1125 if (osRouterIface == null) {
1126 return null;
1127 }
1128
1129 Router osRouter = osRouterAdminService.router(osRouterIface.getId());
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001130 if (osRouter == null || osRouter.getExternalGatewayInfo() == null) {
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001131 return null;
1132 }
1133
1134 ExternalGateway exGatewayInfo = osRouter.getExternalGatewayInfo();
1135 return osNetworkService.externalPeerRouter(exGatewayInfo);
1136
1137 }
1138
Jian Liebde74d2018-11-14 00:18:57 +09001139 /**
1140 * Returns the external peer router with specified subnet information.
1141 *
1142 * @param subnet openstack subnet
1143 * @param osRouterService openstack router service
1144 * @param osNetworkService openstack network service
1145 * @return external peer router
1146 */
Jian Li5ecfd1a2018-12-10 11:41:03 +09001147 public static ExternalPeerRouter externalPeerRouterFromSubnet(Subnet subnet,
1148 OpenstackRouterService
1149 osRouterService,
1150 OpenstackNetworkService
1151 osNetworkService) {
Jian Liebde74d2018-11-14 00:18:57 +09001152 Router osRouter = getRouterFromSubnet(subnet, osRouterService);
1153 if (osRouter == null) {
1154 return null;
1155 }
1156 if (osRouter.getExternalGatewayInfo() == null) {
1157 // this router does not have external connectivity
1158 log.trace("router({}) has no external gateway",
1159 osRouter.getName());
1160 return null;
1161 }
1162
1163 return osNetworkService.externalPeerRouter(osRouter.getExternalGatewayInfo());
1164 }
1165
1166 /**
1167 * Returns the external ip address with specified router information.
1168 *
1169 * @param srcSubnet source subnet
1170 * @param osRouterService openstack router service
1171 * @param osNetworkService openstack network service
1172 * @return external ip address
1173 */
1174 public static IpAddress externalIpFromSubnet(Subnet srcSubnet,
Jian Li5ecfd1a2018-12-10 11:41:03 +09001175 OpenstackRouterService
1176 osRouterService,
1177 OpenstackNetworkService
1178 osNetworkService) {
Jian Liebde74d2018-11-14 00:18:57 +09001179
1180 Router osRouter = getRouterFromSubnet(srcSubnet, osRouterService);
1181
1182 if (osRouter.getExternalGatewayInfo() == null) {
1183 // this router does not have external connectivity
1184 log.trace("router({}) has no external gateway",
1185 osRouter.getName());
1186 return null;
1187 }
1188
1189 return getExternalIp(osRouter, osNetworkService);
1190 }
1191
1192 /**
1193 * Returns the external ip address with specified router information.
1194 *
1195 * @param router openstack router
1196 * @param osNetworkService openstack network service
1197 * @return external ip address
1198 */
Jian Li5ecfd1a2018-12-10 11:41:03 +09001199 public static IpAddress getExternalIp(Router router,
1200 OpenstackNetworkService osNetworkService) {
Jian Liebde74d2018-11-14 00:18:57 +09001201 if (router == null) {
1202 return null;
1203 }
1204
1205 ExternalGateway externalGateway = router.getExternalGatewayInfo();
1206 if (externalGateway == null || !externalGateway.isEnableSnat()) {
Jian Li5ecfd1a2018-12-10 11:41:03 +09001207 log.trace("Failed to get externalIp for router {} because " +
1208 "externalGateway is null or SNAT is disabled",
Jian Liebde74d2018-11-14 00:18:57 +09001209 router.getId());
1210 return null;
1211 }
1212
1213 // TODO fix openstack4j for ExternalGateway provides external fixed IP list
1214 Port exGatewayPort = osNetworkService.ports(externalGateway.getNetworkId())
1215 .stream()
1216 .filter(port -> Objects.equals(port.getDeviceId(), router.getId()))
1217 .findAny().orElse(null);
1218
1219 if (exGatewayPort == null) {
1220 return null;
1221 }
1222
1223 return IpAddress.valueOf(exGatewayPort.getFixedIps().stream()
1224 .findAny().get().getIpAddress());
1225 }
1226
Jian Li2d68c192018-12-13 15:52:59 +09001227 /**
1228 * Returns the tunnel port number with specified net ID and openstack node.
1229 *
1230 * @param netId network ID
1231 * @param netService network service
1232 * @param osNode openstack node
1233 * @return tunnel port number
1234 */
1235 public static PortNumber tunnelPortNumByNetId(String netId,
1236 OpenstackNetworkService netService,
1237 OpenstackNode osNode) {
SONA Project6bc5c4a2018-12-14 23:49:52 +09001238 Type netType = netService.networkType(netId);
Jian Li2d68c192018-12-13 15:52:59 +09001239
1240 if (netType == null) {
1241 return null;
1242 }
1243
1244 return tunnelPortNumByNetType(netType, osNode);
1245 }
1246
1247 /**
1248 * Returns the tunnel port number with specified net type and openstack node.
1249 *
1250 * @param netType network type
1251 * @param osNode openstack node
1252 * @return tunnel port number
1253 */
SONA Project6bc5c4a2018-12-14 23:49:52 +09001254 public static PortNumber tunnelPortNumByNetType(Type netType, OpenstackNode osNode) {
Jian Li2d68c192018-12-13 15:52:59 +09001255 switch (netType) {
1256 case VXLAN:
1257 return osNode.vxlanTunnelPortNum();
1258 case GRE:
1259 return osNode.greTunnelPortNum();
Jian Li621f73c2018-12-15 01:49:22 +09001260 case GENEVE:
1261 return osNode.geneveTunnelPortNum();
Jian Li2d68c192018-12-13 15:52:59 +09001262 default:
1263 return null;
1264 }
1265 }
1266
Jian Li7b8c3682019-05-12 13:57:15 +09001267 /**
1268 * Returns the REST URL of active node.
1269 *
1270 * @param haService openstack HA service
1271 * @return REST URL of active node
1272 */
1273 public static String getActiveUrl(OpenstackHaService haService) {
1274 return "http://" + haService.getActiveIp().toString() + ":" +
1275 REST_PORT + "/" + OPENSTACK_NETWORKING_REST_PATH + "/";
1276 }
1277
1278 /**
1279 * Returns the REST client instance with given resource path.
1280 *
1281 * @param haService openstack HA service
1282 * @param resourcePath resource path
1283 * @return REST client instance
1284 */
1285 public static WebTarget getActiveClient(OpenstackHaService haService,
1286 String resourcePath) {
1287 HttpAuthenticationFeature feature =
1288 HttpAuthenticationFeature.universal(REST_USER, REST_PASSWORD);
1289 Client client = ClientBuilder.newClient().register(feature);
1290 return client.target(getActiveUrl(haService)).path(resourcePath);
1291 }
1292
1293 /**
1294 * Returns the post response from the active node.
1295 *
1296 * @param haService openstack HA service
1297 * @param resourcePath resource path
1298 * @param input input
1299 * @return post response
1300 */
1301 public static Response syncPost(OpenstackHaService haService,
1302 String resourcePath,
1303 String input) {
1304
1305 log.debug("Sync POST request with {} on {}",
1306 haService.getActiveIp().toString(), resourcePath);
1307
1308 return getActiveClient(haService, resourcePath)
1309 .request(APPLICATION_JSON_TYPE)
1310 .post(Entity.json(input));
1311 }
1312
1313 /**
1314 * Returns the put response from the active node.
1315 *
1316 * @param haService openstack HA service
1317 * @param resourcePath resource path
1318 * @param id resource identifier
1319 * @param input input
1320 * @return put response
1321 */
1322 public static Response syncPut(OpenstackHaService haService,
1323 String resourcePath,
1324 String id, String input) {
1325 return syncPut(haService, resourcePath, null, id, input);
1326 }
1327
1328 /**
1329 * Returns the put response from the active node.
1330 *
1331 * @param haService openstack HA service
1332 * @param resourcePath resource path
1333 * @param id resource identifier
1334 * @param suffix resource suffix
1335 * @param input input
1336 * @return put response
1337 */
1338 public static Response syncPut(OpenstackHaService haService,
1339 String resourcePath,
1340 String suffix,
1341 String id, String input) {
1342
1343 log.debug("Sync PUT request with {} on {}",
1344 haService.getActiveIp().toString(), resourcePath);
1345
1346 String pathStr = "/" + id;
1347
1348 if (suffix != null) {
1349 pathStr += "/" + suffix;
1350 }
1351
1352 return getActiveClient(haService, resourcePath)
1353 .path(pathStr)
1354 .request(APPLICATION_JSON_TYPE)
1355 .put(Entity.json(input));
1356 }
1357
1358 /**
1359 * Returns the delete response from the active node.
1360 *
1361 * @param haService openstack HA service
1362 * @param resourcePath resource path
1363 * @param id resource identifier
1364 * @return delete response
1365 */
1366 public static Response syncDelete(OpenstackHaService haService,
1367 String resourcePath,
1368 String id) {
1369
1370 log.debug("Sync DELETE request with {} on {}",
1371 haService.getActiveIp().toString(), resourcePath);
1372
1373 return getActiveClient(haService, resourcePath)
1374 .path("/" + id)
1375 .request(APPLICATION_JSON_TYPE)
1376 .delete();
1377 }
1378
Jian Li51728702019-05-17 18:38:56 +09001379 /**
1380 * Gets the ovsdb client with supplied openstack node.
1381 *
1382 * @param node openstack node
1383 * @param ovsdbPort openvswitch DB port number
1384 * @param controller openvswitch DB controller instance
1385 * @return ovsdb client instance
1386 */
1387 public static OvsdbClientService getOvsdbClient(OpenstackNode node, int ovsdbPort,
1388 OvsdbController controller) {
1389 OvsdbNodeId ovsdb = new OvsdbNodeId(node.managementIp(), ovsdbPort);
1390 return controller.getOvsdbClient(ovsdb);
1391 }
1392
1393 /**
1394 * Obtains the name of interface attached to the openstack VM.
1395 *
1396 * @param portId openstack port identifier
1397 * @return name of interface
1398 */
1399 public static String ifaceNameFromOsPortId(String portId) {
1400 if (portId != null) {
1401 return PORT_NAME_PREFIX_VM + StringUtils.substring(portId, 0, TAP_PORT_LENGTH);
1402 }
1403
1404 return null;
1405 }
1406
Jian Li5ecfd1a2018-12-10 11:41:03 +09001407 private static Router getRouterFromSubnet(Subnet subnet,
1408 OpenstackRouterService osRouterService) {
Jian Liebde74d2018-11-14 00:18:57 +09001409 RouterInterface osRouterIface = osRouterService.routerInterfaces().stream()
1410 .filter(i -> Objects.equals(i.getSubnetId(), subnet.getId()))
1411 .findAny().orElse(null);
1412 if (osRouterIface == null) {
1413 return null;
1414 }
1415
1416 return osRouterService.router(osRouterIface.getId());
1417 }
1418
Daniel Park7e8c4d82018-08-13 23:47:49 +09001419 private static boolean isDirectPort(String portName) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001420 return portNamePrefixMap().values().stream().anyMatch(portName::startsWith);
Daniel Park7e8c4d82018-08-13 23:47:49 +09001421 }
1422
Daniel Park2ff66b42018-08-01 11:52:45 +09001423 /**
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001424 * Returns GARP packet with supplied floating ip and instance port information.
1425 *
1426 * @param floatingIP floating ip
1427 * @param instancePort instance port
1428 * @param vlanId vlan id
1429 * @return GARP packet
1430 */
1431 private static Ethernet buildGratuitousArpPacket(NetFloatingIP floatingIP,
1432 InstancePort instancePort,
1433 VlanId vlanId) {
1434 Ethernet ethernet = new Ethernet();
1435 ethernet.setDestinationMACAddress(MacAddress.BROADCAST);
1436 ethernet.setSourceMACAddress(instancePort.macAddress());
1437 ethernet.setEtherType(Ethernet.TYPE_ARP);
1438 ethernet.setVlanID(vlanId.id());
1439
1440 ARP arp = new ARP();
1441 arp.setOpCode(ARP.OP_REPLY);
1442 arp.setProtocolType(ARP.PROTO_TYPE_IP);
1443 arp.setHardwareType(ARP.HW_TYPE_ETHERNET);
1444
1445 arp.setProtocolAddressLength((byte) Ip4Address.BYTE_LENGTH);
1446 arp.setHardwareAddressLength((byte) Ethernet.DATALAYER_ADDRESS_LENGTH);
1447
1448 arp.setSenderHardwareAddress(instancePort.macAddress().toBytes());
1449 arp.setTargetHardwareAddress(MacAddress.BROADCAST.toBytes());
1450
Jian Li5ecfd1a2018-12-10 11:41:03 +09001451 arp.setSenderProtocolAddress(valueOf(floatingIP.getFloatingIpAddress()).toInt());
1452 arp.setTargetProtocolAddress(valueOf(floatingIP.getFloatingIpAddress()).toInt());
Daniel Park4fa1f5e2018-10-17 12:41:52 +09001453
1454 ethernet.setPayload(arp);
1455
1456 return ethernet;
1457 }
1458
1459 /**
Jian Lia271b3c2019-09-03 23:10:20 +09001460 * Re-structures the OVS port name.
1461 * The length of OVS port name should be not large than 15.
1462 *
1463 * @param portName original port name
1464 * @return re-structured OVS port name
1465 */
1466 public static String structurePortName(String portName) {
1467
1468 // The size of OVS port name should not be larger than 15
1469 if (portName.length() > PORT_NAME_MAX_LENGTH) {
1470 return StringUtils.substring(portName, 0, PORT_NAME_MAX_LENGTH);
1471 }
1472
1473 return portName;
1474 }
1475
1476 /**
Jian Lid5727622019-09-11 11:15:16 +09001477 * Obtains flow group key from the given id.
1478 *
1479 * @param groupId flow group identifier
1480 * @return flow group key
1481 */
1482 public static GroupKey getGroupKey(int groupId) {
1483 return new DefaultGroupKey((Integer.toString(groupId)).getBytes());
1484 }
1485
1486 /**
Jian Li51b844c2018-05-31 10:59:03 +09001487 * Builds up and a complete endpoint URL from gateway node.
1488 *
1489 * @param node gateway node
1490 * @return a complete endpoint URL
1491 */
1492 private static String buildEndpoint(OpenstackNode node) {
1493
Jian Lic704b672018-09-04 18:52:53 +09001494 OpenstackAuth auth = node.keystoneConfig().authentication();
Jian Li51b844c2018-05-31 10:59:03 +09001495
1496 StringBuilder endpointSb = new StringBuilder();
1497 endpointSb.append(auth.protocol().name().toLowerCase());
1498 endpointSb.append("://");
Jian Lic704b672018-09-04 18:52:53 +09001499 endpointSb.append(node.keystoneConfig().endpoint());
Jian Li51b844c2018-05-31 10:59:03 +09001500 return endpointSb.toString();
1501 }
1502
1503 /**
1504 * Obtains the SSL config without verifying the certification.
1505 *
1506 * @return SSL config
1507 */
1508 private static Config getSslConfig() {
1509 // we bypass the SSL certification verification for now
1510 // TODO: verify server side SSL using a given certification
1511 Config config = Config.newConfig().withSSLVerificationDisabled();
1512
1513 TrustManager[] trustAllCerts = new TrustManager[]{
1514 new X509TrustManager() {
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001515 @Override
Jian Li51b844c2018-05-31 10:59:03 +09001516 public X509Certificate[] getAcceptedIssuers() {
1517 return null;
1518 }
1519
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001520 @Override
Jian Li51b844c2018-05-31 10:59:03 +09001521 public void checkClientTrusted(X509Certificate[] certs,
1522 String authType) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001523 return;
Jian Li51b844c2018-05-31 10:59:03 +09001524 }
1525
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001526 @Override
Jian Li51b844c2018-05-31 10:59:03 +09001527 public void checkServerTrusted(X509Certificate[] certs,
1528 String authType) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001529 return;
Jian Li51b844c2018-05-31 10:59:03 +09001530 }
1531 }
1532 };
1533
1534 HostnameVerifier allHostsValid = (hostname, session) -> true;
1535
1536 try {
1537 SSLContext sc = SSLContext.getInstance(SSL_TYPE);
1538 sc.init(null, trustAllCerts,
1539 new java.security.SecureRandom());
1540 HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
1541 HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
1542
1543 config.withSSLContext(sc);
1544 } catch (Exception e) {
Daniel Parka3ffbdb2018-11-28 13:51:39 +09001545 log.error("Failed to access OpenStack service due to {}", e);
Jian Li51b844c2018-05-31 10:59:03 +09001546 return null;
1547 }
1548
1549 return config;
1550 }
1551
1552 /**
1553 * Obtains the facing object with given openstack perspective.
1554 *
1555 * @param perspective keystone perspective
1556 * @return facing object
1557 */
1558 private static Facing getFacing(Perspective perspective) {
1559
1560 switch (perspective) {
1561 case PUBLIC:
1562 return Facing.PUBLIC;
1563 case ADMIN:
1564 return Facing.ADMIN;
1565 case INTERNAL:
1566 return Facing.INTERNAL;
1567 default:
1568 return null;
1569 }
1570 }
1571
1572 /**
1573 * Obtains gateway instance by giving index number.
1574 *
1575 * @param gws a collection of gateway nodes
1576 * @param index index number
1577 * @return gateway instance
1578 */
1579 private static OpenstackNode getGwByIndex(Set<OpenstackNode> gws, int index) {
1580 Map<String, OpenstackNode> hashMap = new HashMap<>();
1581 gws.forEach(gw -> hashMap.put(gw.hostname(), gw));
1582 TreeMap<String, OpenstackNode> treeMap = new TreeMap<>(hashMap);
1583 Iterator<String> iteratorKey = treeMap.keySet().iterator();
1584
1585 int intIndex = 0;
1586 OpenstackNode gw = null;
1587 while (iteratorKey.hasNext()) {
1588 String key = iteratorKey.next();
1589
1590 if (intIndex == index) {
1591 gw = treeMap.get(key);
1592 }
1593 intIndex++;
1594 }
1595 return gw;
1596 }
Jian Li40f032a2019-10-02 20:36:09 +09001597
1598 private static void print(String format, Object... args) {
1599 System.out.println(String.format(format, args));
1600 }
Jian Li63430202018-08-30 16:24:09 +09001601}