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