com.alibaba.csp.sentinel.util.AssertUtil Java Examples

The following examples show how to use com.alibaba.csp.sentinel.util.AssertUtil. 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: SentinelApiClient.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private CompletableFuture<Void> setRulesAsync(String app, String ip, int port, String type, List<? extends RuleEntity> entities) {
    try {
        AssertUtil.notNull(entities, "rules cannot be null");
        AssertUtil.notEmpty(app, "Bad app name");
        AssertUtil.notEmpty(ip, "Bad machine IP");
        AssertUtil.isTrue(port > 0, "Bad machine port");
        String data = JSON.toJSONString(
            entities.stream().map(r -> r.toRule()).collect(Collectors.toList()));
        Map<String, String> params = new HashMap<>(2);
        params.put("type", type);
        params.put("data", data);
        return executeCommand(app, ip, port, SET_RULES_PATH, params, true)
            .thenCompose(r -> {
                if ("success".equalsIgnoreCase(r.trim())) {
                    return CompletableFuture.completedFuture(null);
                }
                return AsyncUtils.newFailedFuture(new CommandFailedException(r));
            });
    } catch (Exception e) {
        logger.error("setRulesAsync API failed, type={}", type, e);
        return AsyncUtils.newFailedFuture(e);
    }
}
 
Example #2
Source File: FileInJarReadableDataSource.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
public FileInJarReadableDataSource(String jarName, String fileInJarName, Converter<String, T> configParser,
                                   int bufSize, Charset charset) throws IOException {
    super(configParser);
    AssertUtil.assertNotBlank(jarName, "jarName cannot be blank");
    AssertUtil.assertNotBlank(fileInJarName, "fileInJarName cannot be blank");
    if (bufSize <= 0 || bufSize > MAX_SIZE) {
        throw new IllegalArgumentException("bufSize must between (0, " + MAX_SIZE + "], but " + bufSize + " get");
    }
    AssertUtil.notNull(charset, "charset can't be null");
    this.buf = new byte[bufSize];
    this.charset = charset;
    this.jarName = jarName;
    this.fileInJarName = fileInJarName;
    initializeJar();
    firstLoad();
}
 
Example #3
Source File: ConnectionGroup.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
public ConnectionGroup addConnection(String address) {
    AssertUtil.notEmpty(address, "address cannot be empty");

    String[] ip = address.split(":");
    String host;
    if (ip != null && ip.length >= 1) {
        host = ip[0];
    } else {
        host = address;
    }
    boolean newAdded = connectionSet.add(new ConnectionDescriptor().setAddress(address).setHost(host));
    if (newAdded) {
        connectedCount.incrementAndGet();
    }

    return this;
}
 
Example #4
Source File: SentinelApiClient.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
public boolean modifyGatewayFlowRules(String app, String ip, int port, List<GatewayFlowRuleEntity> rules) {
    if (rules == null) {
        return true;
    }

    try {
        AssertUtil.notEmpty(app, "Bad app name");
        AssertUtil.notEmpty(ip, "Bad machine IP");
        AssertUtil.isTrue(port > 0, "Bad machine port");
        String data = JSON.toJSONString(
                rules.stream().map(r -> r.toGatewayFlowRule()).collect(Collectors.toList()));
        Map<String, String> params = new HashMap<>(2);
        params.put("data", data);
        String result = executeCommand(app, ip, port, MODIFY_GATEWAY_FLOW_RULE_PATH, params, true).get();
        logger.info("Modify gateway flow rules: {}", result);
        return true;
    } catch (Exception e) {
        logger.warn("Error when modifying gateway apis", e);
        return false;
    }
}
 
Example #5
Source File: ClusterFlowRuleManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
/**
 * Listen to the {@link SentinelProperty} for cluster {@link FlowRule}s.
 * The property is the source of cluster {@link FlowRule}s for a specific namespace.
 *
 * @param namespace namespace to register
 */
public static void register2Property(String namespace) {
    AssertUtil.notEmpty(namespace, "namespace cannot be empty");
    if (propertySupplier == null) {
        RecordLog.warn(
            "[ClusterFlowRuleManager] Cluster flow property supplier is absent, cannot register property");
        return;
    }
    SentinelProperty<List<FlowRule>> property = propertySupplier.apply(namespace);
    if (property == null) {
        RecordLog.warn(
            "[ClusterFlowRuleManager] Wrong created property from cluster flow property supplier, ignoring");
        return;
    }
    synchronized (UPDATE_LOCK) {
        RecordLog.info("[ClusterFlowRuleManager] Registering new property to cluster flow rule manager"
            + " for namespace <{0}>", namespace);
        registerPropertyInternal(namespace, property);
    }
}
 
