Java Code Examples for com.alibaba.csp.sentinel.log.RecordLog#warn()

The following examples show how to use com.alibaba.csp.sentinel.log.RecordLog#warn() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClientEntityCodecProvider.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private static void resolveInstance() {
    RequestEntityWriter writer = SpiLoader.loadFirstInstance(RequestEntityWriter.class);
    if (writer == null) {
        RecordLog.warn("[ClientEntityCodecProvider] No existing request entity writer, resolve failed");
    } else {
        requestEntityWriter = writer;
        RecordLog.info("[ClientEntityCodecProvider] Request entity writer resolved: " + requestEntityWriter.getClass().getCanonicalName());
    }
    ResponseEntityDecoder decoder = SpiLoader.loadFirstInstance(ResponseEntityDecoder.class);
    if (decoder == null) {
        RecordLog.warn("[ClientEntityCodecProvider] No existing response entity decoder, resolve failed");
    } else {
        responseEntityDecoder = decoder;
        RecordLog.info("[ClientEntityCodecProvider] Response entity decoder resolved: " + responseEntityDecoder.getClass().getCanonicalName());
    }
}
 
Example 2
Source File: SpiLoader.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
public static <T> T loadFirstInstance(Class<T> clazz) {
    try {
        String key = clazz.getName();
        // Not thread-safe, as it's expected to be resolved in a thread-safe context.
        ServiceLoader<T> serviceLoader = SERVICE_LOADER_MAP.get(key);
        if (serviceLoader == null) {
            serviceLoader = ServiceLoader.load(clazz);
            SERVICE_LOADER_MAP.put(key, serviceLoader);
        }

        Iterator<T> iterator = serviceLoader.iterator();
        if (iterator.hasNext()) {
            return iterator.next();
        } else {
            return null;
        }
    } catch (Throwable t) {
        RecordLog.warn("[SpiLoader] ERROR: loadFirstInstance failed", t);
        t.printStackTrace();
        return null;
    }
}
 
Example 3
Source File: ClusterStateManager.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private static boolean stopClient() {
    try {
        ClusterTokenClient tokenClient = TokenClientProvider.getClient();
        if (tokenClient != null) {
            tokenClient.stop();
            RecordLog.info("[ClusterStateManager] Stopping the cluster token client");
            return true;
        } else {
            RecordLog.warn("[ClusterStateManager] Cannot stop cluster token client (no server SPI found)");
            return false;
        }
    } catch (Exception ex) {
        RecordLog.warn("[ClusterStateManager] Error when stopping cluster token client", ex);
        return false;
    }
}
 
Example 4
Source File: ClusterStateManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private static boolean stopClient() {
    try {
        ClusterTokenClient tokenClient = TokenClientProvider.getClient();
        if (tokenClient != null) {
            tokenClient.stop();
            RecordLog.info("[ClusterStateManager] Stopping the cluster token client");
            return true;
        } else {
            RecordLog.warn("[ClusterStateManager] Cannot stop cluster token client (no server SPI found)");
            return false;
        }
    } catch (Exception ex) {
        RecordLog.warn("[ClusterStateManager] Error when stopping cluster token client", ex);
        return false;
    }
}
 
Example 5
Source File: SimpleHttpClient.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * Encode and get the URL request parameters.
 *
 * @param paramsMap pair of parameters
 * @param charset   charset
 * @return encoded request parameters, or empty string ("") if no parameters are provided
 */
private String encodeRequestParams(Map<String, String> paramsMap, Charset charset) {
    if (paramsMap == null || paramsMap.isEmpty()) {
        return "";
    }
    try {
        StringBuilder paramsBuilder = new StringBuilder();
        for (Entry<String, String> entry : paramsMap.entrySet()) {
            if (entry.getKey() == null || entry.getValue() == null) {
                continue;
            }
            paramsBuilder.append(URLEncoder.encode(entry.getKey(), charset.name()))
                .append("=")
                .append(URLEncoder.encode(entry.getValue(), charset.name()))
                .append("&");
        }
        if (paramsBuilder.length() > 0) {
            // Remove the last '&'.
            paramsBuilder.delete(paramsBuilder.length() - 1, paramsBuilder.length());
        }
        return paramsBuilder.toString();
    } catch (Throwable e) {
        RecordLog.warn("Encode request params fail", e);
        return "";
    }
}
 
Example 6
Source File: DefaultNode.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * Add child node to current node.
 *
 * @param node valid child node
 */
public void addChild(Node node) {
    if (node == null) {
        RecordLog.warn("Trying to add null child to node <{}>, ignored", id.getName());
        return;
    }
    if (!childList.contains(node)) {
        synchronized (this) {
            if (!childList.contains(node)) {
                Set<Node> newSet = new HashSet<>(childList.size() + 1);
                newSet.addAll(childList);
                newSet.add(node);
                childList = newSet;
            }
        }
        RecordLog.info("Add child <{}> to node <{}>", ((DefaultNode)node).id.getName(), id.getName());
    }
}
 
