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