Example #6
Source File: ClusterFlowRuleManager.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * Listen to the {@link SentinelProperty} for cluster {@link FlowRule}s.
 * The property is the source of cluster {@link FlowRule}s for a specific namespace.
 *
 * @param namespace namespace to register
 */
public static void register2Property(String namespace) {
    AssertUtil.notEmpty(namespace, "namespace cannot be empty");
    if (propertySupplier == null) {
        RecordLog.warn(
            "[ClusterFlowRuleManager] Cluster flow property supplier is absent, cannot register property");
        return;
    }
    SentinelProperty<List<FlowRule>> property = propertySupplier.apply(namespace);
    if (property == null) {
        RecordLog.warn(
            "[ClusterFlowRuleManager] Wrong created property from cluster flow property supplier, ignoring");
        return;
    }
    synchronized (UPDATE_LOCK) {
        RecordLog.info("[ClusterFlowRuleManager] Registering new property to cluster flow rule manager"
            + " for namespace <{}>", namespace);
        registerPropertyInternal(namespace, property);
    }
}
 
Example #7
Source File: FileInJarReadableDataSource.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
public FileInJarReadableDataSource(String jarName, String fileInJarName, Converter<String, T> configParser,
                                   int bufSize, Charset charset) throws IOException {
    super(configParser);
    AssertUtil.assertNotBlank(jarName, "jarName cannot be blank");
    AssertUtil.assertNotBlank(fileInJarName, "fileInJarName cannot be blank");
    if (bufSize <= 0 || bufSize > MAX_SIZE) {
        throw new IllegalArgumentException("bufSize must between (0, " + MAX_SIZE + "], but " + bufSize + " get");
    }
    AssertUtil.notNull(charset, "charset can't be null");
    this.buf = new byte[bufSize];
    this.charset = charset;
    this.jarName = jarName;
    this.fileInJarName = fileInJarName;
    initializeJar();
    firstLoad();
}
 
Example #8
Source File: RedisDataSource.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor of {@code RedisDataSource}.
 *
 * @param connectionConfig Redis connection config
 * @param ruleKey          data key in Redis
 * @param channel          channel to subscribe in Redis
 * @param parser           customized data parser, cannot be empty
 */
public RedisDataSource(RedisConnectionConfig connectionConfig, String ruleKey, String channel,
                       Converter<String, T> parser) {
    super(parser);
    AssertUtil.notNull(connectionConfig, "Redis connection config can not be null");
    AssertUtil.notEmpty(ruleKey, "Redis ruleKey can not be empty");
    AssertUtil.notEmpty(channel, "Redis subscribe channel can not be empty");
    this.redisClient = getRedisClient(connectionConfig);
    this.ruleKey = ruleKey;
    loadInitialConfig();
    subscribeFromChannel(channel);
}
 
Example #9
Source File: RedisConnectionConfig.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * Set Sentinel host and port. Creates a new builder.
 *
 * @param host the host name
 * @param port the port
 * @return New builder with Sentinel host/port.
 */
public static RedisConnectionConfig.Builder redisSentinel(String host, int port) {

    AssertUtil.notEmpty(host, "Host must not be empty");
    AssertUtil.isTrue(isValidPort(port), String.format("Port out of range: %s", port));

    RedisConnectionConfig.Builder builder = RedisConnectionConfig.builder();
    return builder.withRedisSentinel(host, port);
}
 
Example #10
Source File: ZuulBlockFallbackManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Register special provider for different route.
 */
public static synchronized void registerProvider(ZuulBlockFallbackProvider provider) {
    AssertUtil.notNull(provider, "fallback provider cannot be null");
    String route = provider.getRoute();
    if ("*".equals(route) || route == null) {
        defaultFallbackProvider = provider;
    } else {
        fallbackProviderCache.put(route, provider);
    }
}
 
Example #11
Source File: InMemoryRuleRepositoryAdapter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public List<T> findAllByApp(String appName) {
    AssertUtil.notEmpty(appName, "appName cannot be empty");
    Map<Long, T> entities = appRules.get(appName);
    if (entities == null) {
        return new ArrayList<>();
    }
    return new ArrayList<>(entities.values());
}
 
Example #12
Source File: ClusterServerConfigManager.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * Register cluster server global statistic (flow) configuration dynamic property.
 *
 * @param property server flow configuration dynamic property
 */
