Jian Li | bde20bf | 2019-01-25 17:34:43 +0900 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2019-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.k8snetworking.util; |
| 17 | |
| 18 | import com.fasterxml.jackson.core.JsonParseException; |
| 19 | import com.fasterxml.jackson.core.JsonProcessingException; |
| 20 | import com.fasterxml.jackson.databind.JsonMappingException; |
| 21 | import com.fasterxml.jackson.databind.ObjectMapper; |
Jian Li | 2cc2b63 | 2019-02-18 00:56:40 +0900 | [diff] [blame] | 22 | import com.google.common.collect.Maps; |
Jian Li | 8538773 | 2019-02-19 23:56:18 +0900 | [diff] [blame] | 23 | import io.fabric8.kubernetes.client.ConfigBuilder; |
| 24 | import io.fabric8.kubernetes.client.DefaultKubernetesClient; |
| 25 | import io.fabric8.kubernetes.client.KubernetesClient; |
| 26 | import org.apache.commons.lang3.StringUtils; |
Jian Li | 9b19916 | 2019-02-10 18:00:35 +0900 | [diff] [blame] | 27 | import org.apache.commons.net.util.SubnetUtils; |
| 28 | import org.onlab.packet.IpAddress; |
Jian Li | 140d8a2 | 2019-04-24 23:41:44 +0900 | [diff] [blame] | 29 | import org.onlab.packet.TpPort; |
Jian Li | 4aa1764 | 2019-01-30 00:01:11 +0900 | [diff] [blame] | 30 | import org.onosproject.cfg.ConfigProperty; |
| 31 | import org.onosproject.k8snetworking.api.K8sNetwork; |
| 32 | import org.onosproject.k8snetworking.api.K8sNetworkService; |
Jian Li | 8538773 | 2019-02-19 23:56:18 +0900 | [diff] [blame] | 33 | import org.onosproject.k8snode.api.K8sApiConfig; |
Jian Li | 3d1111e | 2019-02-22 02:02:13 +0900 | [diff] [blame] | 34 | import org.onosproject.k8snode.api.K8sApiConfigService; |
Jian Li | 4aa1764 | 2019-01-30 00:01:11 +0900 | [diff] [blame] | 35 | import org.onosproject.k8snode.api.K8sNode; |
Jian Li | 2cc2b63 | 2019-02-18 00:56:40 +0900 | [diff] [blame] | 36 | import org.onosproject.k8snode.api.K8sNodeService; |
Jian Li | 4aa1764 | 2019-01-30 00:01:11 +0900 | [diff] [blame] | 37 | import org.onosproject.net.PortNumber; |
Jian Li | 2cc2b63 | 2019-02-18 00:56:40 +0900 | [diff] [blame] | 38 | import org.onosproject.net.group.DefaultGroupKey; |
| 39 | import org.onosproject.net.group.GroupKey; |
Jian Li | bde20bf | 2019-01-25 17:34:43 +0900 | [diff] [blame] | 40 | import org.slf4j.Logger; |
| 41 | import org.slf4j.LoggerFactory; |
| 42 | |
| 43 | import java.io.IOException; |
Jian Li | 9b19916 | 2019-02-10 18:00:35 +0900 | [diff] [blame] | 44 | import java.util.Arrays; |
| 45 | import java.util.HashSet; |
Jian Li | 2cc2b63 | 2019-02-18 00:56:40 +0900 | [diff] [blame] | 46 | import java.util.Map; |
Jian Li | 140d8a2 | 2019-04-24 23:41:44 +0900 | [diff] [blame] | 47 | import java.util.Objects; |
Jian Li | 4aa1764 | 2019-01-30 00:01:11 +0900 | [diff] [blame] | 48 | import java.util.Optional; |
| 49 | import java.util.Set; |
Jian Li | 9b19916 | 2019-02-10 18:00:35 +0900 | [diff] [blame] | 50 | import java.util.stream.Collectors; |
Jian Li | bde20bf | 2019-01-25 17:34:43 +0900 | [diff] [blame] | 51 | |
| 52 | import static org.onosproject.k8snetworking.api.Constants.PORT_NAME_PREFIX_CONTAINER; |
| 53 | |
| 54 | /** |
| 55 | * An utility that used in kubernetes networking app. |
| 56 | */ |
| 57 | public final class K8sNetworkingUtil { |
| 58 | |
| 59 | private static final Logger log = LoggerFactory.getLogger(K8sNetworkingUtil.class); |
| 60 | |
Jian Li | 8538773 | 2019-02-19 23:56:18 +0900 | [diff] [blame] | 61 | private static final String COLON_SLASH = "://"; |
| 62 | private static final String COLON = ":"; |
| 63 | |
Jian Li | 140d8a2 | 2019-04-24 23:41:44 +0900 | [diff] [blame] | 64 | private static final String STR_ZERO = "0"; |
| 65 | private static final String STR_ONE = "1"; |
| 66 | private static final String STR_PADDING = "0000000000000000"; |
| 67 | private static final int MASK_BEGIN_IDX = 0; |
| 68 | private static final int MASK_MAX_IDX = 16; |
| 69 | private static final int MASK_RADIX = 2; |
| 70 | private static final int PORT_RADIX = 16; |
| 71 | |
Jian Li | bde20bf | 2019-01-25 17:34:43 +0900 | [diff] [blame] | 72 | private K8sNetworkingUtil() { |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * Checks that whether the port is associated with container interface. |
| 77 | * |
| 78 | * @param portName port name |
| 79 | * @return true if the port is associated with container; false otherwise |
| 80 | */ |
| 81 | public static boolean isContainer(String portName) { |
Jian Li | 4aa1764 | 2019-01-30 00:01:11 +0900 | [diff] [blame] | 82 | return portName != null && portName.contains(PORT_NAME_PREFIX_CONTAINER); |
| 83 | } |
| 84 | |
| 85 | /** |
| 86 | * Returns the tunnel port number with specified net ID and kubernetes node. |
| 87 | * |
| 88 | * @param netId network ID |
| 89 | * @param netService network service |
| 90 | * @param node kubernetes node |
| 91 | * @return tunnel port number |
| 92 | */ |
| 93 | public static PortNumber tunnelPortNumByNetId(String netId, |
| 94 | K8sNetworkService netService, |
| 95 | K8sNode node) { |
| 96 | K8sNetwork.Type netType = netService.network(netId).type(); |
| 97 | |
| 98 | if (netType == null) { |
| 99 | return null; |
| 100 | } |
| 101 | |
| 102 | return tunnelPortNumByNetType(netType, node); |
| 103 | } |
| 104 | |
| 105 | /** |
| 106 | * Returns the tunnel port number with specified net type and kubernetes node. |
| 107 | * |
| 108 | * @param netType network type |
| 109 | * @param node kubernetes node |
| 110 | * @return tunnel port number |
| 111 | */ |
| 112 | public static PortNumber tunnelPortNumByNetType(K8sNetwork.Type netType, |
| 113 | K8sNode node) { |
| 114 | switch (netType) { |
| 115 | case VXLAN: |
| 116 | return node.vxlanPortNum(); |
| 117 | case GRE: |
| 118 | return node.grePortNum(); |
| 119 | case GENEVE: |
| 120 | return node.genevePortNum(); |
| 121 | default: |
| 122 | return null; |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | /** |
| 127 | * Obtains the property value with specified property key name. |
| 128 | * |
| 129 | * @param properties a collection of properties |
| 130 | * @param name key name |
| 131 | * @return mapping value |
| 132 | */ |
| 133 | public static String getPropertyValue(Set<ConfigProperty> properties, |
| 134 | String name) { |
| 135 | Optional<ConfigProperty> property = |
| 136 | properties.stream().filter(p -> p.name().equals(name)).findFirst(); |
| 137 | return property.map(ConfigProperty::value).orElse(null); |
Jian Li | bde20bf | 2019-01-25 17:34:43 +0900 | [diff] [blame] | 138 | } |
| 139 | |
| 140 | /** |
| 141 | * Prints out the JSON string in pretty format. |
| 142 | * |
| 143 | * @param mapper Object mapper |
| 144 | * @param jsonString JSON string |
| 145 | * @return pretty formatted JSON string |
| 146 | */ |
| 147 | public static String prettyJson(ObjectMapper mapper, String jsonString) { |
| 148 | try { |
| 149 | Object jsonObject = mapper.readValue(jsonString, Object.class); |
| 150 | return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject); |
| 151 | } catch (JsonParseException e) { |
| 152 | log.debug("JsonParseException caused by {}", e); |
| 153 | } catch (JsonMappingException e) { |
| 154 | log.debug("JsonMappingException caused by {}", e); |
| 155 | } catch (JsonProcessingException e) { |
| 156 | log.debug("JsonProcessingException caused by {}", e); |
| 157 | } catch (IOException e) { |
| 158 | log.debug("IOException caused by {}", e); |
| 159 | } |
| 160 | return null; |
| 161 | } |
Jian Li | 9b19916 | 2019-02-10 18:00:35 +0900 | [diff] [blame] | 162 | |
| 163 | /** |
| 164 | * Obtains valid IP addresses of the given subnet. |
| 165 | * |
| 166 | * @param cidr CIDR |
| 167 | * @return set of IP addresses |
| 168 | */ |
| 169 | public static Set<IpAddress> getSubnetIps(String cidr) { |
| 170 | SubnetUtils utils = new SubnetUtils(cidr); |
| 171 | utils.setInclusiveHostCount(true); |
| 172 | SubnetUtils.SubnetInfo info = utils.getInfo(); |
| 173 | Set<String> allAddresses = |
| 174 | new HashSet<>(Arrays.asList(info.getAllAddresses())); |
| 175 | |
| 176 | if (allAddresses.size() > 2) { |
| 177 | allAddresses.remove(info.getBroadcastAddress()); |
| 178 | allAddresses.remove(info.getNetworkAddress()); |
| 179 | } |
| 180 | |
| 181 | return allAddresses.stream() |
| 182 | .map(IpAddress::valueOf).collect(Collectors.toSet()); |
| 183 | } |
Jian Li | 8538773 | 2019-02-19 23:56:18 +0900 | [diff] [blame] | 184 | |
| 185 | /** |
Jian Li | 2cc2b63 | 2019-02-18 00:56:40 +0900 | [diff] [blame] | 186 | * Obtains flow group key from the given id. |
| 187 | * |
| 188 | * @param groupId flow group identifier |
| 189 | * @return flow group key |
| 190 | */ |
| 191 | public static GroupKey getGroupKey(int groupId) { |
| 192 | return new DefaultGroupKey((Integer.toString(groupId)).getBytes()); |
| 193 | } |
| 194 | |
| 195 | /** |
Jian Li | 8538773 | 2019-02-19 23:56:18 +0900 | [diff] [blame] | 196 | * Generates endpoint URL by referring to scheme, ipAddress and port. |
| 197 | * |
| 198 | * @param scheme scheme |
| 199 | * @param ipAddress IP address |
| 200 | * @param port port number |
| 201 | * @return generated endpoint URL |
| 202 | */ |
| 203 | public static String endpoint(K8sApiConfig.Scheme scheme, IpAddress ipAddress, int port) { |
| 204 | StringBuilder endpoint = new StringBuilder(); |
| 205 | String protocol = StringUtils.lowerCase(scheme.name()); |
| 206 | |
| 207 | endpoint.append(protocol); |
| 208 | endpoint.append(COLON_SLASH); |
| 209 | endpoint.append(ipAddress.toString()); |
| 210 | endpoint.append(COLON); |
| 211 | endpoint.append(port); |
| 212 | |
| 213 | return endpoint.toString(); |
| 214 | } |
| 215 | |
| 216 | /** |
| 217 | * Generates endpoint URL by referring to scheme, ipAddress and port. |
| 218 | * |
| 219 | * @param apiConfig kubernetes API config |
| 220 | * @return generated endpoint URL |
| 221 | */ |
| 222 | public static String endpoint(K8sApiConfig apiConfig) { |
| 223 | return endpoint(apiConfig.scheme(), apiConfig.ipAddress(), apiConfig.port()); |
| 224 | } |
| 225 | |
| 226 | /** |
| 227 | * Obtains workable kubernetes client. |
| 228 | * |
| 229 | * @param config kubernetes API config |
| 230 | * @return kubernetes client |
| 231 | */ |
| 232 | public static KubernetesClient k8sClient(K8sApiConfig config) { |
| 233 | if (config == null) { |
| 234 | log.warn("Kubernetes API server config is empty."); |
| 235 | return null; |
| 236 | } |
| 237 | |
| 238 | String endpoint = endpoint(config); |
| 239 | |
| 240 | ConfigBuilder configBuilder = new ConfigBuilder().withMasterUrl(endpoint); |
| 241 | |
| 242 | if (config.scheme() == K8sApiConfig.Scheme.HTTPS) { |
| 243 | configBuilder.withTrustCerts(true) |
| 244 | .withOauthToken(config.token()) |
| 245 | .withCaCertData(config.caCertData()) |
| 246 | .withClientCertData(config.clientCertData()) |
| 247 | .withClientKeyData(config.clientKeyData()); |
| 248 | } |
| 249 | |
| 250 | return new DefaultKubernetesClient(configBuilder.build()); |
| 251 | } |
Jian Li | 3d1111e | 2019-02-22 02:02:13 +0900 | [diff] [blame] | 252 | |
| 253 | /** |
| 254 | * Obtains workable kubernetes client. |
| 255 | * |
| 256 | * @param service kubernetes API service |
| 257 | * @return kubernetes client |
| 258 | */ |
| 259 | public static KubernetesClient k8sClient(K8sApiConfigService service) { |
| 260 | K8sApiConfig config = |
| 261 | service.apiConfigs().stream().findAny().orElse(null); |
| 262 | if (config == null) { |
| 263 | log.error("Failed to find valid kubernetes API configuration."); |
| 264 | return null; |
| 265 | } |
| 266 | |
| 267 | KubernetesClient client = k8sClient(config); |
| 268 | |
| 269 | if (client == null) { |
| 270 | log.error("Failed to connect to kubernetes API server."); |
| 271 | return null; |
| 272 | } |
| 273 | |
| 274 | return client; |
| 275 | } |
Jian Li | 2cc2b63 | 2019-02-18 00:56:40 +0900 | [diff] [blame] | 276 | |
| 277 | /** |
| 278 | * Obtains the kubernetes node IP and kubernetes network gateway IP map. |
| 279 | * |
| 280 | * @param nodeService kubernetes node service |
| 281 | * @param networkService kubernetes network service |
| 282 | * @return kubernetes node IP and kubernetes network gateway IP map |
| 283 | */ |
| 284 | public static Map<String, String> nodeIpGatewayIpMap(K8sNodeService nodeService, |
| 285 | K8sNetworkService networkService) { |
| 286 | Map<String, String> ipMap = Maps.newConcurrentMap(); |
| 287 | |
| 288 | nodeService.completeNodes().forEach(n -> { |
| 289 | K8sNetwork network = networkService.network(n.hostname()); |
| 290 | if (network != null) { |
| 291 | ipMap.put(n.dataIp().toString(), network.gatewayIp().toString()); |
| 292 | } |
| 293 | }); |
| 294 | |
| 295 | return ipMap; |
| 296 | } |
Jian Li | 004526d | 2019-02-25 16:26:27 +0900 | [diff] [blame] | 297 | |
| 298 | /** |
Jian Li | 140d8a2 | 2019-04-24 23:41:44 +0900 | [diff] [blame] | 299 | * Returns an unshifted IP address. |
Jian Li | 004526d | 2019-02-25 16:26:27 +0900 | [diff] [blame] | 300 | * |
Jian Li | 140d8a2 | 2019-04-24 23:41:44 +0900 | [diff] [blame] | 301 | * @param ipAddress IP address to be unshifted |
| 302 | * @param ipPrefix IP prefix which to be used for unshifting |
| 303 | * @param cidr a POD network CIDR |
| 304 | * @return unshifted IP address |
Jian Li | 004526d | 2019-02-25 16:26:27 +0900 | [diff] [blame] | 305 | */ |
Jian Li | 140d8a2 | 2019-04-24 23:41:44 +0900 | [diff] [blame] | 306 | public static String unshiftIpDomain(String ipAddress, |
| 307 | String ipPrefix, |
| 308 | String cidr) { |
Jian Li | 004526d | 2019-02-25 16:26:27 +0900 | [diff] [blame] | 309 | |
Jian Li | 140d8a2 | 2019-04-24 23:41:44 +0900 | [diff] [blame] | 310 | String origIpPrefix = cidr.split("\\.")[0] + "." + cidr.split("\\.")[1]; |
| 311 | return StringUtils.replace(ipAddress, ipPrefix, origIpPrefix); |
| 312 | } |
Jian Li | 004526d | 2019-02-25 16:26:27 +0900 | [diff] [blame] | 313 | |
Jian Li | 140d8a2 | 2019-04-24 23:41:44 +0900 | [diff] [blame] | 314 | /** |
| 315 | * Returns the B class IP prefix of the given CIDR. |
| 316 | * |
| 317 | * @param cidr CIDR |
| 318 | * @return IP prefix |
| 319 | */ |
| 320 | public static String getBclassIpPrefixFromCidr(String cidr) { |
| 321 | if (cidr == null) { |
| 322 | return null; |
| 323 | } |
| 324 | return cidr.split("\\.")[0] + "." + cidr.split("\\.")[1]; |
| 325 | } |
Jian Li | 004526d | 2019-02-25 16:26:27 +0900 | [diff] [blame] | 326 | |
Jian Li | 140d8a2 | 2019-04-24 23:41:44 +0900 | [diff] [blame] | 327 | /** |
| 328 | * Returns the A class IP prefix of the given CIDR. |
| 329 | * |
| 330 | * @param cidr CIDR |
| 331 | * @return IP prefix |
| 332 | */ |
| 333 | public static String getAclassIpPrefixFromCidr(String cidr) { |
| 334 | if (cidr == null) { |
| 335 | return null; |
| 336 | } |
| 337 | return cidr.split("\\.")[0]; |
| 338 | } |
| 339 | |
| 340 | /** |
| 341 | * Returns the map of port range. |
| 342 | * |
| 343 | * @param portMin minimum port number |
| 344 | * @param portMax maximum port number |
| 345 | * @return map of port range |
| 346 | */ |
| 347 | public static Map<TpPort, TpPort> buildPortRangeMatches(int portMin, int portMax) { |
| 348 | |
| 349 | boolean processing = true; |
| 350 | int start = portMin; |
| 351 | Map<TpPort, TpPort> portMaskMap = Maps.newHashMap(); |
| 352 | while (processing) { |
| 353 | String minStr = Integer.toBinaryString(start); |
| 354 | String binStrMinPadded = STR_PADDING.substring(minStr.length()) + minStr; |
| 355 | |
| 356 | int mask = testMasks(binStrMinPadded, start, portMax); |
| 357 | int maskStart = binLower(binStrMinPadded, mask); |
| 358 | int maskEnd = binHigher(binStrMinPadded, mask); |
| 359 | |
| 360 | log.debug("start : {} port/mask = {} / {} ", start, getMask(mask), maskStart); |
| 361 | portMaskMap.put(TpPort.tpPort(maskStart), TpPort.tpPort( |
| 362 | Integer.parseInt(Objects.requireNonNull(getMask(mask)), PORT_RADIX))); |
| 363 | |
| 364 | start = maskEnd + 1; |
| 365 | if (start > portMax) { |
| 366 | processing = false; |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | return portMaskMap; |
| 371 | } |
| 372 | |
| 373 | private static int binLower(String binStr, int bits) { |
| 374 | StringBuilder outBin = new StringBuilder( |
| 375 | binStr.substring(MASK_BEGIN_IDX, MASK_MAX_IDX - bits)); |
| 376 | for (int i = 0; i < bits; i++) { |
| 377 | outBin.append(STR_ZERO); |
| 378 | } |
| 379 | |
| 380 | return Integer.parseInt(outBin.toString(), MASK_RADIX); |
| 381 | } |
| 382 | |
| 383 | private static int binHigher(String binStr, int bits) { |
| 384 | StringBuilder outBin = new StringBuilder( |
| 385 | binStr.substring(MASK_BEGIN_IDX, MASK_MAX_IDX - bits)); |
| 386 | for (int i = 0; i < bits; i++) { |
| 387 | outBin.append(STR_ONE); |
| 388 | } |
| 389 | |
| 390 | return Integer.parseInt(outBin.toString(), MASK_RADIX); |
| 391 | } |
| 392 | |
| 393 | private static int testMasks(String binStr, int start, int end) { |
| 394 | int mask = MASK_BEGIN_IDX; |
| 395 | for (; mask <= MASK_MAX_IDX; mask++) { |
| 396 | int maskStart = binLower(binStr, mask); |
| 397 | int maskEnd = binHigher(binStr, mask); |
| 398 | if (maskStart < start || maskEnd > end) { |
| 399 | return mask - 1; |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | return mask; |
| 404 | } |
| 405 | |
| 406 | private static String getMask(int bits) { |
| 407 | switch (bits) { |
| 408 | case 0: return "ffff"; |
| 409 | case 1: return "fffe"; |
| 410 | case 2: return "fffc"; |
| 411 | case 3: return "fff8"; |
| 412 | case 4: return "fff0"; |
| 413 | case 5: return "ffe0"; |
| 414 | case 6: return "ffc0"; |
| 415 | case 7: return "ff80"; |
| 416 | case 8: return "ff00"; |
| 417 | case 9: return "fe00"; |
| 418 | case 10: return "fc00"; |
| 419 | case 11: return "f800"; |
| 420 | case 12: return "f000"; |
| 421 | case 13: return "e000"; |
| 422 | case 14: return "c000"; |
| 423 | case 15: return "8000"; |
| 424 | case 16: return "0000"; |
| 425 | default: return null; |
| 426 | } |
Jian Li | 004526d | 2019-02-25 16:26:27 +0900 | [diff] [blame] | 427 | } |
Jian Li | bde20bf | 2019-01-25 17:34:43 +0900 | [diff] [blame] | 428 | } |