Example 7
Source File: SpiLoader.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
/**
 * Load the SPI instance list for provided SPI interface.
 *
 * @param clazz class of the SPI
 * @param <T>   SPI type
 * @return sorted SPI instance list
 * @since 1.6.0
 */
public static <T> List<T> loadInstanceList(Class<T> clazz) {
    try {
        String key = clazz.getName();
        // Not thread-safe, as it's expected to be resolved in a thread-safe context.
        ServiceLoader<T> serviceLoader = SERVICE_LOADER_MAP.get(key);
        if (serviceLoader == null) {
            serviceLoader = ServiceLoader.load(clazz);
            SERVICE_LOADER_MAP.put(key, serviceLoader);
        }

        List<T> list = new ArrayList<>();
        for (T spi : serviceLoader) {
            list.add(spi);
        }
        return list;
    } catch (Throwable t) {
        RecordLog.warn("[SpiLoader] ERROR: loadInstanceListSorted failed", t);
        t.printStackTrace();
        return new ArrayList<>();
    }
}
 
Example 8
Source File: ModifyClusterParamFlowRulesCommandHandler.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String namespace = request.getParam("namespace");
    if (StringUtil.isEmpty(namespace)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty namespace"));
    }
    String data = request.getParam("data");
    if (StringUtil.isBlank(data)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty data"));
    }
    try {
        data = URLDecoder.decode(data, "UTF-8");
        RecordLog.info("[ModifyClusterParamFlowRulesCommandHandler] Receiving cluster param rules for namespace <{0}>: {1}", namespace, data);

        List<ParamFlowRule> flowRules = JSONArray.parseArray(data, ParamFlowRule.class);
        ClusterParamFlowRuleManager.loadRules(namespace, flowRules);

        return CommandResponse.ofSuccess(SUCCESS);
    } catch (Exception e) {
        RecordLog.warn("[ModifyClusterParamFlowRulesCommandHandler] Decode cluster param rules error", e);
        return CommandResponse.ofFailure(e, "decode cluster param rules error");
    }
}
 
Example 9
Source File: SlotChainProvider.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * The load and pick process is not thread-safe, but it's okay since the method should be only invoked
 * via {@code lookProcessChain} in {@link com.alibaba.csp.sentinel.CtSph} under lock.
 *
 * @return new created slot chain
 */
public static ProcessorSlotChain newSlotChain() {
    if (slotChainBuilder != null) {
        return slotChainBuilder.build();
    }

    // Resolve the slot chain builder SPI.
    slotChainBuilder = SpiLoader.loadFirstInstanceOrDefault(SlotChainBuilder.class, DefaultSlotChainBuilder.class);

    if (slotChainBuilder == null) {
        // Should not go through here.
        RecordLog.warn("[SlotChainProvider] Wrong state when resolving slot chain builder, using default");
        slotChainBuilder = new DefaultSlotChainBuilder();
    } else {
        RecordLog.info("[SlotChainProvider] Global slot chain builder resolved: "
            + slotChainBuilder.getClass().getCanonicalName());
    }
    return slotChainBuilder.build();
}
 
Example 10
Source File: VersionUtil.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public static String getVersion(String defaultVersion) {
    try {
        String version = VersionUtil.class.getPackage().getImplementationVersion();
        return StringUtil.isBlank(version) ? defaultVersion : version;
    } catch (Throwable e) {
        RecordLog.warn("Using default version, ignore exception", e);
        return defaultVersion;
    }
}
 
Example 11
Source File: DefaultResponseEntityWriter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(ClusterResponse response, ByteBuf out) {
    int type = response.getType();
    EntityWriter<Object, ByteBuf> responseDataWriter = ResponseDataWriterRegistry.getWriter(type);

    if (responseDataWriter == null) {
        writeHead(response.setStatus(ClusterConstants.RESPONSE_STATUS_BAD), out);
        RecordLog.warn("[NettyResponseEncoder] Cannot find matching writer for type <{}>", response.getType());
        return;
    }
    writeHead(response, out);
    responseDataWriter.writeTo(response.getData(), out);
}
 
Example 12
Source File: MetricExtensionProvider.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private static void resolveInstance() {
    List<MetricExtension> extensions = SpiLoader.loadInstanceList(MetricExtension.class);

    if (extensions == null) {
        RecordLog.warn("[MetricExtensionProvider] WARN: No existing MetricExtension found");
    } else {
        metricExtensions.addAll(extensions);
        RecordLog.info("[MetricExtensionProvider] MetricExtension resolved, size=" + extensions.size());
    }
}
 