public static void registerGlobalServerFlowProperty(SentinelProperty<ServerFlowConfig> property) {
    AssertUtil.notNull(property, "cluster server flow config dynamic property cannot be null");
    synchronized (GLOBAL_FLOW_PROPERTY_LISTENER) {
        RecordLog.info(
            "[ClusterServerConfigManager] Registering new server global flow dynamic property "
                + "to Sentinel server config manager");
        globalFlowProperty.removeListener(GLOBAL_FLOW_PROPERTY_LISTENER);
        property.addListener(GLOBAL_FLOW_PROPERTY_LISTENER);
        globalFlowProperty = property;
    }
}
 
Example #13
Source File: RedisConnectionConfig.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Set Redis host and port. Creates a new builder
 *
 * @param host the host name
 * @param port the port
 * @return New builder with Redis host/port.
 */
public static RedisConnectionConfig.Builder redis(String host, int port) {

    AssertUtil.notEmpty(host, "Host must not be empty");
    AssertUtil.isTrue(isValidPort(port), String.format("Port out of range: %s", port));

    Builder builder = RedisConnectionConfig.builder();
    return builder.withHost(host).withPort(port);
}
 
Example #14
Source File: EnvoyRlsRuleManager.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * Listen to the {@link SentinelProperty} for Envoy RLS rules. The property is the source of {@link EnvoyRlsRule}.
 *
 * @param property the property to listen
 */
public static void register2Property(SentinelProperty<List<EnvoyRlsRule>> property) {
    AssertUtil.notNull(property, "property cannot be null");
    synchronized (PROPERTY_LISTENER) {
        RecordLog.info("[EnvoyRlsRuleManager] Registering new property to Envoy rate limit service rule manager");
        currentProperty.removeListener(PROPERTY_LISTENER);
        property.addListener(PROPERTY_LISTENER);
        currentProperty = property;
    }
}
 
Example #15
Source File: SentinelApiClient.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch all authority rules from provided machine.
 *
 * @param app  application name
 * @param ip   machine client IP
 * @param port machine client port
 * @return all retrieved authority rules
 * @since 0.2.1
 */
public List<AuthorityRuleEntity> fetchAuthorityRulesOfMachine(String app, String ip, int port) {
    AssertUtil.notEmpty(app, "Bad app name");
    AssertUtil.notEmpty(ip, "Bad machine IP");
    AssertUtil.isTrue(port > 0, "Bad machine port");
    Map<String, String> params = new HashMap<>(1);
    params.put("type", AUTHORITY_TYPE);
    List<AuthorityRule> rules = fetchRules(ip, port, AUTHORITY_TYPE, AuthorityRule.class);
    return Optional.ofNullable(rules).map(r -> r.stream()
                .map(e -> AuthorityRuleEntity.fromAuthorityRule(app, ip, port, e))
                .collect(Collectors.toList())
            ).orElse(null);
}
 
Example #16
Source File: ClusterAssignServiceImpl.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public ClusterAppAssignResultVO unbindClusterServers(String app, Set<String> machineIdSet) {
    AssertUtil.assertNotBlank(app, "app cannot be blank");
    AssertUtil.isTrue(machineIdSet != null && !machineIdSet.isEmpty(), "machineIdSet cannot be empty");
    ClusterAppAssignResultVO result = new ClusterAppAssignResultVO()
        .setFailedClientSet(new HashSet<>())
        .setFailedServerSet(new HashSet<>());
    for (String machineId : machineIdSet) {
        ClusterAppAssignResultVO resultVO = unbindClusterServer(app, machineId);
        result.getFailedClientSet().addAll(resultVO.getFailedClientSet());
        result.getFailedServerSet().addAll(resultVO.getFailedServerSet());
    }
    return result;
}
 
