|
| 1 | +/* |
| 2 | + * Copyright 1999-2018 Alibaba Group Holding Ltd. |
| 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 com.alibaba.csp.sentinel.datasource.eureka; |
| 17 | + |
| 18 | +import com.alibaba.csp.sentinel.datasource.AutoRefreshDataSource; |
| 19 | +import com.alibaba.csp.sentinel.datasource.Converter; |
| 20 | +import com.alibaba.csp.sentinel.datasource.ReadableDataSource; |
| 21 | +import com.alibaba.csp.sentinel.log.RecordLog; |
| 22 | +import com.alibaba.csp.sentinel.util.AssertUtil; |
| 23 | +import com.alibaba.csp.sentinel.util.StringUtil; |
| 24 | +import com.alibaba.fastjson.JSON; |
| 25 | + |
| 26 | +import java.io.*; |
| 27 | +import java.net.HttpURLConnection; |
| 28 | +import java.net.InetAddress; |
| 29 | +import java.net.URL; |
| 30 | +import java.util.ArrayList; |
| 31 | +import java.util.Collections; |
| 32 | +import java.util.List; |
| 33 | + |
| 34 | +/** |
| 35 | + * <p> |
| 36 | + * A {@link ReadableDataSource} based on Eureka. This class will automatically |
| 37 | + * fetches the metadata of the instance every period. |
| 38 | + * </p> |
| 39 | + * <p> |
| 40 | + * Limitations: Default refresh interval is 10s. Because there is synchronization between eureka servers, |
| 41 | + * it may take longer to take effect. |
| 42 | + * </p> |
| 43 | + * |
| 44 | + * @author: liyang |
| 45 | + * @create: 2020-05-23 12:01 |
| 46 | + */ |
| 47 | +public class EurekaDataSource<T> extends AutoRefreshDataSource<String, T> { |
| 48 | + |
| 49 | + private static final long DEFAULT_REFRESH_MS = 10000; |
| 50 | + |
| 51 | + /** |
| 52 | + * connect timeout: 3s |
| 53 | + */ |
| 54 | + private static final int DEFAULT_CONNECT_TIMEOUT_MS = 3000; |
| 55 | + |
| 56 | + /** |
| 57 | + * read timeout: 30s |
| 58 | + */ |
| 59 | + private static final int DEFAULT_READ_TIMEOUT_MS = 30000; |
| 60 | + |
| 61 | + |
| 62 | + private int connectTimeoutMills; |
| 63 | + |
| 64 | + |
| 65 | + private int readTimeoutMills; |
| 66 | + |
| 67 | + /** |
| 68 | + * eureka instance appid |
| 69 | + */ |
| 70 | + private String appId; |
| 71 | + /** |
| 72 | + * eureka instance id |
| 73 | + */ |
| 74 | + private String instanceId; |
| 75 | + |
| 76 | + /** |
| 77 | + * collect of eureka server urls |
| 78 | + */ |
| 79 | + private List<String> serviceUrls; |
| 80 | + |
| 81 | + /** |
| 82 | + * metadata key of the rule source |
| 83 | + */ |
| 84 | + private String ruleKey; |
| 85 | + |
| 86 | + |
| 87 | + public EurekaDataSource(String appId, String instanceId, List<String> serviceUrls, String ruleKey, |
| 88 | + Converter<String, T> configParser) { |
| 89 | + this(appId, instanceId, serviceUrls, ruleKey, configParser, DEFAULT_REFRESH_MS, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_READ_TIMEOUT_MS); |
| 90 | + } |
| 91 | + |
| 92 | + |
| 93 | + public EurekaDataSource(String appId, String instanceId, List<String> serviceUrls, String ruleKey, |
| 94 | + Converter<String, T> configParser, long refreshMs, int connectTimeoutMills, |
| 95 | + int readTimeoutMills) { |
| 96 | + super(configParser, refreshMs); |
| 97 | + AssertUtil.notNull(appId, "appId can't be null"); |
| 98 | + AssertUtil.notNull(instanceId, "instanceId can't be null"); |
| 99 | + AssertUtil.assertNotEmpty(serviceUrls, "serviceUrls can't be empty"); |
| 100 | + AssertUtil.notNull(ruleKey, "ruleKey can't be null"); |
| 101 | + AssertUtil.assertState(connectTimeoutMills > 0, "connectTimeoutMills must be greater than 0"); |
| 102 | + AssertUtil.assertState(readTimeoutMills > 0, "readTimeoutMills must be greater than 0"); |
| 103 | + |
| 104 | + this.appId = appId; |
| 105 | + this.instanceId = instanceId; |
| 106 | + this.serviceUrls = ensureEndWithSlash(serviceUrls); |
| 107 | + AssertUtil.assertNotEmpty(this.serviceUrls, "No available service url"); |
| 108 | + this.ruleKey = ruleKey; |
| 109 | + this.connectTimeoutMills = connectTimeoutMills; |
| 110 | + this.readTimeoutMills = readTimeoutMills; |
| 111 | + } |
| 112 | + |
| 113 | + |
| 114 | + private List<String> ensureEndWithSlash(List<String> serviceUrls) { |
| 115 | + List<String> newServiceUrls = new ArrayList<>(); |
| 116 | + for (String serviceUrl : serviceUrls) { |
| 117 | + if (StringUtil.isBlank(serviceUrl)) { |
| 118 | + continue; |
| 119 | + } |
| 120 | + if (!serviceUrl.endsWith("/")) { |
| 121 | + serviceUrl = serviceUrl + "/"; |
| 122 | + } |
| 123 | + newServiceUrls.add(serviceUrl); |
| 124 | + } |
| 125 | + return newServiceUrls; |
| 126 | + } |
| 127 | + |
| 128 | + @Override |
| 129 | + public String readSource() throws Exception { |
| 130 | + return fetchStringSourceFromEurekaMetadata(this.appId, this.instanceId, this.serviceUrls, ruleKey); |
| 131 | + } |
| 132 | + |
| 133 | + |
| 134 | + private String fetchStringSourceFromEurekaMetadata(String appId, String instanceId, List<String> serviceUrls, |
| 135 | + String ruleKey) throws Exception { |
| 136 | + List<String> shuffleUrls = new ArrayList<>(serviceUrls.size()); |
| 137 | + shuffleUrls.addAll(serviceUrls); |
| 138 | + Collections.shuffle(shuffleUrls); |
| 139 | + for (int i = 0; i < shuffleUrls.size(); i++) { |
| 140 | + String serviceUrl = shuffleUrls.get(i) + String.format("apps/%s/%s", appId, instanceId); |
| 141 | + HttpURLConnection conn = null; |
| 142 | + try { |
| 143 | + conn = (HttpURLConnection) new URL(serviceUrl).openConnection(); |
| 144 | + conn.addRequestProperty("Accept", "application/json;charset=utf-8"); |
| 145 | + |
| 146 | + conn.setConnectTimeout(connectTimeoutMills); |
| 147 | + conn.setReadTimeout(readTimeoutMills); |
| 148 | + conn.setRequestMethod("GET"); |
| 149 | + conn.setDoOutput(true); |
| 150 | + conn.connect(); |
| 151 | + RecordLog.debug("[EurekaDataSource] Request from eureka server: " + serviceUrl); |
| 152 | + if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { |
| 153 | + String s = toString(conn.getInputStream()); |
| 154 | + String ruleString = JSON.parseObject(s) |
| 155 | + .getJSONObject("instance") |
| 156 | + .getJSONObject("metadata") |
| 157 | + .getString(ruleKey); |
| 158 | + return ruleString; |
| 159 | + } |
| 160 | + RecordLog.warn("[EurekaDataSource] Warn: retrying on another server if available " + |
| 161 | + "due to response code: {}, response message: {}", conn.getResponseCode(), toString(conn.getErrorStream())); |
| 162 | + } catch (Exception e) { |
| 163 | + try { |
| 164 | + if (conn != null) { |
| 165 | + RecordLog.warn("[EurekaDataSource] Warn: failed to request " + conn.getURL() + " from " |
| 166 | + + InetAddress.getByName(conn.getURL().getHost()).getHostAddress(), e); |
| 167 | + } |
| 168 | + } catch (Exception e1) { |
| 169 | + RecordLog.warn("[EurekaDataSource] Warn: failed to request ", e1); |
| 170 | + //ignore |
| 171 | + } |
| 172 | + RecordLog.warn("[EurekaDataSource] Warn: failed to request,retrying on another server if available"); |
| 173 | + |
| 174 | + } finally { |
| 175 | + if (conn != null) { |
| 176 | + conn.disconnect(); |
| 177 | + } |
| 178 | + } |
| 179 | + } |
| 180 | + throw new EurekaMetadataFetchException("Can't get any data"); |
| 181 | + } |
| 182 | + |
| 183 | + |
| 184 | + public static class EurekaMetadataFetchException extends Exception { |
| 185 | + |
| 186 | + public EurekaMetadataFetchException(String message) { |
| 187 | + super(message); |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + |
| 192 | + private String toString(InputStream input) throws IOException { |
| 193 | + if (input == null) { |
| 194 | + return null; |
| 195 | + } |
| 196 | + InputStreamReader inputStreamReader = new InputStreamReader(input, "utf-8"); |
| 197 | + CharArrayWriter sw = new CharArrayWriter(); |
| 198 | + copy(inputStreamReader, sw); |
| 199 | + return sw.toString(); |
| 200 | + } |
| 201 | + |
| 202 | + private long copy(Reader input, Writer output) throws IOException { |
| 203 | + char[] buffer = new char[1 << 12]; |
| 204 | + long count = 0; |
| 205 | + for (int n = 0; (n = input.read(buffer)) >= 0; ) { |
| 206 | + output.write(buffer, 0, n); |
| 207 | + count += n; |
| 208 | + } |
| 209 | + return count; |
| 210 | + } |
| 211 | + |
| 212 | + |
| 213 | +} |
0 commit comments