Example 13
Source File: DefaultRequestEntityWriter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(ClusterRequest request, ByteBuf target) {
    int type = request.getType();
    EntityWriter<Object, ByteBuf> requestDataWriter = RequestDataWriterRegistry.getWriter(type);

    if (requestDataWriter == null) {
        RecordLog.warn("[DefaultRequestEntityWriter] Cannot find matching request writer for type <{}>,"
            + " dropping the request", type);
        return;
    }
    // Write head part of request.
    writeHead(request, target);
    // Write data part.
    requestDataWriter.writeTo(request.getData(), target);
}
 
Example 14
Source File: ClusterServerConfigManager.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public void configLoad(ServerTransportConfig config) {
    if (config == null) {
        RecordLog.warn("[ClusterServerConfigManager] Empty initial server transport config");
        return;
    }
    applyConfig(config);
}
 
Example 15
Source File: ConsulDataSource.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void loadInitialConfig() {
    try {
        T newValue = loadConfig();
        if (newValue == null) {
            RecordLog.warn(
                "[ConsulDataSource] WARN: initial config is null, you may have to check your data source");
        }
        getProperty().updateValue(newValue);
    } catch (Exception ex) {
        RecordLog.warn("[ConsulDataSource] Error when loading initial config", ex);
    }
}
 
Example 16
Source File: ContextUtil.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * Not thread-safe, only for test.
 */
static void resetContextMap() {
    if (contextNameNodeMap != null) {
        RecordLog.warn("Context map cleared and reset to initial state");
        contextNameNodeMap.clear();
        initDefaultContext();
    }
}
 
Example 17
Source File: ContextUtil.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private static void setNullContext() {
    contextHolder.set(NULL_CONTEXT);
    // Don't need to be thread-safe.
    if (shouldWarn) {
        RecordLog.warn("[SentinelStatusChecker] WARN: Amount of context exceeds the threshold "
            + Constants.MAX_CONTEXT_NAME_SIZE + ". Entries in new contexts will NOT take effect!");
        shouldWarn = false;
    }
}
 
Example 18
Source File: ClusterServerConfigManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void configLoad(Set<String> set) {
    if (set == null || set.isEmpty()) {
        RecordLog.warn("[ClusterServerConfigManager] WARN: empty initial server namespace set");
        return;
    }
    applyNamespaceSetChange(set);
}
 
Example 19
Source File: ModifyParamFlowRulesCommandHandler.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Write target value to given data source.
 *
 * @param dataSource writable data source
 * @param value target value to save
 * @param <T> value type
 * @return true if write successful or data source is empty; false if error occurs
 */
private <T> boolean writeToDataSource(WritableDataSource<T> dataSource, T value) {
    if (dataSource != null) {
        try {
            dataSource.write(value);
        } catch (Exception e) {
            RecordLog.warn("Write data source failed", e);
            return false;
        }
    }
    return true;
}
 
Example 20
Source File: FlowRuleUtil.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
/**
 * Build the flow rule map from raw list of flow rules, grouping by provided group function.
 *
 * @param list          raw list of flow rules
 * @param groupFunction grouping function of the map (by key)
 * @param filter        rule filter
 * @param shouldSort    whether the rules should be sorted
 * @param <K>           type of key
 * @return constructed new flow rule map; empty map if list is null or empty, or no wanted rules
 */
public static <K> Map<K, List<FlowRule>> buildFlowRuleMap(List<FlowRule> list, Function<FlowRule, K> groupFunction,
                                                          Predicate<FlowRule> filter, boolean shouldSort) {
    Map<K, List<FlowRule>> newRuleMap = new ConcurrentHashMap<>();
    if (list == null || list.isEmpty()) {
        return newRuleMap;
    }
    Map<K, Set<FlowRule>> tmpMap = new ConcurrentHashMap<>();

    for (FlowRule rule : list) {
        if (!isValidRule(rule)) {
            RecordLog.warn("[FlowRuleManager] Ignoring invalid flow rule when loading new flow rules: " + rule);
            continue;
        }
        if (filter != null && !filter.test(rule)) {
            continue;
        }
        if (StringUtil.isBlank(rule.getLimitApp())) {
            rule.setLimitApp(RuleConstant.LIMIT_APP_DEFAULT);
        }

        TrafficShapingController rater = generateRater(rule);
        rule.setRater(rater);

        K key = groupFunction.apply(rule);
        if (key == null) {
            continue;
        }
        Set<FlowRule> flowRules = tmpMap.get(key);

        if (flowRules == null) {
            // Use hash set here to remove duplicate rules.
            flowRules = new HashSet<>();
            tmpMap.put(key, flowRules);
        }

        flowRules.add(rule);
    }
    Comparator<FlowRule> comparator = new FlowRuleComparator();
    for (Entry<K, Set<FlowRule>> entries : tmpMap.entrySet()) {
        List<FlowRule> rules = new ArrayList<>(entries.getValue());
        if (shouldSort) {
            // Sort the rules.
            Collections.sort(rules, comparator);
        }
        newRuleMap.put(entries.getKey(), rules);
    }

    return newRuleMap;
}