Example #17
Source File: ClusterAssignServiceImpl.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public ClusterAppAssignResultVO applyAssignToApp(String app, List<ClusterAppAssignMap> clusterMap,
                                                 Set<String> remainingSet) {
    AssertUtil.assertNotBlank(app, "app cannot be blank");
    AssertUtil.notNull(clusterMap, "clusterMap cannot be null");
    Set<String> failedServerSet = new HashSet<>();
    Set<String> failedClientSet = new HashSet<>();

    // Assign server and apply config.
    clusterMap.stream()
        .filter(Objects::nonNull)
        .filter(ClusterAppAssignMap::getBelongToApp)
        .map(e -> {
            String ip = e.getIp();
            int commandPort = parsePort(e);
            CompletableFuture<Void> f = modifyMode(ip, commandPort, ClusterStateManager.CLUSTER_SERVER)
                .thenCompose(v -> applyServerConfigChange(app, ip, commandPort, e));
            return Tuple2.of(e.getMachineId(), f);
        })
        .forEach(t -> handleFutureSync(t, failedServerSet));

    // Assign client of servers and apply config.
    clusterMap.parallelStream()
        .filter(Objects::nonNull)
        .forEach(e -> applyAllClientConfigChange(app, e, failedClientSet));

    // Unbind remaining (unassigned) machines.
    applyAllRemainingMachineSet(app, remainingSet, failedClientSet);

    return new ClusterAppAssignResultVO()
        .setFailedClientSet(failedClientSet)
        .setFailedServerSet(failedServerSet);
}
 
Example #18
Source File: AbstractApiMatcher.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public AbstractApiMatcher(ApiDefinition apiDefinition) {
    AssertUtil.notNull(apiDefinition, "apiDefinition cannot be null");
    AssertUtil.assertNotBlank(apiDefinition.getApiName(), "apiName cannot be empty");
    this.apiName = apiDefinition.getApiName();
    this.apiDefinition = apiDefinition;

    try {
        initializeMatchers();
    } catch (Exception ex) {
        RecordLog.warn("[GatewayApiMatcher] Failed to initialize internal matchers", ex);
    }
}
 
Example #19
Source File: DegradeRuleManager.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * Listen to the {@link SentinelProperty} for {@link DegradeRule}s. The property is the source
 * of {@link DegradeRule}s. Degrade rules can also be set by {@link #loadRules(List)} directly.
 *
 * @param property the property to listen.
 */
public static void register2Property(SentinelProperty<List<DegradeRule>> property) {
    AssertUtil.notNull(property, "property cannot be null");
    synchronized (LISTENER) {
        RecordLog.info("[DegradeRuleManager] Registering new property to degrade rule manager");
        currentProperty.removeListener(LISTENER);
        property.addListener(LISTENER);
        currentProperty = property;
    }
}
 
Example #20
Source File: ClusterMetricStatistics.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public static boolean putMetricIfAbsent(long id, ClusterMetric metric) {
    AssertUtil.notNull(metric, "Cluster metric cannot be null");
    if (METRIC_MAP.containsKey(id)) {
        return false;
    }
    METRIC_MAP.put(id, metric);
    return true;
}
 
Example #21
Source File: RedisConnectionConfig.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * Set Sentinel host, port and master id. Creates a new builder.
 *
 * @param host     the host name
 * @param port     the port
 * @param masterId redisSentinel master id
 * @return New builder with Sentinel host/port.
 */
public static RedisConnectionConfig.Builder redisSentinel(String host, int port, String masterId) {

    AssertUtil.notEmpty(host, "Host must not be empty");
    AssertUtil.isTrue(isValidPort(port), String.format("Port out of range: %s", port));

    RedisConnectionConfig.Builder builder = RedisConnectionConfig.builder();
    return builder.withSentinelMasterId(masterId).withRedisSentinel(host, port);
}
 
Example #22
Source File: ClusterFlowRuleManager.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * Listen to the {@link SentinelProperty} for cluster {@link FlowRule}s if current property for namespace is absent.
 * The property is the source of cluster {@link FlowRule}s for a specific namespace.
 *
 * @param namespace namespace to register
 */
public static void registerPropertyIfAbsent(String namespace) {
    AssertUtil.notEmpty(namespace, "namespace cannot be empty");
    if (!PROPERTY_MAP.containsKey(namespace)) {
        synchronized (UPDATE_LOCK) {
            if (!PROPERTY_MAP.containsKey(namespace)) {
                register2Property(namespace);
            }
        }
    }
}
 
Example #23
Source File: ParamMapBucket.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public ParamMapBucket(int capacity) {
    AssertUtil.isTrue(capacity > 0, "capacity should be positive");
    RollingParamEvent[] events = RollingParamEvent.values();
    this.data = new CacheMap[events.length];
    for (RollingParamEvent event : events) {
        data[event.ordinal()] = new ConcurrentLinkedHashMapWrapper<Object, AtomicInteger>(capacity);
    }
}
 
Example #24
Source File: ClusterServerConfigManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Register cluster server transport configuration dynamic property.
 *
 * @param property server transport configuration dynamic property
 */
public static void registerServerTransportProperty(SentinelProperty<ServerTransportConfig> property) {
    AssertUtil.notNull(property, "cluster server transport config dynamic property cannot be null");
    synchronized (TRANSPORT_PROPERTY_LISTENER) {
        RecordLog.info(
            "[ClusterServerConfigManager] Registering new server transport dynamic property to Sentinel server "
                + "config manager");
        transportConfigProperty.removeListener(TRANSPORT_PROPERTY_LISTENER);
        property.addListener(TRANSPORT_PROPERTY_LISTENER);
        transportConfigProperty = property;
    }
}
 
Example #25
Source File: ClusterServerConfigManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Register cluster server namespace set dynamic property.
 *
 * @param property server namespace set dynamic property
 */
public static void registerNamespaceSetProperty(SentinelProperty<Set<String>> property) {
    AssertUtil.notNull(property, "namespace set dynamic property cannot be null");
    synchronized (NAMESPACE_SET_PROPERTY_LISTENER) {
        RecordLog.info(
            "[ClusterServerConfigManager] Registering new namespace set dynamic property to Sentinel server "
                + "config manager");
        namespaceSetProperty.removeListener(NAMESPACE_SET_PROPERTY_LISTENER);
        property.addListener(NAMESPACE_SET_PROPERTY_LISTENER);
        namespaceSetProperty = property;
    }
}
 
Example #26
Source File: ClusterServerConfigManager.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public static double getMaxAllowedQps(String namespace) {
    AssertUtil.notEmpty(namespace, "namespace cannot be empty");
    ServerFlowConfig config = NAMESPACE_CONF.get(namespace);
    if (config != null) {
        return config.getMaxAllowedQps();
    }
    return maxAllowedQps;
}
 
Example #27
Source File: RedisConnectionConfig.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Configures a redisSentinel master Id.
 *
 * @param sentinelMasterId redisSentinel master id, must not be empty or {@literal null}
 * @return the builder
 */
public RedisConnectionConfig.Builder withSentinelMasterId(String sentinelMasterId) {

    AssertUtil.notEmpty(sentinelMasterId, "Sentinel master id must not empty");

    this.redisSentinelMasterId = sentinelMasterId;
    return this;
}
 
Example #28
Source File: RedisConnectionConfig.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Add a withRedisSentinel host/port to the existing builder.
 *
 * @param host the host name
 * @param port the port
 * @return the builder
 */
public RedisConnectionConfig.Builder withRedisSentinel(String host, int port) {

    AssertUtil.assertState(this.host == null, "Cannot use with Redis mode.");
    AssertUtil.notEmpty(host, "Host must not be empty");
    AssertUtil.isTrue(isValidPort(port), String.format("Port out of range: %s", port));

    redisSentinels.add(RedisHostAndPort.of(host, port));
    return this;
}
 
Example #29
Source File: GlobalRequestLimiter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public static void applyMaxQpsChange(double maxAllowedQps) {
    AssertUtil.isTrue(maxAllowedQps >= 0, "max allowed QPS should > 0");
    for (RequestLimiter limiter : GLOBAL_QPS_LIMITER_MAP.values()) {
        if (limiter != null) {
            limiter.setQpsAllowed(maxAllowedQps);
        }
    }
}
 
Example #30
Source File: ClusterAssignServiceImpl.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public ClusterAppAssignResultVO unbindClusterServer(String app, String machineId) {
    AssertUtil.assertNotBlank(app, "app cannot be blank");
    AssertUtil.assertNotBlank(machineId, "machineId cannot be blank");

    if (isMachineInApp(machineId)) {
        return handleUnbindClusterServerNotInApp(app, machineId);
    }
    Set<String> failedSet = new HashSet<>();
    try {
        ClusterGroupEntity entity = clusterConfigService.getClusterUniversalStateForAppMachine(app, machineId)
            .get(10, TimeUnit.SECONDS);
        Set<String> toModifySet = new HashSet<>();
        toModifySet.add(machineId);
        if (entity.getClientSet() != null) {
            toModifySet.addAll(entity.getClientSet());
        }
        // Modify mode to NOT-STARTED for all chosen token servers and associated token clients.
        modifyToNonStarted(toModifySet, failedSet);
    } catch (Exception ex) {
        Throwable e = ex instanceof ExecutionException ? ex.getCause() : ex;
        LOGGER.error("Failed to unbind machine <{}>", machineId, e);
        failedSet.add(machineId);
    }
    return new ClusterAppAssignResultVO()
        .setFailedClientSet(failedSet)
        .setFailedServerSet(new HashSet<>());
}