Merge branch 'v2.0.5_dev' into 'master'

V2.0.5 dev

See merge request DDOSAQ/phoenix_ddos_handle!15
This commit is contained in:
黄昕 2021-01-25 17:45:52 +08:00
commit eea1a67ade
77 changed files with 3542 additions and 280 deletions

View File

@ -2,7 +2,7 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2" xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd"> xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>assembly</id> <id>${project.version}</id>
<formats> <formats>
<format>tgz</format> <format>tgz</format>
</formats> </formats>
@ -11,7 +11,7 @@
<directory>${project.build.directory}</directory> <directory>${project.build.directory}</directory>
<outputDirectory>${file.separator}</outputDirectory> <outputDirectory>${file.separator}</outputDirectory>
<includes> <includes>
<include>phoenix_ddos_handle.jar</include> <include>dispose_platform.jar</include>
</includes> </includes>
</fileSet> </fileSet>
<fileSet> <fileSet>

View File

@ -3,7 +3,7 @@
# processor_check.sh脚本内容如下 # processor_check.sh脚本内容如下
#!/bin/bash #!/bin/bash
APP_NAME=phoenix_ddos_handle.jar APP_NAME=dispose_platform.jar
WORK_PATH=$(cd `dirname $0`; pwd) WORK_PATH=$(cd `dirname $0`; pwd)
pids=`ps -ef | grep $APP_NAME | grep -v grep | wc -l` pids=`ps -ef | grep $APP_NAME | grep -v grep | wc -l`

View File

@ -5,4 +5,4 @@ JAVA_OPTS="-Djava.security.egd=file:/dev/./urandom -server -Xms512M -Xmx512M -X
WORK_PATH=$(cd `dirname $0`; pwd) WORK_PATH=$(cd `dirname $0`; pwd)
cd $WORK_PATH cd $WORK_PATH
cd .. cd ..
$JAVA_HOME/bin/java $JAVA_DEBUG_OPTS $JAVA_JMX_OPTS $JAVA_OPTS -jar phoenix_ddos_handle.jar & $JAVA_HOME/bin/java $JAVA_DEBUG_OPTS $JAVA_JMX_OPTS $JAVA_OPTS -jar dispose_platform.jar &

View File

@ -1,5 +1,5 @@
#!/bin/bash #!/bin/bash
APP_NAME=phoenix_ddos_handle.jar APP_NAME=dispose_platform.jar
pids=`ps -ef | grep $APP_NAME | grep -v grep | awk '{print $2}'` pids=`ps -ef | grep $APP_NAME | grep -v grep | awk '{print $2}'`
for pid in $pids for pid in $pids

View File

@ -0,0 +1,46 @@
#模板配置
template.umcTemplate[0].name=Game_Server_10G
template.umcTemplate[0].bandMin=1500
template.umcTemplate[0].bandMax=-1
template.umcTemplate[0].type=GAME
template.umcTemplate[1].name=Game_Server_1G
template.umcTemplate[1].bandMin=0
template.umcTemplate[1].bandMax=1500
template.umcTemplate[1].type=GAME
template.umcTemplate[2].name=DNS_Server_10G
template.umcTemplate[2].bandMin=1500
template.umcTemplate[2].bandMax=-1
template.umcTemplate[2].type=DNS
template.umcTemplate[3].name=DNS_Server_1G
template.umcTemplate[3].bandMin=0
template.umcTemplate[3].bandMax=1500
template.umcTemplate[3].type=DNS
template.umcTemplate[4].name=WEB_Server_10G
template.umcTemplate[4].bandMin=1500
template.umcTemplate[4].bandMax=-1
template.umcTemplate[4].type=WEB
template.umcTemplate[5].name=WEB_Server_1G
template.umcTemplate[5].bandMin=0
template.umcTemplate[5].bandMax=1500
template.umcTemplate[5].type=WEB
template.umcTemplate[6].name=General_Server_10G
template.umcTemplate[6].bandMin=1500
template.umcTemplate[6].bandMax=-1
template.umcTemplate[6].type=GENERAL
template.umcTemplate[7].name=General_Server_1G
template.umcTemplate[7].bandMin=500
template.umcTemplate[7].bandMax=1500
template.umcTemplate[7].type=GENERAL
template.umcTemplate[8].name=General_Server_100M
template.umcTemplate[8].bandMin=0
template.umcTemplate[8].bandMax=500
template.umcTemplate[8].type=GENERAL

View File

@ -1 +1 @@
spring.profiles.active=local,dispose spring.profiles.active=local,dispose,template

12
pom.xml
View File

@ -8,18 +8,18 @@
<spring-cloud.version>Greenwich.SR3</spring-cloud.version> <spring-cloud.version>Greenwich.SR3</spring-cloud.version>
<undertow.version>2.1.3.Final</undertow.version> <undertow.version>2.1.3.Final</undertow.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.framework.version>2.3.4.RELEASE</spring.framework.version> <spring.framework.version>2.3.8.RELEASE</spring.framework.version>
</properties> </properties>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version> <version>2.3.8.RELEASE</version>
<relativePath/> <relativePath/>
</parent> </parent>
<groupId>com.dispose</groupId> <groupId>com.dispose</groupId>
<artifactId>phoenix_ddos_handle</artifactId> <artifactId>dispose_platform</artifactId>
<version>2.0.3</version> <version>2.0.5</version>
<name>phoenix_ddos_handle</name> <name>dispose_platform</name>
<description>Dispose Platform</description> <description>Dispose Platform</description>
<dependencies> <dependencies>
<dependency> <dependency>
@ -219,7 +219,7 @@
</dependencies> </dependencies>
<build> <build>
<finalName>phoenix_ddos_handle</finalName> <finalName>dispose_platform</finalName>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>

View File

@ -4,10 +4,12 @@ import com.dispose.common.DisposeCapacityType;
import com.dispose.common.DisposeObjectType; import com.dispose.common.DisposeObjectType;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.NetflowDirection; import com.dispose.common.NetflowDirection;
import com.dispose.pojo.entity.ServiceInfo;
import com.dispose.pojo.po.MulReturnType; import com.dispose.pojo.po.MulReturnType;
import com.dispose.pojo.vo.DeviceFirewareInfo; import com.dispose.pojo.vo.DeviceFirewareInfo;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.List;
/** /**
* The interface Dispose ability. * The interface Dispose ability.
@ -98,4 +100,31 @@ public interface DisposeAbility {
* @return the boolean * @return the boolean
*/ */
boolean isCarryProtectIp(String ipAddr); boolean isCarryProtectIp(String ipAddr);
/**
* Is carry attack type boolean.
*
* @param attackType the attack type
* @return the boolean
*/
boolean isCarryAttackType(Long attackType);
/**
* Period task runtime.
*/
void periodTaskRuntime();
/**
* Device ready boolean.
*
* @return the boolean
*/
boolean deviceReady();
/**
* Upgrade service group.
*
* @param svrList the svr list
*/
void upgradeServiceGroup(List<ServiceInfo> svrList);
} }

View File

@ -2,13 +2,16 @@ package com.dispose.ability.impl;
import com.dispose.ability.DisposeAbility; import com.dispose.ability.DisposeAbility;
import com.dispose.common.CommonEnumHandler; import com.dispose.common.CommonEnumHandler;
import com.dispose.common.DDoSAttackType;
import com.dispose.common.DisposeCapacityType; import com.dispose.common.DisposeCapacityType;
import com.dispose.common.DisposeConfigValue;
import com.dispose.common.DisposeObjectType; import com.dispose.common.DisposeObjectType;
import com.dispose.common.DpTechAttackType; import com.dispose.common.DpTechAttackType;
import com.dispose.common.DpTechConfigValue; import com.dispose.common.DpTechConfigValue;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.Helper; import com.dispose.common.Helper;
import com.dispose.common.NetflowDirection; import com.dispose.common.NetflowDirection;
import com.dispose.pojo.entity.ServiceInfo;
import com.dispose.pojo.po.MulReturnType; import com.dispose.pojo.po.MulReturnType;
import com.dispose.pojo.vo.DeviceFirewareInfo; import com.dispose.pojo.vo.DeviceFirewareInfo;
import com.dptech.dispose.AbnormalFlowCleaningServicePortType; import com.dptech.dispose.AbnormalFlowCleaningServicePortType;
@ -48,12 +51,29 @@ public class DpTechAbilityImpl implements DisposeAbility {
* The Protect ip v 6. * The Protect ip v 6.
*/ */
private final List<String> protectIpV6 = new ArrayList<>(); private final List<String> protectIpV6 = new ArrayList<>();
/**
* The Timer cnt.
*/
private long timerCnt = 0;
/**
* The Device link status.
*/
private boolean deviceLinkStatus = false;
/** /**
* The Clean type port. * The Clean type port.
*/ */
private AbnormalFlowCleaningServicePortType cleanTypePort; private AbnormalFlowCleaningServicePortType cleanTypePort;
/**
* Gets clean type port.
*
* @return the clean type port
*/
public AbnormalFlowCleaningServicePortType getCleanTypePort() {
return cleanTypePort;
}
/** /**
* Init device env. * Init device env.
* *
@ -107,7 +127,8 @@ public class DpTechAbilityImpl implements DisposeAbility {
* @return the mul return type * @return the mul return type
*/ */
@Override @Override
public MulReturnType<ErrorCode, String> runDispose(String disposeObject, DisposeObjectType objectType, DisposeCapacityType capType, public MulReturnType<ErrorCode, String> runDispose(String disposeObject, DisposeObjectType objectType,
DisposeCapacityType capType,
NetflowDirection nfDirection, NetflowDirection nfDirection,
Integer attackType, Integer attackType,
Long duration) { Long duration) {
@ -205,15 +226,23 @@ public class DpTechAbilityImpl implements DisposeAbility {
*/ */
@Override @Override
public boolean getDeviceLinkStatus() { public boolean getDeviceLinkStatus() {
return deviceLinkStatus;
}
/**
* Dev get link status.
*/
private void devGetLinkStatus() {
try { try {
// 获取防护对象接口调用成功认为设备心跳正常 // 获取防护对象接口调用成功认为设备心跳正常
cleanTypePort.getAllProtectionObjectFromUMC().getProtectionObjectDataForService(); cleanTypePort.getAllProtectionObjectFromUMC().getProtectionObjectDataForService();
return true; deviceLinkStatus = true;
} catch (Exception ex) { } catch (Exception ex) {
log.error(ex.getMessage()); log.error(ex.getMessage());
} }
return false; deviceLinkStatus = false;
} }
/** /**
@ -246,7 +275,7 @@ public class DpTechAbilityImpl implements DisposeAbility {
*/ */
@Override @Override
public Long toDeviceAttackType(Long ddosAttackTypeMask) { public Long toDeviceAttackType(Long ddosAttackTypeMask) {
return DpTechAttackType.formDdosAttackTypeMaks(ddosAttackTypeMask); return DpTechAttackType.getTypeMaskFromAttackType(new DpTechAttackType[] {DpTechAttackType.UDP_FLOOD});
} }
/** /**
@ -327,4 +356,55 @@ public class DpTechAbilityImpl implements DisposeAbility {
public MulReturnType<ErrorCode, Long> taskStatus(String taskId) { public MulReturnType<ErrorCode, Long> taskStatus(String taskId) {
return new MulReturnType<>(ErrorCode.ERR_UNSUPPORT, -1L); return new MulReturnType<>(ErrorCode.ERR_UNSUPPORT, -1L);
} }
/**
* Period task runtime.
*/
@Override
public void periodTaskRuntime() {
log.debug("++++DpTech Period Task Running");
if (timerCnt++ % DpTechConfigValue.PROTECTION_UPGRADE_PERIOD == 0) {
// 定时检测防护对象
getDisposeDeviceProtectObject();
}
// 更新心跳状态
if (timerCnt++ % DisposeConfigValue.HEART_PERIOD_OF_SECOND == 0) {
devGetLinkStatus();
}
log.debug("----DpTech Period Task Running");
}
/**
* Device ready boolean.
*
* @return the boolean
*/
@Override
public boolean deviceReady() {
return true;
}
/**
* Upgrade service group.
*
* @param svrList the svr list
*/
@Override
public void upgradeServiceGroup(List<ServiceInfo> svrList) {
}
/**
* Is carry attack type boolean.
*
* @param attackType the attack type
* @return the boolean
*/
@Override
public boolean isCarryAttackType(Long attackType) {
return !DDoSAttackType.maskToDdosAttackType(attackType).contains(DDoSAttackType.NONE_ATTACKS);
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -2,9 +2,11 @@ package com.dispose.ability.impl;
import com.dispose.ability.DisposeAbility; import com.dispose.ability.DisposeAbility;
import com.dispose.common.DisposeCapacityType; import com.dispose.common.DisposeCapacityType;
import com.dispose.common.DisposeConfigValue;
import com.dispose.common.DisposeObjectType; import com.dispose.common.DisposeObjectType;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.NetflowDirection; import com.dispose.common.NetflowDirection;
import com.dispose.pojo.entity.ServiceInfo;
import com.dispose.pojo.po.MulReturnType; import com.dispose.pojo.po.MulReturnType;
import com.dispose.pojo.vo.DeviceFirewareInfo; import com.dispose.pojo.vo.DeviceFirewareInfo;
import com.haohan.dispose.common.HaoHanStartCleanResp; import com.haohan.dispose.common.HaoHanStartCleanResp;
@ -16,6 +18,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.List;
/** /**
* The type Hao han ability. * The type Hao han ability.
@ -38,6 +41,14 @@ public class HaoHanAbilityImpl implements DisposeAbility {
* The Url root path. * The Url root path.
*/ */
private String urlRootPath; private String urlRootPath;
/**
* The Timer cnt.
*/
private long timerCnt = 0;
/**
* The Device link status.
*/
private boolean deviceLinkStatus = false;
/** /**
* Init device env. * Init device env.
@ -153,14 +164,23 @@ public class HaoHanAbilityImpl implements DisposeAbility {
*/ */
@Override @Override
public boolean getDeviceLinkStatus() { public boolean getDeviceLinkStatus() {
return deviceLinkStatus;
}
/**
* Dev get link status.
*/
private void devGetLinkStatus() {
try { try {
// 获取任务信息接口调用成功认为设备心跳正常 // 获取任务信息接口调用成功认为设备心跳正常
return (restfulInterface.getCleanTaskStatus(this.urlRootPath, -1) != null); if (restfulInterface.getCleanTaskStatus(this.urlRootPath, -1) != null) {
deviceLinkStatus = true;
}
} catch (Exception ex) { } catch (Exception ex) {
log.error(ex.getMessage()); log.error(ex.getMessage());
} }
return false; deviceLinkStatus = false;
} }
/** /**
@ -225,4 +245,49 @@ public class HaoHanAbilityImpl implements DisposeAbility {
public MulReturnType<ErrorCode, Long> taskStatus(String taskId) { public MulReturnType<ErrorCode, Long> taskStatus(String taskId) {
return new MulReturnType<>(ErrorCode.ERR_UNSUPPORT, -1L); return new MulReturnType<>(ErrorCode.ERR_UNSUPPORT, -1L);
} }
/**
* Period task runtime.
*/
@Override
public void periodTaskRuntime() {
log.debug("++++HaoHan Period Task Running");
// 更新心跳状态
if (timerCnt++ % DisposeConfigValue.HEART_PERIOD_OF_SECOND == 0) {
devGetLinkStatus();
}
log.debug("----HaoHan Period Task Running");
}
/**
* Device ready boolean.
*
* @return the boolean
*/
@Override
public boolean deviceReady() {
return true;
}
/**
* Upgrade service group.
*
* @param svrList the svr list
*/
@Override
public void upgradeServiceGroup(List<ServiceInfo> svrList) {
}
/**
* Is carry attack type boolean.
*
* @param attackType the attack type
* @return the boolean
*/
@Override
public boolean isCarryAttackType(Long attackType) {
return true;
}
} }

View File

@ -3,9 +3,11 @@ package com.dispose.ability.impl;
import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpResponse;
import com.dispose.ability.DisposeAbility; import com.dispose.ability.DisposeAbility;
import com.dispose.common.DisposeCapacityType; import com.dispose.common.DisposeCapacityType;
import com.dispose.common.DisposeConfigValue;
import com.dispose.common.DisposeObjectType; import com.dispose.common.DisposeObjectType;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.NetflowDirection; import com.dispose.common.NetflowDirection;
import com.dispose.pojo.entity.ServiceInfo;
import com.dispose.pojo.po.MulReturnType; import com.dispose.pojo.po.MulReturnType;
import com.dispose.pojo.vo.DeviceFirewareInfo; import com.dispose.pojo.vo.DeviceFirewareInfo;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
@ -20,6 +22,7 @@ import org.springframework.stereotype.Component;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.util.List;
/** /**
* The type Hua wei ability. * The type Hua wei ability.
@ -29,16 +32,22 @@ import javax.servlet.http.HttpServletResponse;
@Component @Component
@Slf4j @Slf4j
public class HuaWeiAbilityImpl implements DisposeAbility { public class HuaWeiAbilityImpl implements DisposeAbility {
/**
* The Restful interface.
*/
private final HuaWeiInterface restfulInterface = new HuaWeiInterface();
/** /**
* The constant OBJECT_MAPPER. * The constant OBJECT_MAPPER.
*/ */
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
/**
* The Restful interface.
*/
private final HuaWeiInterface restfulInterface = new HuaWeiInterface();
/**
* The Timer cnt.
*/
private long timerCnt = 0;
/**
* The Device link status.
*/
private boolean deviceLinkStatus = false;
/** /**
* The Url root path. * The Url root path.
*/ */
@ -105,7 +114,7 @@ public class HuaWeiAbilityImpl implements DisposeAbility {
if (addr.isIPv4()) { if (addr.isIPv4()) {
disposeObj = disposeObject + "/32"; disposeObj = disposeObject + "/32";
}else if(addr.isIPv6()) { } else if (addr.isIPv6()) {
disposeObj = disposeObject + "/128"; disposeObj = disposeObject + "/128";
} }
@ -136,14 +145,18 @@ public class HuaWeiAbilityImpl implements DisposeAbility {
} }
if (resp != ErrorCode.ERR_OK) { if (resp != ErrorCode.ERR_OK) {
log.error("----Error HuaWei start clean {} return error: {}, {}", disposeObject, resp.getCode(), resp.getMsg()); log.error("----Error HuaWei start clean {} return error: {}, {}", disposeObject, resp.getCode(),
resp.getMsg());
return new MulReturnType<>(ErrorCode.ERR_HUAWEI_ERROR, null); return new MulReturnType<>(ErrorCode.ERR_HUAWEI_ERROR, null);
} }
log.debug("----Finish HuaWei Start Cleanup Task: {}", disposeObject); log.info("----Finish HuaWei Start Cleanup Task: {}", disposeObject);
return new MulReturnType<>(ErrorCode.ERR_OK, null); return new MulReturnType<>(ErrorCode.ERR_OK, null);
} catch (Exception ex) { } catch (Exception ex) {
log.error("----Exception HuaWei Start Cleanup Task: {}, {}, {}", disposeObject, nfDirection, duration); log.error("----Exception HuaWei Start Cleanup Task [{}]: {}, {}, {}, {}, {}", ex.getMessage(),
disposeObject,
nfDirection,
duration, url, token);
return new MulReturnType<>(ErrorCode.ERR_SYSTEMEXCEPTION, null); return new MulReturnType<>(ErrorCode.ERR_SYSTEMEXCEPTION, null);
} }
} }
@ -170,7 +183,7 @@ public class HuaWeiAbilityImpl implements DisposeAbility {
if (addr.isIPv4()) { if (addr.isIPv4()) {
disposeObj = disposeObject + "-32"; disposeObj = disposeObject + "-32";
}else if(addr.isIPv6()) { } else if (addr.isIPv6()) {
disposeObj = disposeObject + "-128"; disposeObj = disposeObject + "-128";
} }
@ -181,7 +194,7 @@ public class HuaWeiAbilityImpl implements DisposeAbility {
} }
try { try {
log.debug("++++Begging HuaWei Stop Cleanup Task: {}", taskId); log.info("++++Begging HuaWei Stop Cleanup Task: {}", taskId);
if (capType != DisposeCapacityType.CLEANUP) { if (capType != DisposeCapacityType.CLEANUP) {
log.error("----Error HuaWei don't support dispose capacity type: {}", capType); log.error("----Error HuaWei don't support dispose capacity type: {}", capType);
@ -211,10 +224,12 @@ public class HuaWeiAbilityImpl implements DisposeAbility {
return new MulReturnType<>(ErrorCode.ERR_CALLDEVICE, null); return new MulReturnType<>(ErrorCode.ERR_CALLDEVICE, null);
} }
log.debug("----Finish HuaWei Stop Cleanup Task: {}", taskId); log.info("----Finish HuaWei Stop Cleanup Task: {}", taskId);
return new MulReturnType<>(ErrorCode.ERR_OK, null); return new MulReturnType<>(ErrorCode.ERR_OK, null);
} catch (Exception ex) { } catch (Exception ex) {
log.error("----Exception HuaWei Stop Cleanup Task: {}, {}, {}", disposeObject, nfDirection, taskId); log.error("----Exception HuaWei Stop Cleanup Task [{}]: {}, {}, {}, {}", ex.getMessage(),
disposeObject,
nfDirection, url, token);
return new MulReturnType<>(ErrorCode.ERR_SYSTEMEXCEPTION, null); return new MulReturnType<>(ErrorCode.ERR_SYSTEMEXCEPTION, null);
} }
} }
@ -238,18 +253,18 @@ public class HuaWeiAbilityImpl implements DisposeAbility {
@Override @Override
public MulReturnType<ErrorCode, DeviceFirewareInfo> getAbilityDeviceFireware() { public MulReturnType<ErrorCode, DeviceFirewareInfo> getAbilityDeviceFireware() {
return new MulReturnType<>(ErrorCode.ERR_OK, return new MulReturnType<>(ErrorCode.ERR_OK,
DeviceFirewareInfo.builder() DeviceFirewareInfo.builder()
.vendor("HuaWei") .vendor("HuaWei")
.model("Unknown") .model("Unknown")
.firmware("Unknown") .firmware("Unknown")
.os("Linux Server") .os("Linux Server")
.kernel("Linux") .kernel("Linux")
.arch("x86_64") .arch("x86_64")
.version("Unknown") .version("Unknown")
.memory(-1) .memory(-1)
.freeMemory(-1) .freeMemory(-1)
.cpuUsed(-1) .cpuUsed(-1)
.build()); .build());
} }
/** /**
@ -270,12 +285,20 @@ public class HuaWeiAbilityImpl implements DisposeAbility {
*/ */
@Override @Override
public boolean getDeviceLinkStatus() { public boolean getDeviceLinkStatus() {
return deviceLinkStatus;
}
/**
* Dev get link status.
*/
private void devGetLinkStatus() {
try { try {
//查询所有的zone接口调用成功认为设备心跳正常 //查询所有的zone接口调用成功认为设备心跳正常
String url = urlRootPath + "/allzone"; String url = urlRootPath + "/allzone";
if (token == null || token.length() == 0) { if (token == null || token.length() == 0) {
return false; deviceLinkStatus = false;
return;
} }
HttpResponse response = restfulInterface.queryAllZones(url, token); HttpResponse response = restfulInterface.queryAllZones(url, token);
@ -286,13 +309,14 @@ public class HuaWeiAbilityImpl implements DisposeAbility {
response = restfulInterface.queryAllZones(url, token); response = restfulInterface.queryAllZones(url, token);
} }
return response.getStatus() == HttpServletResponse.SC_OK; if (response.getStatus() == HttpServletResponse.SC_OK) {
} catch ( deviceLinkStatus = true;
Exception ex) { }
} catch (Exception ex) {
log.error(ex.getMessage()); log.error(ex.getMessage());
} }
return false; deviceLinkStatus = false;
} }
@ -330,5 +354,50 @@ public class HuaWeiAbilityImpl implements DisposeAbility {
} catch (Exception ignored) { } catch (Exception ignored) {
} }
} }
/**
* Period task runtime.
*/
@Override
public void periodTaskRuntime() {
log.debug("++++HuaWei Period Task Running");
// 更新心跳状态
if (timerCnt++ % DisposeConfigValue.HEART_PERIOD_OF_SECOND == 0) {
devGetLinkStatus();
}
log.debug("----HuaWei Period Task Running");
}
/**
* Device ready boolean.
*
* @return the boolean
*/
@Override
public boolean deviceReady() {
return true;
}
/**
* Upgrade service group.
*
* @param svrList the svr list
*/
@Override
public void upgradeServiceGroup(List<ServiceInfo> svrList) {
}
/**
* Is carry attack type boolean.
*
* @param attackType the attack type
* @return the boolean
*/
@Override
public boolean isCarryAttackType(Long attackType) {
return true;
}
} }

View File

@ -2,12 +2,14 @@ package com.dispose.ability.impl;
import com.dispose.ability.DisposeAbility; import com.dispose.ability.DisposeAbility;
import com.dispose.common.DisposeCapacityType; import com.dispose.common.DisposeCapacityType;
import com.dispose.common.DisposeConfigValue;
import com.dispose.common.DisposeObjectType; import com.dispose.common.DisposeObjectType;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.Helper; import com.dispose.common.Helper;
import com.dispose.common.IpAddrType; import com.dispose.common.IpAddrType;
import com.dispose.common.NetflowDirection; import com.dispose.common.NetflowDirection;
import com.dispose.pojo.dto.protocol.base.ProtocolRespDTO; import com.dispose.pojo.dto.protocol.base.ProtocolRespDTO;
import com.dispose.pojo.entity.ServiceInfo;
import com.dispose.pojo.po.MulReturnType; import com.dispose.pojo.po.MulReturnType;
import com.dispose.pojo.vo.DeviceFirewareInfo; import com.dispose.pojo.vo.DeviceFirewareInfo;
import com.pengxin.dispose.common.PengXinDisposeAbilityRsp; import com.pengxin.dispose.common.PengXinDisposeAbilityRsp;
@ -55,6 +57,15 @@ public class PengXinAbilityImpl implements DisposeAbility {
* The Task req id. * The Task req id.
*/ */
private Long taskReqId = System.currentTimeMillis(); private Long taskReqId = System.currentTimeMillis();
/**
* The Timer cnt.
*/
private long timerCnt = 0;
/**
* The Device link status.
*/
private boolean deviceLinkStatus = false;
/** /**
* The Url root path. * The Url root path.
*/ */
@ -310,11 +321,19 @@ public class PengXinAbilityImpl implements DisposeAbility {
*/ */
@Override @Override
public boolean getDeviceLinkStatus() { public boolean getDeviceLinkStatus() {
return deviceLinkStatus;
}
/**
* Dev get link status.
*/
private void devGetLinkStatus() {
try { try {
String url = urlRootPath + "dispose_device/information/linkstatus"; String url = urlRootPath + "dispose_device/information/linkstatus";
if (token == null || token.length() == 0) { if (token == null || token.length() == 0) {
return false; deviceLinkStatus = false;
return;
} }
ErrorCode err = restfulInterface.getLinkStatus(url, token); ErrorCode err = restfulInterface.getLinkStatus(url, token);
@ -325,12 +344,14 @@ public class PengXinAbilityImpl implements DisposeAbility {
err = restfulInterface.getLinkStatus(url, token); err = restfulInterface.getLinkStatus(url, token);
} }
return err == ErrorCode.ERR_OK; if (err == ErrorCode.ERR_OK) {
deviceLinkStatus = true;
}
} catch (Exception ex) { } catch (Exception ex) {
log.error(ex.getMessage()); log.error(ex.getMessage());
} }
return false; deviceLinkStatus = false;
} }
/** /**
@ -480,4 +501,52 @@ public class PengXinAbilityImpl implements DisposeAbility {
} catch (Exception ignored) { } catch (Exception ignored) {
} }
} }
/**
* Period task runtime.
*/
@Override
public void periodTaskRuntime() {
log.debug("++++PengXin Period Task Running");
// 更新防护对象
getDisposeDeviceProtectObject();
// 更新心跳状态
if (timerCnt++ % DisposeConfigValue.HEART_PERIOD_OF_SECOND == 0) {
devGetLinkStatus();
}
log.debug("----PengXin Period Task Running");
}
/**
* Device ready boolean.
*
* @return the boolean
*/
@Override
public boolean deviceReady() {
return true;
}
/**
* Upgrade service group.
*
* @param svrList the svr list
*/
@Override
public void upgradeServiceGroup(List<ServiceInfo> svrList) {
}
/**
* Is carry attack type boolean.
*
* @param attackType the attack type
* @return the boolean
*/
@Override
public boolean isCarryAttackType(Long attackType) {
return true;
}
} }

View File

@ -5,10 +5,12 @@ import com.dispose.common.DisposeCapacityType;
import com.dispose.common.DisposeObjectType; import com.dispose.common.DisposeObjectType;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.NetflowDirection; import com.dispose.common.NetflowDirection;
import com.dispose.pojo.entity.ServiceInfo;
import com.dispose.pojo.po.MulReturnType; import com.dispose.pojo.po.MulReturnType;
import com.dispose.pojo.vo.DeviceFirewareInfo; import com.dispose.pojo.vo.DeviceFirewareInfo;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.List;
/** /**
* The type Virtual ability. * The type Virtual ability.
@ -143,4 +145,42 @@ public class VirtualAbilityImpl implements DisposeAbility {
public MulReturnType<ErrorCode, Long> taskStatus(String taskId) { public MulReturnType<ErrorCode, Long> taskStatus(String taskId) {
return new MulReturnType<>(ErrorCode.ERR_UNSUPPORT, -1L); return new MulReturnType<>(ErrorCode.ERR_UNSUPPORT, -1L);
} }
/**
* Period task runtime.
*/
@Override
public void periodTaskRuntime() {
}
/**
* Device ready boolean.
*
* @return the boolean
*/
@Override
public boolean deviceReady() {
return true;
}
/**
* Upgrade service group.
*
* @param svrList the svr list
*/
@Override
public void upgradeServiceGroup(List<ServiceInfo> svrList) {
}
/**
* Is carry attack type boolean.
*
* @param attackType the attack type
* @return the boolean
*/
@Override
public boolean isCarryAttackType(Long attackType) {
return true;
}
} }

View File

@ -79,6 +79,21 @@ public class ConstValue {
public static final String IP_PORT_REG = "^[1-9]$|(^[1-9][0-9]$)|(^[1-9][0-9][0-9]$)|(^[1-9][0-9][0-9][0-9]$)|" + public static final String IP_PORT_REG = "^[1-9]$|(^[1-9][0-9]$)|(^[1-9][0-9][0-9]$)|(^[1-9][0-9][0-9][0-9]$)|" +
"(^[1-6][0-5][0-5][0-3][0-5]$)"; "(^[1-6][0-5][0-5][0-3][0-5]$)";
/**
* The constant BUSINESS_TYPE.
*/
public static final String BUSINESS_TYPE = "^(GENERAL)|(WEB)|(DNS)|(GAME)$";
/**
* The constant NUMBER_TYPE.
*/
public static final String NUMBER_TYPE = "^[0-9]+([.]{1}[0-9]+){0,1}$";
/**
* The constant IP_SEGMENT_SPILT.
*/
public static final String[] IP_SEGMENT_SPILT = new String[] {"-", "/"};
/** /**
* The type Protocol. * The type Protocol.
* *

View File

@ -186,6 +186,11 @@ public enum DDoSAttackType implements BaseEnum {
*/ */
IGMP_FLOOD(42, "IGMP_FLOOD"), IGMP_FLOOD(42, "IGMP_FLOOD"),
/**
* None attacks d do s attack type.
*/
NONE_ATTACKS(63, "NONE_ATTACKS"),
/** /**
* The All attacks. * The All attacks.
*/ */
@ -224,7 +229,7 @@ public enum DDoSAttackType implements BaseEnum {
if (types.contains(ALL_ATTACKS)) { if (types.contains(ALL_ATTACKS)) {
for (DDoSAttackType type : DDoSAttackType.values()) { for (DDoSAttackType type : DDoSAttackType.values()) {
if (type.equals(ALL_ATTACKS)) { if (type.equals(ALL_ATTACKS) || type.equals(NONE_ATTACKS)) {
continue; continue;
} }
mask |= (long) 1 << type.getValue(); mask |= (long) 1 << type.getValue();
@ -249,7 +254,8 @@ public enum DDoSAttackType implements BaseEnum {
if (Arrays.asList(types).contains(ALL_ATTACKS)) { if (Arrays.asList(types).contains(ALL_ATTACKS)) {
for (DDoSAttackType type : DDoSAttackType.values()) { for (DDoSAttackType type : DDoSAttackType.values()) {
if (type.equals(ALL_ATTACKS)) { // 掩码处理跳过所有攻击类型与不指定攻击类型
if (type.equals(ALL_ATTACKS) || type.equals(NONE_ATTACKS)) {
continue; continue;
} }
mask |= (long) 1 << type.getValue(); mask |= (long) 1 << type.getValue();
@ -270,8 +276,12 @@ public enum DDoSAttackType implements BaseEnum {
* @return the type mask from attack type * @return the type mask from attack type
*/ */
public static Long getTypeMaskFromAttackType(Integer[] types) { public static Long getTypeMaskFromAttackType(Integer[] types) {
// 如果指定了所有攻击类型选择所有攻击类型
if (Arrays.stream(types).anyMatch(v -> ALL_ATTACKS.getValue().equals(v))) { if (Arrays.stream(types).anyMatch(v -> ALL_ATTACKS.getValue().equals(v))) {
return getTypeMaskFromAttackType(new DDoSAttackType[]{ALL_ATTACKS}); return getTypeMaskFromAttackType(new DDoSAttackType[]{ALL_ATTACKS});
} else if (Arrays.stream(types).anyMatch(v -> NONE_ATTACKS.getValue().equals(v))) {
// 如果不指定攻击类型
return getTypeMaskFromAttackType(new DDoSAttackType[]{NONE_ATTACKS});
} else { } else {
long mask = 0L; long mask = 0L;
for (int i : types) { for (int i : types) {

View File

@ -58,4 +58,9 @@ public class DisposeConfigValue {
* The constant ENABLE_UTEST_MOCK. * The constant ENABLE_UTEST_MOCK.
*/ */
public static volatile boolean ENABLE_UTEST_MOCK = false; public static volatile boolean ENABLE_UTEST_MOCK = false;
/**
* The constant HEART_PERIOD_OF_SECOND.
*/
public static long HEART_PERIOD_OF_SECOND = 30;
} }

View File

@ -19,9 +19,13 @@ public enum DisposeDeviceType implements BaseEnum {
*/ */
PENGXIN_PLATFORM(2, "鹏信处置设备"), PENGXIN_PLATFORM(2, "鹏信处置设备"),
/** /**
* The HuaWei platform. * The Huawei platform.
*/ */
HUAWEI_PLATFORM(3, "华为处置设备"), HUAWEI_PLATFORM(3, "华为处置设备"),
/**
* Dptech bypass umc dispose device type.
*/
DPTECH_BYPASS_UMC(4, "迪普旁路牵引UMC管理平台"),
/** /**
* The Virtual dispose. * The Virtual dispose.
*/ */

View File

@ -57,7 +57,13 @@ public enum DpTechAttackType implements BaseEnum {
/** /**
* The Host total traffic. * The Host total traffic.
*/ */
HOST_TOTAL_TRAFFIC(31, "Host Total Traffic"); HOST_TOTAL_TRAFFIC(31, "Host Total Traffic"),
/**
* The Auto attack type.
*/
AUTO_ATTACK_TYPE(32, "Automatic detect attack type"),
;
/** /**
* The Code. * The Code.
@ -130,10 +136,10 @@ public enum DpTechAttackType implements BaseEnum {
} }
/** /**
* From ddos attack type value stream. * From ddos attack type value list.
* *
* @param type the type * @param type the type
* @return the stream * @return the list
*/ */
public static List<DpTechAttackType> fromDdosAttackTypeValue(DDoSAttackType type) { public static List<DpTechAttackType> fromDdosAttackTypeValue(DDoSAttackType type) {
List<DpTechAttackType> attackList = new ArrayList<>(); List<DpTechAttackType> attackList = new ArrayList<>();
@ -204,6 +210,10 @@ public enum DpTechAttackType implements BaseEnum {
attackList.addAll(Arrays.asList(DpTechAttackType.values())); attackList.addAll(Arrays.asList(DpTechAttackType.values()));
break; break;
case NONE_ATTACKS:
attackList.add(AUTO_ATTACK_TYPE);
break;
default: default:
break; break;
} }

View File

@ -21,4 +21,9 @@ public class DpTechConfigValue {
* The constant SOAP_RECEIVE_TIMEOUT_SECOND. * The constant SOAP_RECEIVE_TIMEOUT_SECOND.
*/ */
public static volatile long SOAP_RECEIVE_TIMEOUT_SECOND = 60; public static volatile long SOAP_RECEIVE_TIMEOUT_SECOND = 60;
/**
* The Protection upgrade period.
*/
public static final long PROTECTION_UPGRADE_PERIOD = 10;
} }

View File

@ -165,7 +165,7 @@ public enum ErrorCode {
*/ */
ERR_UNTRUSTTOKEN(38, "未经授权的Token"), ERR_UNTRUSTTOKEN(38, "未经授权的Token"),
/** /**
* Err unknowninterface error code. * The Err unknowninterface.
*/ */
ERR_UNKNOWNINTERFACE(39, "未提供该接口"), ERR_UNKNOWNINTERFACE(39, "未提供该接口"),
/** /**
@ -217,19 +217,19 @@ public enum ErrorCode {
*/ */
ERR_DECRYPT_AES256(111, "AES256解密失败"), ERR_DECRYPT_AES256(111, "AES256解密失败"),
/** /**
* The Err no device by areaCode. * The Err nodevice areacode.
*/ */
ERR_NODEVICE_AREACODE(112, "区域无该设备"), ERR_NODEVICE_AREACODE(112, "区域无该设备"),
/** /**
* The Err specified IP already exists. * The Err specifiedip exists.
*/ */
ERR_SPECIFIEDIP_EXISTS(113, "指定的IP已经存在"), ERR_SPECIFIEDIP_EXISTS(113, "指定的IP已经存在"),
/** /**
* The Err specified IP does not exists. * The Err specifiedip notexists.
*/ */
ERR_SPECIFIEDIP_NOTEXISTS(114, "指定的IP地址不存在"), ERR_SPECIFIEDIP_NOTEXISTS(114, "指定的IP地址不存在"),
/** /**
* The Err server processing request. * The Err server processreq.
*/ */
ERR_SERVER_PROCESSREQ(115, "服务器处理请求错误"), ERR_SERVER_PROCESSREQ(115, "服务器处理请求错误"),
/** /**
@ -240,6 +240,44 @@ public enum ErrorCode {
* The Err pengxin error. * The Err pengxin error.
*/ */
ERR_PENGXIN_ERROR(117, "鹏信设备返回错误"), ERR_PENGXIN_ERROR(117, "鹏信设备返回错误"),
/**
* The Err nosuchumcprotectobject.
*/
ERR_NOSUCHUMCPROTECTOBJECT(200, "没有找到UMC防护对象"),
/**
* The Err protectobjectexists.
*/
ERR_PROTECTOBJECTEXISTS(201, "该防护对象已经存在"),
/**
* The Err tractionstrategyrunning.
*/
ERR_TRACTIONSTRATEGYRUNNING(201, "该防护策略正在运行"),
/**
* The Err nosuchprotectstrategy.
*/
ERR_NOSUCHPROTECTSTRATEGY(202, "没有该防护策略"),
/**
* The Err businessexists.
*/
ERR_BUSINESSEXISTS(300, "该业务已经存在"),
/**
* Err businessnotexists error code.
*/
ERR_BUSINESSNOTEXISTS(301, "该业务不存在"),
/**
* Err addbusiness error code.
*/
ERR_ADDBUSINESS(302, "添加客户业务失败"),
ERR_DELBUSINESS(303, "删除客户业务失败"),
; ;
/** /**

View File

@ -1,9 +1,12 @@
package com.dispose.common; package com.dispose.common;
import com.dispose.config.TemplateConfigure;
import com.dispose.pojo.vo.TemplateInfo;
import inet.ipaddr.AddressStringException; import inet.ipaddr.AddressStringException;
import inet.ipaddr.IPAddress; import inet.ipaddr.IPAddress;
import inet.ipaddr.IPAddressSeqRange; import inet.ipaddr.IPAddressSeqRange;
import inet.ipaddr.IPAddressString; import inet.ipaddr.IPAddressString;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
@ -14,6 +17,7 @@ import java.sql.Timestamp;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.Arrays; import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@ -21,12 +25,13 @@ import java.util.stream.Collectors;
* *
* @author <huangxin@cmhi.chinamoblie.com> * @author <huangxin@cmhi.chinamoblie.com>
*/ */
@Slf4j
public class Helper { public class Helper {
/** /**
* Instantiates a new Helper. * Instantiates a new Helper.
*/ */
private Helper () { private Helper() {
throw new AssertionError("Instantiating utility class."); throw new AssertionError("Instantiating utility class.");
} }
@ -155,7 +160,8 @@ public class Helper {
} else if (addr.isIPv6() && ipV6All.equals(rangeIp)) { } else if (addr.isIPv6() && ipV6All.equals(rangeIp)) {
return true; return true;
} }
} catch (Exception ignored) {} } catch (Exception ignored) {
}
// 处理CIDR格式 // 处理CIDR格式
if (rangeIp.contains(cidrSplit)) { if (rangeIp.contains(cidrSplit)) {
@ -177,7 +183,8 @@ public class Helper {
addr = new IPAddressString(ipAddr).toAddress(); addr = new IPAddressString(ipAddr).toAddress();
IPAddressSeqRange range = lower.toSequentialRange(upper); IPAddressSeqRange range = lower.toSequentialRange(upper);
return range.contains(addr); return range.contains(addr);
} catch (AddressStringException ignored) {} } catch (AddressStringException ignored) {
}
return false; return false;
} }
@ -202,4 +209,22 @@ public class Helper {
return sb.toString(); return sb.toString();
} }
/**
* Gets dp template.
*
* @param type the type
* @param bandWidth the band width
* @return the dp template
*/
public static String getDpTemplate(String type, Long bandWidth) {
Optional<String> ret = TemplateConfigure.UMC_TEMPLATE.stream()
.filter(v -> v.getType().equals(type))
.filter(v -> (bandWidth == 0 && v.getBandMin() == 0)
|| (bandWidth > v.getBandMin() && (bandWidth <= v.getBandMax() || v.getBandMax() == -1L)))
.map(TemplateInfo::getName)
.findFirst();
return ret.orElse("");
}
} }

View File

@ -0,0 +1,42 @@
package com.dispose.config;
import com.dispose.pojo.vo.TemplateInfo;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;
/**
* The type Template configure.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "template")
@Configuration
public class TemplateConfigure {
/**
* The Umc template.
*/
public static List<TemplateInfo> UMC_TEMPLATE;
/**
* The Umc template.
*/
private List<TemplateInfo> umcTemplate;
/**
* Init template configure.
*/
@PostConstruct
private void initTemplateConfigure() {
TemplateConfigure.UMC_TEMPLATE = umcTemplate;
}
}

View File

@ -105,7 +105,7 @@ public class DisposeTaskController {
NetflowDirection netDir = CommonEnumHandler.codeOf(NetflowDirection.class, NetflowDirection netDir = CommonEnumHandler.codeOf(NetflowDirection.class,
Optional.ofNullable(req.getFlowDirection()).orElse(2)); Optional.ofNullable(req.getFlowDirection()).orElse(2));
Long attackType = DDoSAttackType.getTypeMaskFromAttackType(Optional.ofNullable(req.getAttackType()) Long attackType = DDoSAttackType.getTypeMaskFromAttackType(Optional.ofNullable(req.getAttackType())
.orElse(new Integer[]{DDoSAttackType.ALL_ATTACKS.getValue()})); .orElse(new Integer[]{DDoSAttackType.NONE_ATTACKS.getValue()}));
Integer flowBand = Optional.ofNullable(req.getFlowBandwidth()) Integer flowBand = Optional.ofNullable(req.getFlowBandwidth())
.orElse(DisposeConfigValue.DEFAULT_DISPOSE_BANDWIDTH); .orElse(DisposeConfigValue.DEFAULT_DISPOSE_BANDWIDTH);
@ -186,7 +186,7 @@ public class DisposeTaskController {
.orElse(2))) .orElse(2)))
.attackType(DDoSAttackType.getTypeMaskFromAttackType( .attackType(DDoSAttackType.getTypeMaskFromAttackType(
Optional.ofNullable(req.getAttackType()) Optional.ofNullable(req.getAttackType())
.orElse(new Integer[]{DDoSAttackType.ALL_ATTACKS.getValue()}))) .orElse(new Integer[]{DDoSAttackType.NONE_ATTACKS.getValue()})))
.flowBandWidth(Optional.ofNullable(req.getFlowBandwidth()) .flowBandWidth(Optional.ofNullable(req.getFlowBandwidth())
.orElse(DisposeConfigValue.DEFAULT_DISPOSE_BANDWIDTH)) .orElse(DisposeConfigValue.DEFAULT_DISPOSE_BANDWIDTH))
.build(); .build();
@ -237,7 +237,7 @@ public class DisposeTaskController {
NetflowDirection netDir = CommonEnumHandler.codeOf(NetflowDirection.class, NetflowDirection netDir = CommonEnumHandler.codeOf(NetflowDirection.class,
Optional.ofNullable(req.getFlowDirection()).orElse(2)); Optional.ofNullable(req.getFlowDirection()).orElse(2));
Long attackType = DDoSAttackType.getTypeMaskFromAttackType(Optional.ofNullable(req.getAttackType()) Long attackType = DDoSAttackType.getTypeMaskFromAttackType(Optional.ofNullable(req.getAttackType())
.orElse(new Integer[]{DDoSAttackType.ALL_ATTACKS.getValue()})); .orElse(new Integer[]{DDoSAttackType.NONE_ATTACKS.getValue()}));
Integer flowBand = Optional.ofNullable(req.getFlowBandwidth()) Integer flowBand = Optional.ofNullable(req.getFlowBandwidth())
.orElse(DisposeConfigValue.DEFAULT_DISPOSE_BANDWIDTH); .orElse(DisposeConfigValue.DEFAULT_DISPOSE_BANDWIDTH);

View File

@ -0,0 +1,178 @@
package com.dispose.controller;
import com.dispose.common.ErrorCode;
import com.dispose.pojo.dto.protocol.base.ProtocolReqDTO;
import com.dispose.pojo.dto.protocol.base.ProtocolRespDTO;
import com.dispose.pojo.dto.protocol.device.business.AddUserSvrReq;
import com.dispose.pojo.dto.protocol.device.business.AddUserSvrRsp;
import com.dispose.pojo.dto.protocol.device.business.BusinessIdArray;
import com.dispose.pojo.dto.protocol.device.business.UserSvrInfo;
import com.dispose.pojo.dto.protocol.device.business.UserSvrRsp;
import com.dispose.pojo.entity.ServiceInfo;
import com.dispose.pojo.po.MulReturnType;
import com.dispose.security.annotation.Decryption;
import com.dispose.security.annotation.Encryption;
import com.dispose.service.UserBusinessManagerService;
import com.dispose.validation.group.ValidGroups;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* The type User business controller.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Controller
@RequestMapping(value = "/business")
@Slf4j
@Api(value = "抗DDoS处置平台客户业务管理接口", tags = "抗DDoS处置平台客户业务管理接口")
@Component
@Validated
@Encryption
@Decryption
public class UserBusinessController {
/**
* The User business manager service.
*/
@Resource
private UserBusinessManagerService userBusinessManagerService;
/**
* Add user business protocol resp dto.
*
* @param mr the mr
* @return the protocol resp dto
*/
@PutMapping("/manage")
@ResponseBody
@ApiOperation("添加客户业务信息")
public ProtocolRespDTO<AddUserSvrRsp> addUserBusiness(
@Validated(ValidGroups.AddUserInfoValid.class)
@RequestBody ProtocolReqDTO<AddUserSvrReq> mr) {
List<ServiceInfo> svrList = new ArrayList<>();
// 参数转换
for (UserSvrInfo v : mr.getMsgContent().getItems()) {
svrList.add(ServiceInfo.builder()
.serviceId(v.getBusinessId())
.serviceType(v.getBusinessType())
.serviceBandwidth((long) Math.ceil(Double.parseDouble(v.getBusinessBandwidth())))
.serviceIp(StringUtils.deleteWhitespace(v.getBusinessIp()))
.build());
}
// 添加业务
List<MulReturnType<ErrorCode, String>> ret = userBusinessManagerService.addUserBusiness(svrList);
AddUserSvrRsp rspInfo = AddUserSvrRsp.builder()
.items(new ArrayList<>())
.build();
// 处理反回值
ret.forEach(v -> {
UserSvrRsp rsp = UserSvrRsp.builder()
.businessId(v.getSecondParam())
.build();
rsp.setStatus(v.getFirstParam().getCode());
rsp.setMessage(new String[]{v.getFirstParam().getMsg()});
rspInfo.getItems().add(rsp);
});
return ProtocolRespDTO.result(ErrorCode.ERR_OK, rspInfo);
}
/**
* Del user business protocol resp dto.
*
* @param mr the mr
* @return the protocol resp dto
*/
@DeleteMapping("/manage")
@ResponseBody
@ApiOperation("删除客户业务信息")
public ProtocolRespDTO<AddUserSvrRsp> delUserBusiness(
@Validated(ValidGroups.AddUserInfoValid.class)
@RequestBody ProtocolReqDTO<BusinessIdArray> mr) {
// 删除业务
List<MulReturnType<ErrorCode, String>> ret = userBusinessManagerService.delUserBusiness(mr.getMsgContent()
.getBusinessId());
// 处理反回值
AddUserSvrRsp rspInfo = AddUserSvrRsp.builder()
.items(new ArrayList<>())
.build();
ret.forEach(v -> {
UserSvrRsp rsp = UserSvrRsp.builder()
.businessId(v.getSecondParam())
.build();
rsp.setStatus(v.getFirstParam().getCode());
rsp.setMessage(new String[]{v.getFirstParam().getMsg()});
rspInfo.getItems().add(rsp);
});
return ProtocolRespDTO.result(ErrorCode.ERR_OK, rspInfo);
}
/**
* Upgrade user business protocol resp dto.
*
* @param mr the mr
* @return the protocol resp dto
*/
@PostMapping("/updateBusiness")
@ResponseBody
@ApiOperation("更新客户业务信息")
public ProtocolRespDTO<AddUserSvrRsp> upgradeUserBusiness(
@Validated(ValidGroups.AddUserInfoValid.class)
@RequestBody ProtocolReqDTO<AddUserSvrReq> mr) {
List<ServiceInfo> svrList = new ArrayList<>();
// 参数转换
for (UserSvrInfo v : mr.getMsgContent().getItems()) {
svrList.add(ServiceInfo.builder()
.serviceId(v.getBusinessId())
.serviceType(v.getBusinessType())
.serviceBandwidth((long) Math.ceil(Double.parseDouble(v.getBusinessBandwidth())))
.serviceIp(v.getBusinessIp())
.build());
}
// 更新业务
List<MulReturnType<ErrorCode, String>> ret = userBusinessManagerService.upgradeUserBusiness(svrList);
AddUserSvrRsp rspInfo = AddUserSvrRsp.builder()
.items(new ArrayList<>())
.build();
// 处理反回值
ret.forEach(v -> {
UserSvrRsp rsp = UserSvrRsp.builder()
.businessId(v.getSecondParam())
.build();
rsp.setStatus(v.getFirstParam().getCode());
rsp.setMessage(new String[]{v.getFirstParam().getMsg()});
rspInfo.getItems().add(rsp);
});
return ProtocolRespDTO.result(ErrorCode.ERR_OK, rspInfo);
}
}

View File

@ -136,6 +136,15 @@ public interface DeviceTaskManager {
*/ */
DeviceTask getTaskById(Long id); DeviceTask getTaskById(Long id);
/**
* Device task created boolean.
*
* @param taskId the task id
* @param devId the dev id
* @return the boolean
*/
boolean deviceTaskCreated(Long taskId, Long devId);
/** /**
* Gets peng xin task. * Gets peng xin task.
* *

View File

@ -41,6 +41,13 @@ public interface DisposeTaskManager {
*/ */
List<DisposeTask> getExpiredTasks(); List<DisposeTask> getExpiredTasks();
/**
* Gets un expired tasks.
*
* @return the un expired tasks
*/
List<DisposeTask> getUnExpiredTasks();
/** /**
* Gets new dispose tasks. * Gets new dispose tasks.
* *

View File

@ -0,0 +1,27 @@
package com.dispose.manager;
import com.dispose.common.ErrorCode;
import com.dispose.pojo.entity.ServiceInfo;
/**
* The interface User business manager.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
public interface UserBusinessManager {
/**
* Add user business error code.
*
* @param svrInfo the svr info
* @return the error code
*/
ErrorCode addUserBusiness(ServiceInfo svrInfo);
/**
* Del user business error code.
*
* @param svrId the svr id
* @return the error code
*/
ErrorCode delUserBusiness(String svrId);
}

View File

@ -25,6 +25,18 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager {
@Resource @Resource
private DeviceTaskMapper deviceTaskMapper; private DeviceTaskMapper deviceTaskMapper;
/**
* Device task created boolean.
*
* @param taskId the task id
* @param devId the dev id
* @return the boolean
*/
@Override
public boolean deviceTaskCreated(Long taskId, Long devId) {
return deviceTaskMapper.getTaskByDetails(taskId, devId).size() != 0;
}
/** /**
* Add dispose device task info boolean. * Add dispose device task info boolean.
* *
@ -80,11 +92,11 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager {
} }
/** /**
* Change dispose device task info dev status long. * Change dispose device task info dev status int.
* *
* @param id the id * @param id the id
* @param devStatus the dev status * @param devStatus the dev status
* @return the long * @return the int
*/ */
@Override @Override
public int changeDisposeDeviceTaskInfoDevStatus(Long id, Long devStatus) { public int changeDisposeDeviceTaskInfoDevStatus(Long id, Long devStatus) {
@ -297,9 +309,9 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager {
} }
/** /**
* Gets PengXin device task info. * Get peng xin task list.
* *
* @return the minId task info. * @return the list
*/ */
@Override @Override
public List<DeviceTask> getPengXinTask(){ public List<DeviceTask> getPengXinTask(){

View File

@ -56,7 +56,8 @@ public class DisposeDeviceManagerImpl implements DisposeDeviceManager {
@Override @Override
public MulReturnType<ErrorCode, Long> addDisposeDevice(DisposeDevice dev) { public MulReturnType<ErrorCode, Long> addDisposeDevice(DisposeDevice dev) {
// 看看系统中有没有存在相同IP+端口地址的设备有的话返回失败 // 看看系统中有没有存在相同IP+端口地址的设备有的话返回失败
DisposeDevice tDev = disposeDeviceMapper.getDeviceByAddress(dev.getIpAddr(), dev.getIpPort()); DisposeDevice tDev = disposeDeviceMapper.getDeviceByAddress(dev.getIpAddr(), dev.getIpPort(),
dev.getDeviceType().getValue());
if (tDev != null) { if (tDev != null) {
// 如果设备是删除状态则更新设备信息 // 如果设备是删除状态则更新设备信息
@ -135,20 +136,17 @@ public class DisposeDeviceManagerImpl implements DisposeDeviceManager {
*/ */
@Override @Override
public MulReturnType<ErrorCode, Long> upgradeDisposeDevice(DisposeDevice dev) { public MulReturnType<ErrorCode, Long> upgradeDisposeDevice(DisposeDevice dev) {
DisposeDevice tDev = disposeDeviceMapper.getDeviceByAddress(dev.getIpAddr(), dev.getIpPort()); DisposeDevice tDev = disposeDeviceMapper.getDeviceByAddress(dev.getIpAddr(), dev.getIpPort(),
dev.getDeviceType().getValue());
// 处理默认端口情况 // 处理默认端口情况
if (tDev == null) { if (tDev == null) {
if (dev.getIpPort() == null || dev.getIpPort().length() == 0) { if (dev.getIpPort() == null || dev.getIpPort().length() == 0) {
// HTTP 默认端口 tDev = disposeDeviceMapper.getDeviceByAddress(dev.getIpAddr(),
if (dev.getUrlType() == HttpType.HTTP) { dev.getUrlType() == HttpType.HTTP ?
tDev = disposeDeviceMapper.getDeviceByAddress(dev.getIpAddr(), HttpType.getDefaultPort(HttpType.HTTP) :
HttpType.getDefaultPort(HttpType.HTTP)); HttpType.getDefaultPort(HttpType.HTTPS),
} else if (dev.getUrlType() == HttpType.HTTPS) { dev.getDeviceType().getValue());
// HTTPS 默认端口
tDev = disposeDeviceMapper.getDeviceByAddress(dev.getIpAddr(),
HttpType.getDefaultPort(HttpType.HTTPS));
}
} }
} }

View File

@ -88,6 +88,16 @@ public class DisposeTaskManagerImpl implements DisposeTaskManager {
return disposeTaskMapper.getExpiredTasks(); return disposeTaskMapper.getExpiredTasks();
} }
/**
* Gets un expired tasks.
*
* @return the un expired tasks
*/
@Override
public List<DisposeTask> getUnExpiredTasks() {
return disposeTaskMapper.getUnExpiredTasks();
}
/** /**
* Gets new dispose tasks. * Gets new dispose tasks.
* *

View File

@ -0,0 +1,59 @@
package com.dispose.manager.impl;
import com.dispose.common.ErrorCode;
import com.dispose.manager.UserBusinessManager;
import com.dispose.mapper.ServiceGroupMapper;
import com.dispose.pojo.entity.ServiceInfo;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* The type User business manager.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Component
public class UserBusinessManagerImpl implements UserBusinessManager {
/**
* The Service group mapper.
*/
@Resource
private ServiceGroupMapper serviceGroupMapper;
/**
* Add user business error code.
*
* @param svrInfo the svr info
* @return the error code
*/
@Override
public ErrorCode addUserBusiness(ServiceInfo svrInfo) {
if (serviceGroupMapper.selectByServiceId(svrInfo.getServiceId()) != null) {
return ErrorCode.ERR_BUSINESSEXISTS;
}
List<ServiceInfo> svrList = new ArrayList<>();
svrList.add(svrInfo);
return serviceGroupMapper.addServiceGroup(svrList) != 1 ? ErrorCode.ERR_ADDBUSINESS : ErrorCode.ERR_OK;
}
/**
* Del user business error code.
*
* @param svrId the svr id
* @return the error code
*/
@Override
public ErrorCode delUserBusiness(String svrId) {
if (serviceGroupMapper.selectByServiceId(svrId) == null) {
return ErrorCode.ERR_BUSINESSNOTEXISTS;
}
return serviceGroupMapper.delServiceGroupByServiceId(svrId) != 1 ? ErrorCode.ERR_DELBUSINESS : ErrorCode.ERR_OK;
}
}

View File

@ -83,7 +83,8 @@ public interface DisposeDeviceMapper {
* @return the device by address * @return the device by address
*/ */
DisposeDevice getDeviceByAddress(@Param("ipAddr") String ipAddr, DisposeDevice getDeviceByAddress(@Param("ipAddr") String ipAddr,
@Param("ipPort") String ipPort); @Param("ipPort") String ipPort,
@Param("devType") Integer devType);
/** /**

View File

@ -104,4 +104,11 @@ public interface DisposeTaskMapper {
* @return the expired tasks * @return the expired tasks
*/ */
List<DisposeTask> getExpiredTasks(); List<DisposeTask> getExpiredTasks();
/**
* Gets un expired tasks.
*
* @return the un expired tasks
*/
List<DisposeTask> getUnExpiredTasks();
} }

View File

@ -0,0 +1,52 @@
package com.dispose.mapper;
import com.dispose.pojo.entity.ServiceInfo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* The interface Service group mapper.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
public interface ServiceGroupMapper {
/**
* Select all list.
*
* @return the list
*/
List<ServiceInfo> selectAll();
/**
* Select by service id service info.
*
* @param serviceId the service id
* @return the service info
*/
ServiceInfo selectByServiceId(@Param("serviceId") String serviceId);
/**
* Add service group int.
*
* @param svrGrps the svr grps
* @return the int
*/
int addServiceGroup(@Param("svrGrps") List<ServiceInfo> svrGrps);
/**
* Del service group by id int.
*
* @param id the id
* @return the int
*/
int delServiceGroupById(@Param("id") Long id);
/**
* Del service group by service id int.
*
* @param serviceId the service id
* @return the int
*/
int delServiceGroupByServiceId(@Param("serviceId") String serviceId);
}

View File

@ -0,0 +1,34 @@
package com.dispose.pojo.dto.protocol.device.ability;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Hashtable;
/**
* The type Dp bypass manager.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DpBypassManager {
/**
* The Protect object.
*/
Hashtable<String, DpProtectObject> protectObject;
/**
* The Protect strategy.
*/
Hashtable<String, DpProtectionStrategyInfo> protectStrategy;
/**
* The Traction strategy name.
*/
Hashtable<String, DpTractionStrategy> tractionStrategyName;
}

View File

@ -0,0 +1,45 @@
package com.dispose.pojo.dto.protocol.device.ability;
import com.dispose.common.IpAddrType;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Hashtable;
/**
* The type Dp protect object.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DpProtectObject {
/**
* The Protect name.
*/
private String protectName;
/**
* The Detection devices.
*/
private String detectionDevices;
/**
* The Cleanup devices.
*/
private String cleanupDevices;
/**
* The Ip type.
*/
private IpAddrType ipType;
/**
* The Ip segment.
*/
private Hashtable<String, String> ipSegment;
}

View File

@ -0,0 +1,26 @@
package com.dispose.pojo.dto.protocol.device.ability;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* The type Dp protection strategy info.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DpProtectionStrategyInfo {
/**
* The Protect target name.
*/
private String protectTargetName;
/**
* The Protect strategy name.
*/
private String protectStrategyName;
}

View File

@ -0,0 +1,34 @@
package com.dispose.pojo.dto.protocol.device.ability;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* The type Dp traction strategy.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DpTractionStrategy {
/**
* The Policy name.
*/
private String policyName;
/**
* The Protect name.
*/
private String protectName;
/**
* The Ip range.
*/
private String ipRange;
/**
* The Running.
*/
private boolean running;
}

View File

@ -0,0 +1,33 @@
package com.dispose.pojo.dto.protocol.device.business;
import com.dispose.validation.group.ValidGroups;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.List;
/**
* The type Add user svr req.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AddUserSvrReq {
/**
* The Items.
*/
@NotNull(message = "items 设备列表不能为空", groups = ValidGroups.AddUserInfoValid.class)
@Size(min = 1, message = "items 至少需要有一个元素", groups = ValidGroups.AddUserInfoValid.class)
@Valid
private List<UserSvrInfo> items;
}

View File

@ -0,0 +1,26 @@
package com.dispose.pojo.dto.protocol.device.business;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* The type Add user svr rsp.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AddUserSvrRsp {
/**
* The Items.
*/
private List<UserSvrRsp> items;
}

View File

@ -0,0 +1,28 @@
package com.dispose.pojo.dto.protocol.device.business;
import com.dispose.validation.group.ValidGroups;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* The type Business id array.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class BusinessIdArray {
/**
* The Business id.
*/
@NotNull(message = "businessId 字段不能为空", groups = ValidGroups.AddUserInfoValid.class)
@Size(min = 1, message = "businessId 字段必须指定明确编号", groups = ValidGroups.AddUserInfoValid.class)
private String[] businessId;
}

View File

@ -0,0 +1,55 @@
package com.dispose.pojo.dto.protocol.device.business;
import com.dispose.common.ConstValue;
import com.dispose.validation.group.ValidGroups;
import com.dispose.validation.valids.ValidIpSegment;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
/**
* The type User svr info.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserSvrInfo {
/**
* The Business id.
*/
@NotBlank(message = "businessId 客户业务ID能为空", groups = ValidGroups.AddUserInfoValid.class)
@Size(min = 1, max = 13, message = "businessId 字符串长度为 [1, 13]", groups = ValidGroups.AddUserInfoValid.class)
private String businessId;
/**
* The Business type.
*/
@NotBlank(message = "businessType 客户业务类型不能为空", groups = ValidGroups.AddUserInfoValid.class)
@Pattern(regexp = ConstValue.BUSINESS_TYPE,
message = "businessType 未知业务类型, [GENERAL, WEB, DNS, GAME]",
groups = ValidGroups.AddUserInfoValid.class)
private String businessType;
/**
* The Business ip.
*/
@JsonProperty("businessIP")
@ValidIpSegment(message = "businessIp Ip地址格式错误", groups = ValidGroups.AddUserInfoValid.class)
@NotBlank(message = "businessIp 业务IP地址段不能为空", groups = ValidGroups.AddUserInfoValid.class)
private String businessIp;
/**
* The Business bandwidth.
*/
@NotBlank(message = "businessBandwidth 客户业务带宽不能为空", groups = ValidGroups.AddUserInfoValid.class)
@Pattern(regexp = ConstValue.NUMBER_TYPE,
message = "businessBandwidth 只能为数字",
groups = ValidGroups.AddUserInfoValid.class)
private String businessBandwidth;
}

View File

@ -0,0 +1,27 @@
package com.dispose.pojo.dto.protocol.device.business;
import com.dispose.pojo.dto.protocol.base.BaseRespStatus;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* The type User svr rsp.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
@JsonPropertyOrder({"businessId", "status", "message"})
public class UserSvrRsp extends BaseRespStatus {
/**
* The Business id.
*/
private String businessId;
}

View File

@ -0,0 +1,61 @@
package com.dispose.pojo.entity;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import tk.mybatis.mapper.annotation.KeySql;
import tk.mybatis.mapper.annotation.NameStyle;
import tk.mybatis.mapper.code.Style;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* The type Service info.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder(alphabetic = true)
@Table(name = "service_group")
@NameStyle(Style.normal)
public class ServiceInfo {
/**
* The constant serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* The Id.
*/
@Id
@KeySql(useGeneratedKeys = true)
private Long id;
/**
* The Service id.
*/
private String serviceId;
/**
* The Service type.
*/
private String serviceType;
/**
* The Service bandwidth.
*/
private Long serviceBandwidth;
/**
* The Service ip.
*/
private String serviceIp;
}

View File

@ -0,0 +1,34 @@
package com.dispose.pojo.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* The type Template info.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class TemplateInfo {
/**
* The Name.
*/
private String name;
/**
* The Band min.
*/
private Long bandMin;
/**
* The Band max.
*/
private Long bandMax;
/**
* The Type.
*/
private String type;
}

View File

@ -24,20 +24,20 @@ import java.util.Map;
@Slf4j @Slf4j
public class RestfulInterface { public class RestfulInterface {
/** /**
* Instantiates a new Restful interface. * The constant OBJECT_MAPPER.
*/ */
private RestfulInterface () { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
throw new AssertionError("Instantiating utility class.");
}
/** /**
* The constant timeOutValue. * The constant timeOutValue.
*/ */
private static int timeOutValue = 1000; private static int timeOutValue = 1000;
/** /**
* The constant OBJECT_MAPPER. * Instantiates a new Restful interface.
*/ */
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private RestfulInterface() {
throw new AssertionError("Instantiating utility class.");
}
/** /**
* Init env. * Init env.
@ -203,11 +203,11 @@ public class RestfulInterface {
/** /**
* huawei pro run protocol resp dto. * huawei pro run protocol resp dto.
* *
* @param <E> the type parameter * @param <E> the type parameter
* @param url the url * @param url the url
* @param token the token * @param token the token
* @param obj the obj * @param obj the obj
* @param reqType the req type * @param reqType the req type
* @return the t * @return the t
*/ */
public static <E> HttpResponse huaWeiProRun(String url, String token, E obj, RequestMethod reqType) { public static <E> HttpResponse huaWeiProRun(String url, String token, E obj, RequestMethod reqType) {

View File

@ -18,9 +18,10 @@ public interface DisposeAbilityRouterService {
* *
* @param ipAddr the ip addr * @param ipAddr the ip addr
* @param ipPort the ip port * @param ipPort the ip port
* @param deviceType the device type
* @return the ability device * @return the ability device
*/ */
AbilityInfo getAbilityDevice(String ipAddr, String ipPort); AbilityInfo getAbilityDevice(String ipAddr, String ipPort, String deviceType);
/** /**
* Gets ability device. * Gets ability device.
@ -54,4 +55,9 @@ public interface DisposeAbilityRouterService {
* @return the error code * @return the error code
*/ */
ErrorCode verifyDisposeCapacity(Long deviceId, String disposeIp, DisposeCapacityType capacityType); ErrorCode verifyDisposeCapacity(Long deviceId, String disposeIp, DisposeCapacityType capacityType);
/**
* Run period task.
*/
void runPeriodTask();
} }

View File

@ -0,0 +1,17 @@
package com.dispose.service;
/**
* The interface Template service.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
public interface TemplateService {
/**
* Gets template.
*
* @param type the type
* @param bandWidth the band width
* @return the template
*/
String getTemplate(String type, Long bandWidth);
}

View File

@ -0,0 +1,38 @@
package com.dispose.service;
import com.dispose.common.ErrorCode;
import com.dispose.pojo.entity.ServiceInfo;
import com.dispose.pojo.po.MulReturnType;
import java.util.List;
/**
* The interface User business manager service.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
public interface UserBusinessManagerService {
/**
* Add user business list.
*
* @param svrInfoList the svr info list
* @return the list
*/
List<MulReturnType<ErrorCode, String>> addUserBusiness(List<ServiceInfo> svrInfoList);
/**
* Upgrade user business list.
*
* @param svrInfoList the svr info list
* @return the list
*/
List<MulReturnType<ErrorCode, String>> upgradeUserBusiness(List<ServiceInfo> svrInfoList);
/**
* Del user business list.
*
* @param svrId the svr id
* @return the list
*/
List<MulReturnType<ErrorCode, String>> delUserBusiness(String[] svrId);
}

View File

@ -133,85 +133,79 @@ public class DeviceTaskManagerServiceImpl implements DeviceTaskManagerService {
// 设置任务状态为启动中 // 设置任务状态为启动中
deviceTaskManager.changeDisposeDeviceTaskInfoStatus(deviceTask.getId(), DisposeTaskStatus.TASK_STARTING); deviceTaskManager.changeDisposeDeviceTaskInfoStatus(deviceTask.getId(), DisposeTaskStatus.TASK_STARTING);
// 遍历设备攻击类型 // 启动迪普设备采用一种攻击类型
for (DpTechAttackType t : DpTechAttackType.maskToDdosAttackType(deviceTask.getTaskAttackType())) { DpTechAttackType attackType = DpTechAttackType.maskToDdosAttackType(deviceTask.getTaskAttackType()).get(0);
// 出方向 // 出方向
if (disposeTask.getFlowDirection() != NetflowDirection.DIRECTION_IN) { if (disposeTask.getFlowDirection() != NetflowDirection.DIRECTION_IN) {
// 已经启动过的任务不再重复启动 // 设置启动任务攻击类型状态
if ((deviceTask.getExecAttackTypeOut() & t.getAttackTypeMask()) != 0) { deviceTaskManager.execAttackTypeSetBit(deviceTask.getId(), NetflowDirection.DIRECTION_OUT,
continue; attackType.getValue());
} // 调用迪普设备启动处置任务
// 设置启动任务攻击类型状态 ret = ai.getDb().runDispose(disposeTask.getDisposeObject(), disposeTask.getObjectType(),
deviceTaskManager.execAttackTypeSetBit(deviceTask.getId(), NetflowDirection.DIRECTION_OUT, disposeTask.getDisposeCapacity(), NetflowDirection.DIRECTION_OUT,
t.getValue()); attackType.getValue(), null);
// 调用迪普设备启动处置任务
ret = ai.getDb().runDispose(disposeTask.getDisposeObject(), disposeTask.getObjectType(),
disposeTask.getDisposeCapacity(), NetflowDirection.DIRECTION_OUT,
t.getValue(), null);
if (ret.getFirstParam() == ErrorCode.ERR_OK) { if (ret.getFirstParam() == ErrorCode.ERR_OK) {
// 标志启动成功 // 标志启动成功
deviceTaskManager.attackTypeStatusSetBit(deviceTask.getId(), NetflowDirection.DIRECTION_OUT, deviceTaskManager.attackTypeStatusSetBit(deviceTask.getId(), NetflowDirection.DIRECTION_OUT,
t.getValue()); attackType.getValue());
log.info("DPTECH_UMC setup task {}, {} succeed: {}", t, NetflowDirection.DIRECTION_OUT, deviceTask); log.info("DPTECH_UMC setup task {}, {} succeed: {}", attackType, NetflowDirection.DIRECTION_OUT,
deviceTask);
deviceTaskManager.setTaskErrRetryTimes(deviceTask.getId(), 0); deviceTaskManager.setTaskErrRetryTimes(deviceTask.getId(), 0);
} else if (deviceTask.getErrRetry() < DisposeConfigValue.CALL_ERROR_RETRY_TIMES * 10) { } else if (deviceTask.getErrRetry() < DisposeConfigValue.CALL_ERROR_RETRY_TIMES * 10) {
// 设置该任务为新任务待下次重试启动 // 设置该任务为新任务待下次重试启动
// 记录任务出错重试次数 // 记录任务出错重试次数
deviceTask.setErrRetry(deviceTask.getErrRetry() + 1); deviceTask.setErrRetry(deviceTask.getErrRetry() + 1);
deviceTaskManager.setTaskErrRetryTimes(deviceTask.getId(), deviceTask.getErrRetry()); deviceTaskManager.setTaskErrRetryTimes(deviceTask.getId(), deviceTask.getErrRetry());
//清除任务攻击类型启动标志 //清除任务攻击类型启动标志
deviceTaskManager.execAttackTypeCleanBit(deviceTask.getId(), NetflowDirection.DIRECTION_OUT, deviceTaskManager.execAttackTypeCleanBit(deviceTask.getId(), NetflowDirection.DIRECTION_OUT,
t.getValue()); attackType.getValue());
log.error("DPTECH_UMC setup task {}, {} times {} error: {}", t, log.error("DPTECH_UMC setup task {}, {} times {} error: {}", attackType,
NetflowDirection.DIRECTION_OUT, deviceTask.getErrRetry(), deviceTask); NetflowDirection.DIRECTION_OUT, deviceTask.getErrRetry(), deviceTask);
} else { } else {
log.error("DPTECH_UMC setup task {}, {} error {}: {}", t, log.error("DPTECH_UMC setup task {}, {} error {}: {}", attackType,
NetflowDirection.DIRECTION_OUT, ret.getFirstParam(), deviceTask); NetflowDirection.DIRECTION_OUT, ret.getFirstParam(), deviceTask);
}
}
// 入方向
if (disposeTask.getFlowDirection() != NetflowDirection.DIRECTION_OUT) {
// 已经启动过的任务不再重复启动
if ((deviceTask.getExecAttackTypeIn() & t.getAttackTypeMask()) != 0) {
continue;
}
// 设置启动任务攻击类型状态
deviceTaskManager.execAttackTypeSetBit(deviceTask.getId(), NetflowDirection.DIRECTION_IN,
t.getValue());
// 调用迪普设备启动处置任务
ret = ai.getDb().runDispose(disposeTask.getDisposeObject(), disposeTask.getObjectType(),
disposeTask.getDisposeCapacity(), NetflowDirection.DIRECTION_IN,
t.getValue(), null);
if (ret.getFirstParam() == ErrorCode.ERR_OK) {
// 标志启动成功
deviceTaskManager.attackTypeStatusSetBit(deviceTask.getId(), NetflowDirection.DIRECTION_IN,
t.getValue());
log.info("DPTECH_UMC setup task {}, {} succeed: {}", t, NetflowDirection.DIRECTION_IN, deviceTask);
deviceTaskManager.setTaskErrRetryTimes(deviceTask.getId(), 0);
} else if (deviceTask.getErrRetry() < DisposeConfigValue.CALL_ERROR_RETRY_TIMES * 10) {
// 设置该任务为新任务待下次重试启动
// 记录任务出错重试次数
deviceTask.setErrRetry(deviceTask.getErrRetry() + 1);
deviceTaskManager.setTaskErrRetryTimes(deviceTask.getId(), deviceTask.getErrRetry());
//清除任务攻击类型启动标志
deviceTaskManager.execAttackTypeCleanBit(deviceTask.getId(), NetflowDirection.DIRECTION_IN,
t.getValue());
log.error("DPTECH_UMC setup task {}, {} times {} error: {}", t,
NetflowDirection.DIRECTION_IN, deviceTask.getErrRetry(), deviceTask);
} else {
log.error("DPTECH_UMC setup task {}, {} error {}: {}", t,
NetflowDirection.DIRECTION_IN, ret.getFirstParam(), deviceTask);
}
} }
} }
// 入方向
if (disposeTask.getFlowDirection() != NetflowDirection.DIRECTION_OUT) {
// 设置启动任务攻击类型状态
deviceTaskManager.execAttackTypeSetBit(deviceTask.getId(), NetflowDirection.DIRECTION_IN,
attackType.getValue());
// 调用迪普设备启动处置任务
ret = ai.getDb().runDispose(disposeTask.getDisposeObject(), disposeTask.getObjectType(),
disposeTask.getDisposeCapacity(), NetflowDirection.DIRECTION_IN,
attackType.getValue(), null);
if (ret.getFirstParam() == ErrorCode.ERR_OK) {
// 标志启动成功
deviceTaskManager.attackTypeStatusSetBit(deviceTask.getId(), NetflowDirection.DIRECTION_IN,
attackType.getValue());
log.info("DPTECH_UMC setup task {}, {} succeed: {}", attackType, NetflowDirection.DIRECTION_IN,
deviceTask);
deviceTaskManager.setTaskErrRetryTimes(deviceTask.getId(), 0);
} else if (deviceTask.getErrRetry() < DisposeConfigValue.CALL_ERROR_RETRY_TIMES * 10) {
// 设置该任务为新任务待下次重试启动
// 记录任务出错重试次数
deviceTask.setErrRetry(deviceTask.getErrRetry() + 1);
deviceTaskManager.setTaskErrRetryTimes(deviceTask.getId(), deviceTask.getErrRetry());
//清除任务攻击类型启动标志
deviceTaskManager.execAttackTypeCleanBit(deviceTask.getId(), NetflowDirection.DIRECTION_IN,
attackType.getValue());
log.error("DPTECH_UMC setup task {}, {} times {} error: {}", attackType,
NetflowDirection.DIRECTION_IN, deviceTask.getErrRetry(), deviceTask);
} else {
log.error("DPTECH_UMC setup task {}, {} error {}: {}", attackType,
NetflowDirection.DIRECTION_IN, ret.getFirstParam(), deviceTask);
}
}
// 检查需要处置的各种攻击类型任务启动状态与处置任务执行状态判断该处置任务是否调用成功 // 检查需要处置的各种攻击类型任务启动状态与处置任务执行状态判断该处置任务是否调用成功
boolean taskSetupSucceed = true; boolean taskSetupSucceed = true;
@ -468,7 +462,7 @@ public class DeviceTaskManagerServiceImpl implements DeviceTaskManagerService {
} }
// 对新建的任务创建对应处置设备任务信息 // 对新建的任务创建对应处置设备任务信息
for (DisposeTask v : disposeTaskManager.getNewDisposeTasks()) { for (DisposeTask v : disposeTaskManager.getUnExpiredTasks()) {
// 设置任务状态, 开始创建任务 // 设置任务状态, 开始创建任务
disposeTaskManager.changeDisposeTaskStatus(v.getId(), DisposeTaskStatus.TASK_STARTING); disposeTaskManager.changeDisposeTaskStatus(v.getId(), DisposeTaskStatus.TASK_STARTING);
@ -483,12 +477,22 @@ public class DeviceTaskManagerServiceImpl implements DeviceTaskManagerService {
.getDisposeCapacity())) .getDisposeCapacity()))
// 当前设备是否支持处置该IP // 当前设备是否支持处置该IP
.filter(c -> c.getDb().isCarryProtectIp(v.getDisposeObject())) .filter(c -> c.getDb().isCarryProtectIp(v.getDisposeObject()))
// 判断当前攻击类型是否支持
.filter(c -> c.getDb().isCarryAttackType(v.getAttackType()))
// 判断设备是否就绪
.filter(c -> c.getDb().deviceReady())
.forEach(d -> { .forEach(d -> {
log.info("Add dispose task for device: {}", d.getDev()); // 检查当前设备是否已经创建了该任务
if (deviceTaskManager.deviceTaskCreated(v.getId(),
d.getDev().getId())) {
return;
}
if (!deviceTaskManager.addDisposeDeviceTaskInfo(v.getId(), d.getDev().getId(), log.info("Add dispose task for device: {}", d.getDev());
d.getDb() if (!deviceTaskManager
.toDeviceAttackType(v.getAttackType()))) { .addDisposeDeviceTaskInfo(v.getId(),
d.getDev().getId(),
d.getDb().toDeviceAttackType(v.getAttackType()))) {
log.error("Add task {} to device {} error", v, d); log.error("Add task {} to device {} error", v, d);
} }
}); });
@ -534,6 +538,10 @@ public class DeviceTaskManagerServiceImpl implements DeviceTaskManagerService {
dpTechDeviceTaskRun(ai, v, task); dpTechDeviceTaskRun(ai, v, task);
break; break;
case DPTECH_BYPASS_UMC:
restfulDeviceTaskRun(ai, v, task, DisposeDeviceType.DPTECH_BYPASS_UMC);
break;
case HAOHAN_PLATFORM: case HAOHAN_PLATFORM:
restfulDeviceTaskRun(ai, v, task, DisposeDeviceType.HAOHAN_PLATFORM); restfulDeviceTaskRun(ai, v, task, DisposeDeviceType.HAOHAN_PLATFORM);
break; break;
@ -607,6 +615,10 @@ public class DeviceTaskManagerServiceImpl implements DeviceTaskManagerService {
dpTechDeviceTaskStop(ai, v, task); dpTechDeviceTaskStop(ai, v, task);
break; break;
case DPTECH_BYPASS_UMC:
restfulDeviceTaskStop(ai, v, task, DisposeDeviceType.DPTECH_BYPASS_UMC);
break;
case HAOHAN_PLATFORM: case HAOHAN_PLATFORM:
restfulDeviceTaskStop(ai, v, task, DisposeDeviceType.HAOHAN_PLATFORM); restfulDeviceTaskStop(ai, v, task, DisposeDeviceType.HAOHAN_PLATFORM);
break; break;

View File

@ -2,18 +2,22 @@ package com.dispose.service.impl;
import com.dispose.ability.DisposeAbility; import com.dispose.ability.DisposeAbility;
import com.dispose.ability.impl.DpTechAbilityImpl; import com.dispose.ability.impl.DpTechAbilityImpl;
import com.dispose.ability.impl.DpTechBypassAbilityImpl;
import com.dispose.ability.impl.HaoHanAbilityImpl; import com.dispose.ability.impl.HaoHanAbilityImpl;
import com.dispose.ability.impl.HuaWeiAbilityImpl;
import com.dispose.ability.impl.PengXinAbilityImpl; import com.dispose.ability.impl.PengXinAbilityImpl;
import com.dispose.ability.impl.VirtualAbilityImpl; import com.dispose.ability.impl.VirtualAbilityImpl;
import com.dispose.ability.impl.HuaWeiAbilityImpl;
import com.dispose.common.DisposeCapacityType; import com.dispose.common.DisposeCapacityType;
import com.dispose.common.ErrorCode; import com.dispose.common.ErrorCode;
import com.dispose.common.HttpType; import com.dispose.common.HttpType;
import com.dispose.manager.DisposeDeviceManager; import com.dispose.manager.DisposeDeviceManager;
import com.dispose.mapper.ServiceGroupMapper;
import com.dispose.pojo.entity.DisposeDevice; import com.dispose.pojo.entity.DisposeDevice;
import com.dispose.pojo.po.AbilityInfo; import com.dispose.pojo.po.AbilityInfo;
import com.dispose.service.DisposeAbilityRouterService; import com.dispose.service.DisposeAbilityRouterService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
@ -41,6 +45,12 @@ public class DisposeAbilityRouterServiceImpl implements DisposeAbilityRouterServ
@Resource @Resource
private DisposeDeviceManager disposeDeviceManager; private DisposeDeviceManager disposeDeviceManager;
/**
* The Service group mapper.
*/
@Resource
private ServiceGroupMapper serviceGroupMapper;
/** /**
* Init dispose ability. * Init dispose ability.
*/ */
@ -53,13 +63,14 @@ public class DisposeAbilityRouterServiceImpl implements DisposeAbilityRouterServ
/** /**
* Gets ability device. * Gets ability device.
* *
* @param ipAddr the ip addr * @param ipAddr the ip addr
* @param ipPort the ip port * @param ipPort the ip port
* @param deviceType the device type
* @return the ability device * @return the ability device
*/ */
@Override @Override
public AbilityInfo getAbilityDevice(String ipAddr, String ipPort) { public AbilityInfo getAbilityDevice(String ipAddr, String ipPort, String deviceType) {
return disposeAbilityMap.get(getAbilityDeviceHashKey(ipAddr, ipPort)); return disposeAbilityMap.get(getAbilityDeviceHashKey(ipAddr, ipPort, deviceType));
} }
/** /**
@ -71,12 +82,13 @@ public class DisposeAbilityRouterServiceImpl implements DisposeAbilityRouterServ
@Override @Override
public AbilityInfo getAbilityDevice(Long id) { public AbilityInfo getAbilityDevice(Long id) {
DisposeDevice dev = disposeDeviceManager.getAllNormalDisposeDevices().parallelStream() DisposeDevice dev = disposeDeviceManager.getAllNormalDisposeDevices().parallelStream()
.filter(v -> v.getId().equals(id)) .filter(v -> v.getId().equals(id))
.findAny() .findAny()
.orElse(null); .orElse(null);
if (dev != null) { if (dev != null) {
return disposeAbilityMap.get(getAbilityDeviceHashKey(dev.getIpAddr(), dev.getIpPort())); return disposeAbilityMap.get(getAbilityDeviceHashKey(dev.getIpAddr(), dev.getIpPort(),
String.valueOf(dev.getDeviceType())));
} }
return null; return null;
@ -103,7 +115,7 @@ public class DisposeAbilityRouterServiceImpl implements DisposeAbilityRouterServ
DisposeAbility db; DisposeAbility db;
String httpType = dev.getUrlType() == HttpType.HTTP ? "http://" : "https://"; String httpType = dev.getUrlType() == HttpType.HTTP ? "http://" : "https://";
String addr = getAbilityDeviceHashKey(dev.getIpAddr(), dev.getIpPort()); String addr = (dev.getIpPort() == null || dev.getIpPort().length() == 0) ? dev.getIpAddr() : (dev.getIpAddr() + ":" + dev.getIpPort());
String url = httpType + addr + "/" + dev.getUrlPath(); String url = httpType + addr + "/" + dev.getUrlPath();
switch (dev.getDeviceType()) { switch (dev.getDeviceType()) {
@ -122,6 +134,10 @@ public class DisposeAbilityRouterServiceImpl implements DisposeAbilityRouterServ
case VIRTUAL_DISPOSE: case VIRTUAL_DISPOSE:
db = new VirtualAbilityImpl(); db = new VirtualAbilityImpl();
break; break;
case DPTECH_BYPASS_UMC:
db = new DpTechBypassAbilityImpl();
db.upgradeServiceGroup(serviceGroupMapper.selectAll());
break;
default: default:
log.error("Unknown dispose device type: {}", dev.getDeviceType()); log.error("Unknown dispose device type: {}", dev.getDeviceType());
return ErrorCode.ERR_PARAMS; return ErrorCode.ERR_PARAMS;
@ -131,12 +147,15 @@ public class DisposeAbilityRouterServiceImpl implements DisposeAbilityRouterServ
db.initDeviceEnv(url, dev.getUserName(), dev.getPassword()); db.initDeviceEnv(url, dev.getUserName(), dev.getPassword());
db.getDisposeDeviceProtectObject(); db.getDisposeDeviceProtectObject();
String hashKey = getAbilityDeviceHashKey(dev.getIpAddr(), dev.getIpPort(),
String.valueOf(dev.getDeviceType()));
// 缓存处置设备到Hash表中 // 缓存处置设备到Hash表中
disposeAbilityMap.put(addr, AbilityInfo.builder() disposeAbilityMap.put(hashKey, AbilityInfo.builder()
.db(db) .db(db)
.dev(dev) .dev(dev)
.linkStatus(false) .linkStatus(false)
.build()); .build());
return ErrorCode.ERR_OK; return ErrorCode.ERR_OK;
} }
@ -153,24 +172,38 @@ public class DisposeAbilityRouterServiceImpl implements DisposeAbilityRouterServ
public ErrorCode verifyDisposeCapacity(Long deviceId, String disposeIp, DisposeCapacityType capacityType) { public ErrorCode verifyDisposeCapacity(Long deviceId, String disposeIp, DisposeCapacityType capacityType) {
if (getAllAbilityDevices().stream() if (getAllAbilityDevices().stream()
.noneMatch(f -> deviceId == -1 || f.getDev().getId().equals(deviceId))) { .noneMatch(f -> deviceId == -1 || f.getDev().getId().equals(deviceId))) {
return ErrorCode.ERR_NOSUCHDEVICE; return ErrorCode.ERR_NOSUCHDEVICE;
} }
if (getAllAbilityDevices().stream() if (getAllAbilityDevices().stream()
.noneMatch(c -> c.getDev().getDevCapacity().stream() .noneMatch(c -> c.getDev().getDevCapacity().stream()
.anyMatch(m -> m.getCapacityType() == capacityType))) { .anyMatch(m -> m.getCapacityType() == capacityType))) {
return ErrorCode.ERR_NOSUCHTYPE; return ErrorCode.ERR_NOSUCHTYPE;
} }
if (getAllAbilityDevices().stream() if (getAllAbilityDevices().stream()
.noneMatch(c -> c.getDb().isCarryProtectIp(disposeIp))) { .noneMatch(c -> c.getDb().isCarryProtectIp(disposeIp))) {
return ErrorCode.ERR_IPNODEVICE; return ErrorCode.ERR_IPNODEVICE;
} }
return ErrorCode.ERR_OK; return ErrorCode.ERR_OK;
} }
/**
* Run period task.
*/
@Override
@Async("deviceTaskExecutor")
@Scheduled(fixedDelay = 1000)
public void runPeriodTask() {
getAllAbilityDevices().forEach(v -> {
v.getDb().periodTaskRuntime();
// 同步最新处置平台业务信息到设备
v.getDb().upgradeServiceGroup(serviceGroupMapper.selectAll());
});
}
/** /**
* Gets ability device hash key. * Gets ability device hash key.
* *
@ -178,7 +211,8 @@ public class DisposeAbilityRouterServiceImpl implements DisposeAbilityRouterServ
* @param ipPort the ip port * @param ipPort the ip port
* @return the ability device hash key * @return the ability device hash key
*/ */
private String getAbilityDeviceHashKey(String ipAddr, String ipPort) { private String getAbilityDeviceHashKey(String ipAddr, String ipPort, String deviceType) {
return (ipPort == null || ipPort.length() == 0) ? ipAddr : (ipAddr + ":" + ipPort); String addrPort = ipPort == null || ipPort.length() == 0 ? ipAddr : (ipAddr + ":" + ipPort);
return addrPort + "-" + deviceType;
} }
} }

View File

@ -0,0 +1,53 @@
package com.dispose.service.impl;
import com.dispose.config.TemplateConfigure;
import com.dispose.pojo.vo.TemplateInfo;
import com.dispose.service.TemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* The type Template service.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Service
@Slf4j
public class TemplateServiceImpl implements TemplateService {
@Resource
TemplateConfigure templateConfigure;
/**
* Gets template.
*
* @param type the type
* @param bandWidth the band width
* @return the template
*/
@Override
public String getTemplate(String type, Long bandWidth) {
// 遍历所有模板
for (TemplateInfo v : templateConfigure.getUmcTemplate()) {
// 判断类型是否一致
if (v.getType().equals(type)) {
// 当前带宽大于当前模板最小值
if (bandWidth > v.getBandMin() || bandWidth == 0) {
// 模板最大值为-1或者带宽小于等于模板最小值返回模板名称
if (v.getBandMax() == -1 && bandWidth != 0) {
log.debug("Template analyze: {}, {} match {}", type, bandWidth, v);
return v.getName();
} else if (bandWidth <= v.getBandMax() && bandWidth >= v.getBandMin()) {
log.debug("Template analyze: {}, {} match {}", type, bandWidth, v);
return v.getName();
}
}
}
}
// 纪录异常日志
log.error("Template analyze: {}, {} match nothing!!!", type, bandWidth);
return null;
}
}

View File

@ -0,0 +1,93 @@
package com.dispose.service.impl;
import com.dispose.common.ErrorCode;
import com.dispose.manager.UserBusinessManager;
import com.dispose.pojo.entity.ServiceInfo;
import com.dispose.pojo.po.MulReturnType;
import com.dispose.service.UserBusinessManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* The type User business manager service.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@Service
@Slf4j
public class UserBusinessManagerServiceImpl implements UserBusinessManagerService {
/**
* The User business manager.
*/
@Resource
private UserBusinessManager userBusinessManager;
/**
* Add user business list.
*
* @param svrInfoList the svr info list
* @return the list
*/
@Override
public List<MulReturnType<ErrorCode, String>> addUserBusiness(List<ServiceInfo> svrInfoList) {
List<MulReturnType<ErrorCode, String>> rsp = new ArrayList<>();
for (ServiceInfo v : svrInfoList) {
rsp.add(new MulReturnType<>(
userBusinessManager.addUserBusiness(v),
v.getServiceId()
));
}
return rsp;
}
/**
* Upgrade user business list.
*
* @param svrInfoList the svr info list
* @return the list
*/
@Override
public List<MulReturnType<ErrorCode, String>> upgradeUserBusiness(List<ServiceInfo> svrInfoList) {
List<MulReturnType<ErrorCode, String>> rsp = new ArrayList<>();
for (ServiceInfo v : svrInfoList) {
// 删除旧业务
userBusinessManager.delUserBusiness(v.getServiceId());
// 添加新业务
rsp.add(new MulReturnType<>(
userBusinessManager.addUserBusiness(v),
v.getServiceId()
));
}
return rsp;
}
/**
* Del user business list.
*
* @param svrId the svr id
* @return the list
*/
@Override
public List<MulReturnType<ErrorCode, String>> delUserBusiness(String[] svrId) {
List<MulReturnType<ErrorCode, String>> rsp = new ArrayList<>();
for (String v : svrId) {
rsp.add(new MulReturnType<>(
userBusinessManager.delUserBusiness(v),
v
));
}
return rsp;
}
}

View File

@ -57,9 +57,6 @@ public class DeviceManagerTask {
((v.getDev().getIpPort() == null || v.getDev().getIpPort().length() == 0) ? "" : ((v.getDev().getIpPort() == null || v.getDev().getIpPort().length() == 0) ? "" :
":" + v.getDev().getIpPort()), ":" + v.getDev().getIpPort()),
ret.getFirstParam()); ret.getFirstParam());
// 更新设备保护对象
v.getDb().getDisposeDeviceProtectObject();
}); });
} }
} }

View File

@ -40,4 +40,13 @@ public class ThreadPoolConfig {
executor.setCorePoolSize(Runtime.getRuntime().availableProcessors()); executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
return executor; return executor;
} }
@Bean
public Executor dpTechTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("dpTechTask-");
executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() << 1 + 1);
executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
return executor;
}
} }

View File

@ -101,4 +101,12 @@ public interface ValidGroups {
*/ */
interface GetDevVerReqValid extends ProtocolCommonValid { interface GetDevVerReqValid extends ProtocolCommonValid {
} }
/**
* The interface Add device valid.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
interface AddUserInfoValid extends ProtocolCommonValid {
}
} }

View File

@ -5,6 +5,7 @@ import com.dispose.common.ErrorCode;
import com.dispose.restful.RestfulInterface; import com.dispose.restful.RestfulInterface;
import com.huawei.dispose.common.HuaWeiCreatDivertReq; import com.huawei.dispose.common.HuaWeiCreatDivertReq;
import com.huawei.dispose.common.HuaWeiLoginReq; import com.huawei.dispose.common.HuaWeiLoginReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
@ -14,6 +15,7 @@ import javax.servlet.http.HttpServletResponse;
* *
* @author <huangxin@cmhi.chinamoblie.com> * @author <huangxin@cmhi.chinamoblie.com>
*/ */
@Slf4j
public class HuaWeiInterface { public class HuaWeiInterface {
/** /**
* Auth http response. * Auth http response.
@ -60,6 +62,8 @@ public class HuaWeiInterface {
} }
} }
log.error("----HuaWei response [{}]: {}", response == null ? -1 : response.getStatus(), response);
return ErrorCode.ERR_UNKNOWNCMD; return ErrorCode.ERR_UNKNOWNCMD;
} }
@ -92,6 +96,7 @@ public class HuaWeiInterface {
} }
} }
log.error("----HuaWei response [{}]: {}", response == null ? -1 : response.getStatus(), response);
return ErrorCode.ERR_UNKNOWNCMD; return ErrorCode.ERR_UNKNOWNCMD;
} }

View File

@ -1,11 +1,11 @@
-- ---------------------------- -- ----------------------------
-- Records of dispose_device -- Records of dispose_device
-- ---------------------------- -- ----------------------------
INSERT INTO `dispose_device` VALUES (1, '10.88.77.15', '', 0, 0, '中移杭研实验室迪普清洗设备', 'DPTech', 'UMC', '5.7.13', 'admin', 'UMCAdministrator', 'UMC/service/AbnormalFlowCleaningService', 0, '实验室测试设备', 0);
-- INSERT INTO `dispose_device` VALUES (2, '10.88.77.88:18080', 1, 1, 0, '中移杭研实验室浩瀚清洗设备', 'HaoHan', 'Unknown', 'Unknown', '', '', 'http://%s/DDoSClean/clean', '实验室测试设备', 0);
-- id, deviceId, capacityType, objectType, ipType, protectIp, reserveNetflow
INSERT INTO `dispose_capacity` VALUES (1, 1, 0, 1, 3, '0.0.0.0', 10);
-- ---------------------------- -- ----------------------------
-- Records of user_account -- Records of user_account
-- ---------------------------- -- ----------------------------
INSERT INTO `user_account` VALUES (1, 'admin', 'c3855e6b6bb120450f160ba91134522868f89d36062f2061ebeefd80817e1d58', '2020-06-29 10:18:44', '0000-00-00 00:00:00', 0); INSERT INTO `user_account`
VALUES (1, 'admin', 'c3855e6b6bb120450f160ba91134522868f89d36062f2061ebeefd80817e1d58', '2020-11-13 09:25:19', '',
'2021-01-20 10:18:56', '1db9ddc47de514eb16b7ec07d7f7f96f7a714ae00e1209755bab30d543a0a2c3',
'2021-01-20 10:20:57', '1970-01-02 00:00:00', 0, 0);

View File

@ -11,7 +11,7 @@
Target Server Version : 50731 Target Server Version : 50731
File Encoding : 65001 File Encoding : 65001
Date: 11/09/2020 00:46:15 Date: 19/01/2021 15:22:39
*/ */
SET NAMES utf8mb4; SET NAMES utf8mb4;
@ -23,9 +23,9 @@ SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS `device_task`; DROP TABLE IF EXISTS `device_task`;
CREATE TABLE `device_task` CREATE TABLE `device_task`
( (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '任务信息唯一标识符', `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '任务信息唯一标识符',
`taskId` int(11) UNSIGNED NOT NULL COMMENT '处置任务唯一标识符', `taskId` bigint(11) NOT NULL COMMENT '处置任务唯一标识符',
`deviceId` int(10) UNSIGNED NOT NULL COMMENT '处置设备唯一标识符', `deviceId` bigint(11) NOT NULL COMMENT '处置设备唯一标识符',
`beginTime` timestamp(0) NULL DEFAULT NULL COMMENT '任务开始时间', `beginTime` timestamp(0) NULL DEFAULT NULL COMMENT '任务开始时间',
`endTime` timestamp(0) NULL DEFAULT NULL COMMENT '任务结束时间', `endTime` timestamp(0) NULL DEFAULT NULL COMMENT '任务结束时间',
`taskAttackType` bigint(255) UNSIGNED NOT NULL DEFAULT 0 COMMENT '需要处置的攻击类型', `taskAttackType` bigint(255) UNSIGNED NOT NULL DEFAULT 0 COMMENT '需要处置的攻击类型',
@ -34,9 +34,9 @@ CREATE TABLE `device_task`
`execAttackTypeOut` bigint(255) UNSIGNED NOT NULL DEFAULT 0 COMMENT '已经执行处置的攻击类型(Output)', `execAttackTypeOut` bigint(255) UNSIGNED NOT NULL DEFAULT 0 COMMENT '已经执行处置的攻击类型(Output)',
`attackTypeStatusOut` bigint(255) UNSIGNED NOT NULL DEFAULT 0 COMMENT '执行的攻击类型状态(Input)', `attackTypeStatusOut` bigint(255) UNSIGNED NOT NULL DEFAULT 0 COMMENT '执行的攻击类型状态(Input)',
`externId` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '扩展任务ID', `externId` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '扩展任务ID',
`errRetry` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '调用失败重试次数', `errRetry` int(11) UNSIGNED NOT NULL DEFAULT 0 COMMENT '调用失败重试次数',
`status` int(10) NOT NULL DEFAULT 0 COMMENT '任务状态', `status` int(11) NOT NULL DEFAULT 0 COMMENT '任务状态',
`devStatus` int(10) NOT NULL DEFAULT 0 COMMENT '设备任务状态', `devStatus` int(11) NOT NULL DEFAULT 0 COMMENT '设备任务状态',
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
INDEX `task_info_ibfk_1` (`taskId`) USING BTREE, INDEX `task_info_ibfk_1` (`taskId`) USING BTREE,
INDEX `task_info_ibfk_2` (`deviceId`) USING BTREE, INDEX `task_info_ibfk_2` (`deviceId`) USING BTREE,
@ -46,7 +46,7 @@ CREATE TABLE `device_task`
AUTO_INCREMENT = 1 AUTO_INCREMENT = 1
CHARACTER SET = utf8 CHARACTER SET = utf8
COLLATE = utf8_general_ci COLLATE = utf8_general_ci
ROW_FORMAT = Dynamic; ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
-- Table structure for dispose_capacity -- Table structure for dispose_capacity
@ -54,11 +54,11 @@ CREATE TABLE `device_task`
DROP TABLE IF EXISTS `dispose_capacity`; DROP TABLE IF EXISTS `dispose_capacity`;
CREATE TABLE `dispose_capacity` CREATE TABLE `dispose_capacity`
( (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '设备处置能力唯一标识符', `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '设备处置能力唯一标识符',
`deviceId` int(11) UNSIGNED NOT NULL COMMENT '设备ID', `deviceId` bigint(11) NOT NULL COMMENT '设备ID',
`capacityType` int(8) NOT NULL COMMENT '处置能力:\r\n0清洗\r\n1高防 \r\n2路由黑洞 \r\n3检测\r\n4WAF封堵\r\n', `capacityType` int(11) NOT NULL COMMENT '处置能力:\r\n0清洗\r\n1高防 \r\n2路由黑洞 \r\n3检测\r\n4WAF封堵\r\n',
`objectType` int(8) NOT NULL COMMENT '处置对象类型:\r\n0IP\r\n1域名 \r\n2URL', `objectType` int(11) NOT NULL COMMENT '处置对象类型:\r\n0IP\r\n1域名 \r\n2URL',
`ipType` int(8) NOT NULL DEFAULT 3 COMMENT 'IP 地址类型:\r\n1 << 0支持IPV4\r\n1 << 1支持IPV6', `ipType` int(11) NOT NULL DEFAULT 3 COMMENT 'IP 地址类型:\r\n1 << 0支持IPV4\r\n1 << 1支持IPV6',
`protectIp` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '该处置能力能够处置的IP', `protectIp` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '该处置能力能够处置的IP',
`reserveNetflow` int(11) NULL DEFAULT NULL COMMENT '清洗能力储备流量值,单位(G)', `reserveNetflow` int(11) NULL DEFAULT NULL COMMENT '清洗能力储备流量值,单位(G)',
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
@ -68,7 +68,7 @@ CREATE TABLE `dispose_capacity`
AUTO_INCREMENT = 1 AUTO_INCREMENT = 1
CHARACTER SET = utf8 CHARACTER SET = utf8
COLLATE = utf8_general_ci COLLATE = utf8_general_ci
ROW_FORMAT = Dynamic; ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
-- Table structure for dispose_device -- Table structure for dispose_device
@ -76,7 +76,7 @@ CREATE TABLE `dispose_capacity`
DROP TABLE IF EXISTS `dispose_device`; DROP TABLE IF EXISTS `dispose_device`;
CREATE TABLE `dispose_device` CREATE TABLE `dispose_device`
( (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '设备唯一标识符', `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '设备唯一标识符',
`ipAddr` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '设备IP地址, IPv4/IPv6', `ipAddr` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '设备IP地址, IPv4/IPv6',
`ipPort` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '端口', `ipPort` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '端口',
`deviceType` int(11) NOT NULL DEFAULT 0 COMMENT '能力节点类型0迪普UMC平台1浩瀚设备', `deviceType` int(11) NOT NULL DEFAULT 0 COMMENT '能力节点类型0迪普UMC平台1浩瀚设备',
@ -97,7 +97,7 @@ CREATE TABLE `dispose_device`
AUTO_INCREMENT = 1 AUTO_INCREMENT = 1
CHARACTER SET = utf8 CHARACTER SET = utf8
COLLATE = utf8_general_ci COLLATE = utf8_general_ci
ROW_FORMAT = Dynamic; ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
-- Table structure for dispose_task -- Table structure for dispose_task
@ -105,9 +105,9 @@ CREATE TABLE `dispose_device`
DROP TABLE IF EXISTS `dispose_task`; DROP TABLE IF EXISTS `dispose_task`;
CREATE TABLE `dispose_task` CREATE TABLE `dispose_task`
( (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '处置任务唯一标识符', `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '处置任务唯一标识符',
`deviceId` int(10) NOT NULL COMMENT '处置设备唯一标识符', `deviceId` bigint(11) NOT NULL COMMENT '处置设备唯一标识符',
`accountId` int(10) UNSIGNED NOT NULL COMMENT '用户唯一标识符', `accountId` bigint(11) NOT NULL COMMENT '用户唯一标识符',
`areaCode` int(11) NOT NULL DEFAULT -1 COMMENT '设备物理位置区域码', `areaCode` int(11) NOT NULL DEFAULT -1 COMMENT '设备物理位置区域码',
`disposeCapacity` int(11) NOT NULL COMMENT '处置能力类型0清洗 1高防 2黑洞 3检测', `disposeCapacity` int(11) NOT NULL COMMENT '处置能力类型0清洗 1高防 2黑洞 3检测',
`disposeObject` varchar(4096) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '处置对象', `disposeObject` varchar(4096) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '处置对象',
@ -116,8 +116,8 @@ CREATE TABLE `dispose_task`
`planEndTime` timestamp(0) NOT NULL DEFAULT '1970-01-02 00:00:00' COMMENT '计划结束时间', `planEndTime` timestamp(0) NOT NULL DEFAULT '1970-01-02 00:00:00' COMMENT '计划结束时间',
`endTime` timestamp(0) NULL DEFAULT '1970-01-02 00:00:00' COMMENT '实际结束时间', `endTime` timestamp(0) NULL DEFAULT '1970-01-02 00:00:00' COMMENT '实际结束时间',
`flowDirection` int(11) NOT NULL DEFAULT 2 COMMENT '流量方向, 0流入1流出2双向', `flowDirection` int(11) NOT NULL DEFAULT 2 COMMENT '流量方向, 0流入1流出2双向',
`attackType` bigint(20) UNSIGNED NOT NULL DEFAULT 18446744073709551615 COMMENT '攻击类型默认0 全部攻击', `attackType` bigint(20) NOT NULL DEFAULT 0 COMMENT '攻击类型默认0 全部攻击',
`flowBandWidth` int(10) UNSIGNED NULL DEFAULT 1024 COMMENT '攻击流量占用带宽(MB)', `flowBandWidth` int(11) UNSIGNED NULL DEFAULT 1024 COMMENT '攻击流量占用带宽(MB)',
`currentStatus` int(11) NOT NULL DEFAULT 0 COMMENT '状态0停止。1启动', `currentStatus` int(11) NOT NULL DEFAULT 0 COMMENT '状态0停止。1启动',
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
INDEX `dispose_task_device_capacity_id_fk` (`disposeCapacity`) USING BTREE, INDEX `dispose_task_device_capacity_id_fk` (`disposeCapacity`) USING BTREE,
@ -128,13 +128,31 @@ CREATE TABLE `dispose_task`
COLLATE = utf8_general_ci COLLATE = utf8_general_ci
ROW_FORMAT = DYNAMIC; ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Table structure for service_group
-- ----------------------------
DROP TABLE IF EXISTS `service_group`;
CREATE TABLE `service_group`
(
`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '业务ID唯一标识符',
`serviceId` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '业务ID',
`serviceType` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '业务类型SERVER,WEB,DNS,GAME',
`serviceBandwidth` int(11) NOT NULL DEFAULT 1 COMMENT '业务带宽单位M',
`serviceIp` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '业务IP地址逗号分割',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB
AUTO_INCREMENT = 1
CHARACTER SET = utf8
COLLATE = utf8_general_ci
ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
-- Table structure for user_account -- Table structure for user_account
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `user_account`; DROP TABLE IF EXISTS `user_account`;
CREATE TABLE `user_account` CREATE TABLE `user_account`
( (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账户唯一编号', `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '账户唯一编号',
`username` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名', `username` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
`password` varchar(512) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码', `password` varchar(512) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
`createTime` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', `createTime` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间',
@ -143,7 +161,7 @@ CREATE TABLE `user_account`
`token` varchar(512) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '用户token', `token` varchar(512) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '用户token',
`lastAccess` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '最后一次访问时间戳', `lastAccess` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '最后一次访问时间戳',
`lockTime` timestamp(0) NOT NULL DEFAULT '1970-01-02 00:00:00' COMMENT '账户锁定时间', `lockTime` timestamp(0) NOT NULL DEFAULT '1970-01-02 00:00:00' COMMENT '账户锁定时间',
`pwdErrTimes` int(10) NOT NULL DEFAULT 0 COMMENT '密码错误次数', `pwdErrTimes` int(11) NOT NULL DEFAULT 0 COMMENT '密码错误次数',
`status` int(11) NULL DEFAULT 0 COMMENT '账户状态', `status` int(11) NULL DEFAULT 0 COMMENT '账户状态',
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `USERNAME` (`username`) USING BTREE UNIQUE INDEX `USERNAME` (`username`) USING BTREE
@ -151,6 +169,6 @@ CREATE TABLE `user_account`
AUTO_INCREMENT = 1 AUTO_INCREMENT = 1
CHARACTER SET = utf8 CHARACTER SET = utf8
COLLATE = utf8_general_ci COLLATE = utf8_general_ci
ROW_FORMAT = Dynamic; ROW_FORMAT = DYNAMIC;
SET FOREIGN_KEY_CHECKS = 1; SET FOREIGN_KEY_CHECKS = 1;

View File

@ -70,6 +70,7 @@
LEFT JOIN dispose_capacity c ON d.id = c.deviceId LEFT JOIN dispose_capacity c ON d.id = c.deviceId
WHERE d.ipAddr = #{ipAddr} WHERE d.ipAddr = #{ipAddr}
AND d.ipPort = #{ipPort} AND d.ipPort = #{ipPort}
AND d.deviceType = #{devType}
</select> </select>
<select id="getDeviceById" resultMap="dispose_device"> <select id="getDeviceById" resultMap="dispose_device">

View File

@ -139,6 +139,15 @@
WHERE currentStatus = ${@com.dispose.common.DisposeTaskStatus@TASK_NEW.getValue()} WHERE currentStatus = ${@com.dispose.common.DisposeTaskStatus@TASK_NEW.getValue()}
</select> </select>
<select id="getUnExpiredTasks" resultType="com.dispose.pojo.entity.DisposeTask">
SELECT *
FROM dispose_task
WHERE currentStatus != ${@com.dispose.common.DisposeTaskStatus@TASK_FINISHED.getValue()}
AND currentStatus != ${@com.dispose.common.DisposeTaskStatus@TASK_CANCELED.getValue()}
AND currentStatus != ${@com.dispose.common.DisposeTaskStatus@TASK_EXPIRED.getValue()}
AND planEndTime > CURRENT_TIMESTAMP()
</select>
<select id="getExpiredTasks" resultType="com.dispose.pojo.entity.DisposeTask"> <select id="getExpiredTasks" resultType="com.dispose.pojo.entity.DisposeTask">
SELECT * SELECT *
FROM dispose_task FROM dispose_task

View File

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dispose.mapper.ServiceGroupMapper">
<resultMap id="service_grp" type="com.dispose.pojo.entity.ServiceInfo">
<id column="id" property="id"/>
<result column = "serviceId" property="serviceId"/>
<result column="serviceType" property="serviceType"/>
<result column="serviceBandwidth" property="serviceBandwidth"/>
<result column="serviceIp" property="serviceIp"/>
</resultMap>
<select id="selectAll" resultMap="service_grp">
SELECT *
FROM service_group
</select>
<select id="selectByServiceId" resultMap="service_grp">
SELECT *
FROM service_group
WHERE serviceId = #{serviceId}
</select>
<insert id="addServiceGroup" useGeneratedKeys="true" keyProperty="id"
parameterType="com.dispose.pojo.entity.ServiceInfo">
INSERT IGNORE INTO service_group(serviceId, serviceType, serviceBandwidth, serviceIp)
VALUES
<foreach collection="svrGrps" item="svg" separator=",">
(#{svg.serviceId}, #{svg.serviceType}, #{svg.serviceBandwidth}, #{svg.serviceIp})
</foreach>
</insert>
<delete id="delServiceGroupById">
DELETE
FROM service_group
WHERE service_group.id = #{id}
</delete>
<delete id="delServiceGroupByServiceId">
DELETE
FROM service_group
WHERE service_group.serviceId = #{serviceId}
</delete>
<!-- <select id="getDeviceDisposeCapacity" resultMap="dispose_capacity">-->
<!-- SELECT *-->
<!-- FROM dispose_capacity-->
<!-- WHERE dispose_capacity.deviceId = #{deviceId}-->
<!-- </select>-->
</mapper>

View File

@ -23,9 +23,9 @@ SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS `device_task`; DROP TABLE IF EXISTS `device_task`;
CREATE TABLE `device_task` CREATE TABLE `device_task`
( (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '任务信息唯一标识符', `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '任务信息唯一标识符',
`taskId` int(11) UNSIGNED NOT NULL COMMENT '处置任务唯一标识符', `taskId` bigint(11) NOT NULL COMMENT '处置任务唯一标识符',
`deviceId` int(10) UNSIGNED NOT NULL COMMENT '处置设备唯一标识符', `deviceId` bigint(11) NOT NULL COMMENT '处置设备唯一标识符',
`beginTime` timestamp(0) NULL DEFAULT NULL COMMENT '任务开始时间', `beginTime` timestamp(0) NULL DEFAULT NULL COMMENT '任务开始时间',
`endTime` timestamp(0) NULL DEFAULT NULL COMMENT '任务结束时间', `endTime` timestamp(0) NULL DEFAULT NULL COMMENT '任务结束时间',
`taskAttackType` bigint(255) UNSIGNED NOT NULL DEFAULT 0 COMMENT '需要处置的攻击类型', `taskAttackType` bigint(255) UNSIGNED NOT NULL DEFAULT 0 COMMENT '需要处置的攻击类型',
@ -34,9 +34,9 @@ CREATE TABLE `device_task`
`execAttackTypeOut` bigint(255) UNSIGNED NOT NULL DEFAULT 0 COMMENT '已经执行处置的攻击类型(Output)', `execAttackTypeOut` bigint(255) UNSIGNED NOT NULL DEFAULT 0 COMMENT '已经执行处置的攻击类型(Output)',
`attackTypeStatusOut` bigint(255) UNSIGNED NOT NULL DEFAULT 0 COMMENT '执行的攻击类型状态(Input)', `attackTypeStatusOut` bigint(255) UNSIGNED NOT NULL DEFAULT 0 COMMENT '执行的攻击类型状态(Input)',
`externId` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '扩展任务ID', `externId` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '扩展任务ID',
`errRetry` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '调用失败重试次数', `errRetry` int(11) UNSIGNED NOT NULL DEFAULT 0 COMMENT '调用失败重试次数',
`status` int(10) NOT NULL DEFAULT 0 COMMENT '任务状态', `status` int(11) NOT NULL DEFAULT 0 COMMENT '任务状态',
`devStatus` int(10) NOT NULL DEFAULT 0 COMMENT '设备任务状态', `devStatus` int(11) NOT NULL DEFAULT 0 COMMENT '设备任务状态',
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
INDEX `task_info_ibfk_1` (`taskId`) USING BTREE, INDEX `task_info_ibfk_1` (`taskId`) USING BTREE,
INDEX `task_info_ibfk_2` (`deviceId`) USING BTREE, INDEX `task_info_ibfk_2` (`deviceId`) USING BTREE,
@ -46,7 +46,7 @@ CREATE TABLE `device_task`
AUTO_INCREMENT = 1 AUTO_INCREMENT = 1
CHARACTER SET = utf8 CHARACTER SET = utf8
COLLATE = utf8_general_ci COLLATE = utf8_general_ci
ROW_FORMAT = Dynamic; ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
-- Records of device_task -- Records of device_task
@ -58,11 +58,11 @@ CREATE TABLE `device_task`
DROP TABLE IF EXISTS `dispose_capacity`; DROP TABLE IF EXISTS `dispose_capacity`;
CREATE TABLE `dispose_capacity` CREATE TABLE `dispose_capacity`
( (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '设备处置能力唯一标识符', `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '设备处置能力唯一标识符',
`deviceId` int(11) UNSIGNED NOT NULL COMMENT '设备ID', `deviceId` bigint(11) NOT NULL COMMENT '设备ID',
`capacityType` int(8) NOT NULL COMMENT '处置能力:\r\n0清洗\r\n1高防 \r\n2路由黑洞 \r\n3检测\r\n4WAF封堵\r\n', `capacityType` int(11) NOT NULL COMMENT '处置能力:\r\n0清洗\r\n1高防 \r\n2路由黑洞 \r\n3检测\r\n4WAF封堵\r\n',
`objectType` int(8) NOT NULL COMMENT '处置对象类型:\r\n0IP\r\n1域名 \r\n2URL', `objectType` int(11) NOT NULL COMMENT '处置对象类型:\r\n0IP\r\n1域名 \r\n2URL',
`ipType` int(8) NOT NULL DEFAULT 3 COMMENT 'IP 地址类型:\r\n1 << 0支持IPV4\r\n1 << 1支持IPV6', `ipType` int(11) NOT NULL DEFAULT 3 COMMENT 'IP 地址类型:\r\n1 << 0支持IPV4\r\n1 << 1支持IPV6',
`protectIp` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '该处置能力能够处置的IP', `protectIp` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '该处置能力能够处置的IP',
`reserveNetflow` int(11) NULL DEFAULT NULL COMMENT '清洗能力储备流量值,单位(G)', `reserveNetflow` int(11) NULL DEFAULT NULL COMMENT '清洗能力储备流量值,单位(G)',
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
@ -72,7 +72,7 @@ CREATE TABLE `dispose_capacity`
AUTO_INCREMENT = 1 AUTO_INCREMENT = 1
CHARACTER SET = utf8 CHARACTER SET = utf8
COLLATE = utf8_general_ci COLLATE = utf8_general_ci
ROW_FORMAT = Dynamic; ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
-- Records of dispose_capacity -- Records of dispose_capacity
@ -99,7 +99,7 @@ VALUES (7, 4, 0, 1, 3, '0.0.0.0', 10);
DROP TABLE IF EXISTS `dispose_device`; DROP TABLE IF EXISTS `dispose_device`;
CREATE TABLE `dispose_device` CREATE TABLE `dispose_device`
( (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '设备唯一标识符', `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '设备唯一标识符',
`ipAddr` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '设备IP地址, IPv4/IPv6', `ipAddr` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '设备IP地址, IPv4/IPv6',
`ipPort` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '端口', `ipPort` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '端口',
`deviceType` int(11) NOT NULL DEFAULT 0 COMMENT '能力节点类型0迪普UMC平台1浩瀚设备', `deviceType` int(11) NOT NULL DEFAULT 0 COMMENT '能力节点类型0迪普UMC平台1浩瀚设备',
@ -120,7 +120,7 @@ CREATE TABLE `dispose_device`
AUTO_INCREMENT = 1 AUTO_INCREMENT = 1
CHARACTER SET = utf8 CHARACTER SET = utf8
COLLATE = utf8_general_ci COLLATE = utf8_general_ci
ROW_FORMAT = Dynamic; ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
-- Records of dispose_device -- Records of dispose_device
@ -144,9 +144,9 @@ VALUES (4, '127.0.0.1', '1002', 999, 0, '虚拟处置设备', 'Virtual Dispose D
DROP TABLE IF EXISTS `dispose_task`; DROP TABLE IF EXISTS `dispose_task`;
CREATE TABLE `dispose_task` CREATE TABLE `dispose_task`
( (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '处置任务唯一标识符', `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '处置任务唯一标识符',
`deviceId` int(10) NOT NULL COMMENT '处置设备唯一标识符', `deviceId` bigint(11) NOT NULL COMMENT '处置设备唯一标识符',
`accountId` int(10) UNSIGNED NOT NULL COMMENT '用户唯一标识符', `accountId` bigint(11) NOT NULL COMMENT '用户唯一标识符',
`areaCode` int(11) NOT NULL DEFAULT -1 COMMENT '设备物理位置区域码', `areaCode` int(11) NOT NULL DEFAULT -1 COMMENT '设备物理位置区域码',
`disposeCapacity` int(11) NOT NULL COMMENT '处置能力类型0清洗 1高防 2黑洞 3检测', `disposeCapacity` int(11) NOT NULL COMMENT '处置能力类型0清洗 1高防 2黑洞 3检测',
`disposeObject` varchar(4096) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '处置对象', `disposeObject` varchar(4096) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '处置对象',
@ -155,8 +155,8 @@ CREATE TABLE `dispose_task`
`planEndTime` timestamp(0) NOT NULL DEFAULT '1970-01-02 00:00:00' COMMENT '计划结束时间', `planEndTime` timestamp(0) NOT NULL DEFAULT '1970-01-02 00:00:00' COMMENT '计划结束时间',
`endTime` timestamp(0) NULL DEFAULT '1970-01-02 00:00:00' COMMENT '实际结束时间', `endTime` timestamp(0) NULL DEFAULT '1970-01-02 00:00:00' COMMENT '实际结束时间',
`flowDirection` int(11) NOT NULL DEFAULT 2 COMMENT '流量方向, 0流入1流出2双向', `flowDirection` int(11) NOT NULL DEFAULT 2 COMMENT '流量方向, 0流入1流出2双向',
`attackType` bigint(20) UNSIGNED NOT NULL DEFAULT 18446744073709551615 COMMENT '攻击类型默认0 全部攻击', `attackType` bigint(20) NOT NULL DEFAULT 0 COMMENT '攻击类型默认0 全部攻击',
`flowBandWidth` int(10) UNSIGNED NULL DEFAULT 1024 COMMENT '攻击流量占用带宽(MB)', `flowBandWidth` int(11) UNSIGNED NULL DEFAULT 1024 COMMENT '攻击流量占用带宽(MB)',
`currentStatus` int(11) NOT NULL DEFAULT 0 COMMENT '状态0停止。1启动', `currentStatus` int(11) NOT NULL DEFAULT 0 COMMENT '状态0停止。1启动',
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
INDEX `dispose_task_device_capacity_id_fk` (`disposeCapacity`) USING BTREE, INDEX `dispose_task_device_capacity_id_fk` (`disposeCapacity`) USING BTREE,
@ -179,13 +179,31 @@ VALUES (2, -1, 1, -1, 0, '192.168.10.2', 1, CURRENT_TIMESTAMP, date_add(now(), i
8796093022207, 8796093022207,
1024, 0); 1024, 0);
-- ----------------------------
-- Table structure for service_group
-- ----------------------------
DROP TABLE IF EXISTS `service_group`;
CREATE TABLE `service_group`
(
`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '业务ID唯一标识符',
`serviceId` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '业务ID',
`serviceType` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '业务类型SERVER,WEB,DNS,GAME',
`serviceBandwidth` int(11) NOT NULL DEFAULT 1 COMMENT '业务带宽单位M',
`serviceIp` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '业务IP地址逗号分割',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB
AUTO_INCREMENT = 1
CHARACTER SET = utf8
COLLATE = utf8_general_ci
ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
-- Table structure for user_account -- Table structure for user_account
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `user_account`; DROP TABLE IF EXISTS `user_account`;
CREATE TABLE `user_account` CREATE TABLE `user_account`
( (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账户唯一编号', `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '账户唯一编号',
`username` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名', `username` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
`password` varchar(512) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码', `password` varchar(512) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
`createTime` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间', `createTime` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间',
@ -194,7 +212,7 @@ CREATE TABLE `user_account`
`token` varchar(512) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '用户token', `token` varchar(512) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '用户token',
`lastAccess` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '最后一次访问时间戳', `lastAccess` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '最后一次访问时间戳',
`lockTime` timestamp(0) NOT NULL DEFAULT '1970-01-02 00:00:00' COMMENT '账户锁定时间', `lockTime` timestamp(0) NOT NULL DEFAULT '1970-01-02 00:00:00' COMMENT '账户锁定时间',
`pwdErrTimes` int(10) NOT NULL DEFAULT 0 COMMENT '密码错误次数', `pwdErrTimes` int(11) NOT NULL DEFAULT 0 COMMENT '密码错误次数',
`status` int(11) NULL DEFAULT 0 COMMENT '账户状态', `status` int(11) NULL DEFAULT 0 COMMENT '账户状态',
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `USERNAME` (`username`) USING BTREE UNIQUE INDEX `USERNAME` (`username`) USING BTREE
@ -202,8 +220,7 @@ CREATE TABLE `user_account`
AUTO_INCREMENT = 1 AUTO_INCREMENT = 1
CHARACTER SET = utf8 CHARACTER SET = utf8
COLLATE = utf8_general_ci COLLATE = utf8_general_ci
ROW_FORMAT = Dynamic; ROW_FORMAT = DYNAMIC;
-- ---------------------------- -- ----------------------------
-- Records of user_account -- Records of user_account
-- ---------------------------- -- ----------------------------

View File

@ -26,7 +26,7 @@ import java.util.Optional;
@Data @Data
@Slf4j @Slf4j
@EnableEncryptableProperties @EnableEncryptableProperties
@ActiveProfiles({"test", "dispose"}) @ActiveProfiles({"test", "dispose", "template"})
public class CommonEnvironment { public class CommonEnvironment {
/** /**

View File

@ -26,7 +26,7 @@ import javax.annotation.Resource;
@Slf4j @Slf4j
@Getter @Getter
@EnableEncryptableProperties @EnableEncryptableProperties
@ActiveProfiles({"test", "dispose"}) @ActiveProfiles({"test", "dispose", "template"})
public class InitTestEnvironment { public class InitTestEnvironment {
/** /**
* The constant HTTP_CONNECT_TIMEOUT. * The constant HTTP_CONNECT_TIMEOUT.

View File

@ -0,0 +1,58 @@
package com.dispose.test.dev.config;
import com.dispose.common.Helper;
import com.dispose.config.TemplateConfigure;
import com.dispose.service.impl.TemplateServiceImpl;
import com.dispose.test.dev.Global.InitTestEnvironment;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
/**
* The type Template configure test.
*
* @author <huangxin@cmhi.chinamoblie.com>
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class TemplateConfigureTest extends InitTestEnvironment {
/**
* The Template configure.
*/
@Resource
TemplateConfigure templateConfigure;
/**
* The Template service.
*/
@Resource
TemplateServiceImpl templateService;
/**
* Template loads test.
*/
@Test
public void templateLoadsTest() {
log.info("Load template: {}", templateConfigure.getUmcTemplate());
Assert.assertEquals(9, templateConfigure.getUmcTemplate().size());
}
/**
* Template get test.
*/
@Test
public void templateGetTest() {
for (String v : new String[]{"DNS", "GAME", "WEB", "GENERAL"}) {
for (Long k : new Long[]{0L, 200L, 500L, 800L, 1500L, 1600L}) {
log.info("[{}, {}] with template: {}", v, k,
Helper.getDpTemplate(v, k));
}
}
}
}

View File

@ -0,0 +1,138 @@
package com.dispose.test.dev.controller;
import com.dispose.common.ConstValue;
import com.dispose.common.ErrorCode;
import com.dispose.common.ProtoCryptoType;
import com.dispose.mapper.ServiceGroupMapper;
import com.dispose.pojo.dto.protocol.base.ProtocolReqDTO;
import com.dispose.pojo.dto.protocol.base.ProtocolRespDTO;
import com.dispose.pojo.dto.protocol.device.business.AddUserSvrReq;
import com.dispose.pojo.dto.protocol.device.business.AddUserSvrRsp;
import com.dispose.pojo.dto.protocol.device.business.UserSvrInfo;
import com.dispose.service.UserBusinessManagerService;
import com.dispose.test.dev.Global.InitTestEnvironment;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jodd.net.HttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Transactional
@Rollback
@Slf4j
public class UserBusinessControllerTest extends InitTestEnvironment {
/**
* The Mock mvc.
*/
@Resource
private MockMvc mockMvc;
/**
* The Object mapper.
*/
@Resource
private ObjectMapper objectMapper;
/**
* The User business manager service.
*/
@Resource
private UserBusinessManagerService userBusinessManagerService;
/**
* The service group mapper.
*/
@Resource
private ServiceGroupMapper serviceGroupMapper;
/**
* A 1 add user business test.
*
* @throws Exception the exception
*/
@Test
public void a1_addUserBusinessTest() throws Exception{
List<UserSvrInfo> newList = new ArrayList<>();
newList.add(UserSvrInfo.builder()
.businessId("controller1")
.businessType("GAME")
.businessIp("192.168.1.1")
.businessBandwidth("50")
.build());
newList.add(UserSvrInfo.builder()
.businessId("controller2")
.businessType("GAME")
.businessIp("192.168.1.2")
.businessBandwidth("150")
.build());
AddUserSvrReq req = AddUserSvrReq.builder()
.items(newList)
.build();
ProtocolReqDTO<AddUserSvrReq> reqInfo = new ProtocolReqDTO<>();
reqInfo.setVer(ConstValue.Protocol.VERSION);
reqInfo.setCryptoType(ProtoCryptoType.CRYPTO_NONE.getCode());
reqInfo.setTimeStamp(System.currentTimeMillis());
reqInfo.setMsgContent(req);
log.info("reqIfo: {}",reqInfo);
String ret = mockMvc.perform(MockMvcRequestBuilders
.put("/business/manage")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", ConstValue.STRING_HTTP_AUTH_HEAD + getLoginToken())
.content(objectMapper.writeValueAsString(reqInfo)))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(HttpStatus.ok().status()))
.andReturn()
.getResponse()
.getContentAsString();
ProtocolRespDTO<AddUserSvrRsp> rspInfo = objectMapper.readValue(ret,
new TypeReference<ProtocolRespDTO<AddUserSvrRsp>>() {
});
verifyRespProtocol(rspInfo);
log.debug(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rspInfo));
Assert.assertNotNull(rspInfo.getMsgContent().getItems());
rspInfo.getMsgContent().getItems().forEach(k -> {
Assert.assertNotNull(k.getStatus());
if (k.getStatus() == ErrorCode.ERR_OK.getCode()) {
Assert.assertNotNull(k.getMessage());
Assert.assertNotNull(k.getBusinessId());
Assert.assertTrue(serviceGroupMapper.selectAll().stream().anyMatch(v ->
k.getBusinessId().equals(v.getServiceId())
));
}
});
}
}

View File

@ -26,7 +26,9 @@ import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Hashtable;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@ -607,4 +609,61 @@ public class demo {
@Test @Test
public void codeDebug() { public void codeDebug() {
} }
/**
* Dp ip segment test.
*/
@Test
public void dpIpSegmentTest() {
String ipSegmentString = "1_192.168.10.1-192.168.10.12,2_192.168.1.2-192.168.1.20,3_-";
Arrays.stream(ipSegmentString.split(",")).forEach(
k -> {
String value = k.replaceAll("\\d+_", "");
String key = k.replace(value, "").replace("_", "");
if (Pattern.matches(ConstValue.ipAddrSegmentReg(), value)) {
log.info("Result: {}, {}", key, value);
} else {
log.error("Result: {}, {} error", key, value);
}
}
);
}
/**
* List to string with char test.
*/
@Test
public void listToStringWithCharTest() {
List<String> demoList = new ArrayList<>();
List<String> demoList2 = new ArrayList<>();
Hashtable<String, String> tmpTable = new Hashtable<>();
Hashtable<String, String> tmpTable2 = new Hashtable<>();
demoList.add("192.168.0.1");
demoList.add("192.168.0.2");
demoList.add("192.168.0.24/24");
demoList2.add("192.168.0.2");
demoList2.add("192.168.0.1");
demoList2.add("192.168.0.24/24");
//demoList2.add("192.168.0.24/23");
tmpTable.put("1", "192.168.0.1");
tmpTable.put("2", "192.168.0.2");
tmpTable.put("3", "192.168.0.3");
tmpTable2.put("2", "192.168.0.2");
tmpTable2.put("1", "192.168.0.1");
tmpTable2.put("3", "192.168.0.3");
log.info("Result demoList: {}", String.join(",", demoList));
log.info("Result demoList: {}", String.join(",", demoList2));
log.info("demoList difference demoList2: {}", demoList2.containsAll(demoList));
log.info("demoList2 difference demoList1: {}", demoList.containsAll(demoList2));
log.info("demoList2 difference demoList1: {}", demoList.equals(demoList2));
log.info("tmpTable difference tmpTable: {}", tmpTable.equals(tmpTable2));
}
} }

View File

@ -200,7 +200,8 @@ public class DisposeDeviceManagerTest extends InitTestEnvironment {
) { ) {
MulReturnType<ErrorCode, ObjectStatus> ret = disposeDeviceManager.changeDisposeDeviceStatus(v.getId(), obj); MulReturnType<ErrorCode, ObjectStatus> ret = disposeDeviceManager.changeDisposeDeviceStatus(v.getId(), obj);
DisposeDevice dev = disposeDeviceMapper.getDeviceByAddress(v.getIpAddr(), v.getIpPort()); DisposeDevice dev = disposeDeviceMapper.getDeviceByAddress(v.getIpAddr(), v.getIpPort(),
v.getDeviceType().getValue());
if (ret.getFirstParam() == ErrorCode.ERR_OK) { if (ret.getFirstParam() == ErrorCode.ERR_OK) {
Assert.assertNotNull(dev); Assert.assertNotNull(dev);

View File

@ -114,7 +114,8 @@ public class DisposeDeviceMapperTest extends InitTestEnvironment {
devList.forEach(v -> { devList.forEach(v -> {
if(v.getIpPort().length() != 0){ if(v.getIpPort().length() != 0){
DisposeDevice dev = disposeDeviceMapper.getDeviceByAddress(v.getIpAddr(), v.getIpPort()); DisposeDevice dev = disposeDeviceMapper.getDeviceByAddress(v.getIpAddr(), v.getIpPort(),
v.getDeviceType().getValue());
String beforeVer = dev.getVersion(); String beforeVer = dev.getVersion();
if (dev.getVersion().equals("B5.2.27.7")) { if (dev.getVersion().equals("B5.2.27.7")) {
@ -164,12 +165,14 @@ public class DisposeDeviceMapperTest extends InitTestEnvironment {
List<DisposeDevice> devList = disposeDeviceMapper.selectAll(); List<DisposeDevice> devList = disposeDeviceMapper.selectAll();
devList.forEach(v -> { devList.forEach(v -> {
DisposeDevice dev = disposeDeviceMapper.getDeviceByAddress(v.getIpAddr(), v.getIpPort()); DisposeDevice dev = disposeDeviceMapper.getDeviceByAddress(v.getIpAddr(), v.getIpPort(),
v.getDeviceType().getValue());
Assert.assertNotNull(dev); Assert.assertNotNull(dev);
if(v.getIpPort().length() != 0){ if(v.getIpPort().length() != 0){
dev = disposeDeviceMapper.getDeviceByAddress(v.getIpAddr(), dev = disposeDeviceMapper.getDeviceByAddress(v.getIpAddr(),
String.valueOf(Long.parseLong(Optional.ofNullable(v.getIpPort()).orElse("123")) + 1233)); String.valueOf(Long.parseLong(Optional.ofNullable(v.getIpPort()).orElse("123")) + 1233),
v.getDeviceType().getValue());
Assert.assertNull(dev); Assert.assertNull(dev);
} }

View File

@ -0,0 +1,157 @@
package com.dispose.test.dev.mapper;
import com.dispose.mapper.ServiceGroupMapper;
import com.dispose.pojo.entity.ServiceInfo;
import com.dispose.test.dev.Global.InitTestEnvironment;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
//@FixMethodOrder(MethodSorters.NAME_ASCENDING)
//@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
//@Transactional
//@Rollback
public class ServiceGroupMapperTest extends InitTestEnvironment {
/**
* The service group mapper.
*/
@Resource
private ServiceGroupMapper serviceGroupMapper;
/**
* The Object mapper.
*/
@Resource
private ObjectMapper objectMapper;
/**
* A 1 select all.
*
* @throws JsonProcessingException the json processing exception
*/
@Test
public void a1_selectAllTest() throws JsonProcessingException{
List<ServiceInfo> serviceList = serviceGroupMapper.selectAll();
//Assert.assertNotNull(serviceList);
//Assert.assertNotEquals(serviceList.size(), 0);
log.info("Database: {}", objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(serviceList));
}
/**
* A 2 add new service group.
*
* @throws JsonProcessingException the json processing exception
*/
@Test
public void a2_addServiceGroup() throws JsonProcessingException{
List<ServiceInfo> service = new ArrayList<>();
service.add(ServiceInfo.builder()
.serviceId("100")
.serviceType("GAME")
.serviceBandwidth(1000L)
.serviceIp("192.168.100.1-192.168.100.10,192.168.100.20-192.168.100.21")
.build());
service.add(ServiceInfo.builder()
.serviceId("101")
.serviceType("DNS")
.serviceBandwidth(2000L)
.serviceIp("192.168.101.1-192.168.101.10")
.build());
int num = serviceGroupMapper.addServiceGroup(service);
Assert.assertEquals(num, service.size());
log.info("add num {}: {}", num, objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(service));
List<ServiceInfo> serviceList = serviceGroupMapper.selectAll();
Assert.assertNotNull(serviceList);
Assert.assertNotEquals(serviceList.size(), 0);
log.info("Database: {}", objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(serviceList));
}
/**
* A 3 delete service group by id.
*/
@Test
public void a3_delServiceGroupByIdTest(){
List<ServiceInfo> service = new ArrayList<>();
service.add(ServiceInfo.builder()
.serviceId("102")
.serviceType("GAME")
.serviceBandwidth(1000L)
.serviceIp("192.168.102.1-192.168.102.10,192.168.102.20-192.168.102.21")
.build());
service.add(ServiceInfo.builder()
.serviceId("103")
.serviceType("DNS")
.serviceBandwidth(2000L)
.serviceIp("192.168.103.1-192.168.103.10")
.build());
serviceGroupMapper.addServiceGroup(service);
log.info("service number: {}", serviceGroupMapper.selectAll().size());
serviceGroupMapper.selectAll().forEach(v -> {
int ret = serviceGroupMapper.delServiceGroupById(v.getId());
try {
log.info("service info: {}", objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(v));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
Assert.assertEquals(1,ret);
});
log.info("service after delete operate: {}", serviceGroupMapper.selectAll());
Assert.assertEquals(0,serviceGroupMapper.selectAll().size());
}
/**
* A 4 delete service group by service id.
*/
@Test
public void a4_delServiceGroupByServiceIdTest(){
List<ServiceInfo> service = new ArrayList<>();
service.add(ServiceInfo.builder()
.serviceId("104")
.serviceType("GAME")
.serviceBandwidth(1000L)
.serviceIp("192.168.104.1-192.168.104.10,192.168.104.20-192.168.104.21")
.build());
service.add(ServiceInfo.builder()
.serviceId("105")
.serviceType("DNS")
.serviceBandwidth(2000L)
.serviceIp("192.168.105.1-192.168.105.10")
.build());
serviceGroupMapper.addServiceGroup(service);
log.info("service number: {}", serviceGroupMapper.selectAll().size());
serviceGroupMapper.selectAll().forEach(v -> {
int ret = serviceGroupMapper.delServiceGroupByServiceId(v.getServiceId());
try {
log.info("service info: {}", objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(v));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
Assert.assertEquals(1,ret);
});
log.info("service after delete operate: {}", serviceGroupMapper.selectAll());
Assert.assertEquals(0,serviceGroupMapper.selectAll().size());
}
}

View File

@ -149,7 +149,8 @@ public class DisposeAbilityRouterServiceTest extends InitTestEnvironment {
e.printStackTrace(); e.printStackTrace();
} }
AbilityInfo abilityInfo = disposeAbilityRouterService.getAbilityDevice(v.getIpAddr(), v.getIpPort()); AbilityInfo abilityInfo = disposeAbilityRouterService.getAbilityDevice(v.getIpAddr(), v.getIpPort(),
String.valueOf(v.getDeviceType()));
Assert.assertNotNull(abilityInfo); Assert.assertNotNull(abilityInfo);
@ -251,7 +252,8 @@ public class DisposeAbilityRouterServiceTest extends InitTestEnvironment {
log.info(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(deviceList)); log.info(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(deviceList));
deviceList.forEach(v -> { deviceList.forEach(v -> {
AbilityInfo abilityInfo = disposeAbilityRouterService.getAbilityDevice(v.getIpAddr(), v.getIpPort()); AbilityInfo abilityInfo = disposeAbilityRouterService.getAbilityDevice(v.getIpAddr(), v.getIpPort(),
String.valueOf(v.getDeviceType()));
Assert.assertNotNull(abilityInfo); Assert.assertNotNull(abilityInfo);
Assert.assertNotNull(abilityInfo.getDev()); Assert.assertNotNull(abilityInfo.getDev());

View File

@ -0,0 +1,62 @@
package com.dispose.test.dev.service;
import com.dispose.service.TemplateService;
import com.dispose.test.dev.Global.InitTestEnvironment;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
@Transactional
@Rollback
public class TemplateServiceTest extends InitTestEnvironment {
@Resource
private TemplateService templateService;
@Test
public void getTemplateTest() {
Assert.assertEquals("Game_Server_10G", templateService.getTemplate("GAME",1600L));
Assert.assertEquals("Game_Server_1G", templateService.getTemplate("GAME",1500L));
Assert.assertEquals("Game_Server_1G", templateService.getTemplate("GAME", 100L));
Assert.assertEquals("Game_Server_1G", templateService.getTemplate("GAME", 1L));
Assert.assertEquals("Game_Server_1G", templateService.getTemplate("GAME", 0L));
Assert.assertNull(templateService.getTemplate("GAME",-1L));
Assert.assertEquals("DNS_Server_10G", templateService.getTemplate("DNS",1600L));
Assert.assertEquals("DNS_Server_1G", templateService.getTemplate("DNS",1500L));
Assert.assertEquals("DNS_Server_1G", templateService.getTemplate("DNS",1L));
Assert.assertEquals("DNS_Server_1G", templateService.getTemplate("DNS",0L));
Assert.assertNull(templateService.getTemplate("DNS",-1L));
Assert.assertEquals("WEB_Server_10G", templateService.getTemplate("WEB",1600L));
Assert.assertEquals("WEB_Server_1G", templateService.getTemplate("WEB",1500L));
Assert.assertEquals("WEB_Server_1G", templateService.getTemplate("WEB",1L));
Assert.assertEquals("WEB_Server_1G", templateService.getTemplate("WEB",0L));
Assert.assertNull(templateService.getTemplate("WEB",-1L));
Assert.assertEquals("General_Server_10G", templateService.getTemplate("GENERAL",1600L));
Assert.assertEquals("General_Server_1G", templateService.getTemplate("GENERAL",1500L));
Assert.assertEquals("General_Server_100M", templateService.getTemplate("GENERAL",500L));
Assert.assertEquals("General_Server_100M", templateService.getTemplate("GENERAL",1L));
Assert.assertEquals("General_Server_100M", templateService.getTemplate("GENERAL",0L));
Assert.assertNull(templateService.getTemplate("GENERAL",-1L));
Assert.assertNull(templateService.getTemplate("ALL",100L));
}
}

View File

@ -196,7 +196,8 @@ public class P1All {
Assert.assertNotNull(k.getDevStatus()); Assert.assertNotNull(k.getDevStatus());
}); });
DisposeDevice dev = c.getDisposeDeviceMapper().getDeviceByAddress("127.0.0.1", ""); DisposeDevice dev = c.getDisposeDeviceMapper().getDeviceByAddress("127.0.0.1", "",
DisposeDeviceType.VIRTUAL_DISPOSE.getValue());
Assert.assertNotNull(dev); Assert.assertNotNull(dev);

View File

@ -363,7 +363,7 @@ public class P2DeviceAdd {
.method(RequestMethod.PUT) .method(RequestMethod.PUT)
.caseJsonValue("{\"ver\":3,\"cryptoType\":0,\"timeStamp\":1599094454403," + .caseJsonValue("{\"ver\":3,\"cryptoType\":0,\"timeStamp\":1599094454403," +
"\"msgContent\":{\"items\":[{\"ipAddr\":\"127.0.0.1\",\"ipPort\":\"\"," + "\"msgContent\":{\"items\":[{\"ipAddr\":\"127.0.0.1\",\"ipPort\":\"\"," +
"\"deviceType\":0,\"areaCode\":0,\"deviceName\":\"中移杭研实验室迪普清洗设备\"," + "\"deviceType\":999,\"areaCode\":0,\"deviceName\":\"中移杭研实验室迪普清洗设备\"," +
"\"manufacturer\":\"DPTech\",\"model\":\"UMC\",\"version\":\"5.7.13\"," + "\"manufacturer\":\"DPTech\",\"model\":\"UMC\",\"version\":\"5.7.13\"," +
"\"userName\":\"test\",\"password\":\"testpassword\"," + "\"userName\":\"test\",\"password\":\"testpassword\"," +
"\"urlPath\":\"UMC/service/AbnormalFlowCleaningService\",\"urlType\":0," + "\"urlPath\":\"UMC/service/AbnormalFlowCleaningService\",\"urlType\":0," +
@ -797,7 +797,8 @@ public class P2DeviceAdd {
Assert.assertNotNull(k.getDevId()); Assert.assertNotNull(k.getDevId());
}); });
DisposeDevice dev = c.getDisposeDeviceMapper().getDeviceByAddress("10.88.77.15", ""); DisposeDevice dev = c.getDisposeDeviceMapper().getDeviceByAddress("10.88.77.15", "", DisposeDeviceType.DPTECH_UMC
.getValue());
Assert.assertNotNull(dev); Assert.assertNotNull(dev);
Assert.assertEquals(dev.getDeviceType(), DisposeDeviceType.DPTECH_UMC); Assert.assertEquals(dev.getDeviceType(), DisposeDeviceType.DPTECH_UMC);

View File

@ -37,7 +37,7 @@ public class P2DeviceUpgrade {
.method(RequestMethod.POST) .method(RequestMethod.POST)
.caseJsonValue("{\"ver\":3,\"cryptoType\":0,\"timeStamp\":1599094454403," + .caseJsonValue("{\"ver\":3,\"cryptoType\":0,\"timeStamp\":1599094454403," +
"\"msgContent\":{\"items\":[{\"ipAddr\":\"127.0.0.1\",\"ipPort\":\"\"," + "\"msgContent\":{\"items\":[{\"ipAddr\":\"127.0.0.1\",\"ipPort\":\"\"," +
"\"deviceType\":0,\"areaCode\":0,\"deviceName\":\"中移杭研实验室迪普清洗设备\"," + "\"deviceType\":999,\"areaCode\":0,\"deviceName\":\"中移杭研实验室迪普清洗设备\"," +
"\"manufacturer\":\"DPTech\",\"model\":\"UMC\",\"version\":\"5.7.13\"," + "\"manufacturer\":\"DPTech\",\"model\":\"UMC\",\"version\":\"5.7.13\"," +
"\"userName\":\"admin\",\"password\":\"testpassword\"," + "\"userName\":\"admin\",\"password\":\"testpassword\"," +
"\"urlPath\":\"UMC/service/AbnormalFlowCleaningService\",\"urlType\":0," + "\"urlPath\":\"UMC/service/AbnormalFlowCleaningService\",\"urlType\":0," +
@ -48,7 +48,7 @@ public class P2DeviceUpgrade {
.rspCode(ErrorCode.ERR_OK) .rspCode(ErrorCode.ERR_OK)
.autoLogin(true) .autoLogin(true)
.verifyCallback((VerifyProtoRespCallback<CommDeviceListRsp>) (v, e, c) -> { .verifyCallback((VerifyProtoRespCallback<CommDeviceListRsp>) (v, e, c) -> {
DisposeDevice dev = verifyDpTechDeviceAddResp(v, e, c, DisposeDeviceType.DPTECH_UMC, new HashMap<>()); DisposeDevice dev = verifyDpTechDeviceAddResp(v, e, c, DisposeDeviceType.VIRTUAL_DISPOSE, new HashMap<>());
Assert.assertEquals(dev.getDevCapacity().size(), 2); Assert.assertEquals(dev.getDevCapacity().size(), 2);
dev.getDevCapacity().forEach(k -> { dev.getDevCapacity().forEach(k -> {
@ -73,7 +73,7 @@ public class P2DeviceUpgrade {
.method(RequestMethod.POST) .method(RequestMethod.POST)
.caseJsonValue("{\"ver\":3,\"cryptoType\":0,\"timeStamp\":1599094454403," + .caseJsonValue("{\"ver\":3,\"cryptoType\":0,\"timeStamp\":1599094454403," +
"\"msgContent\":{\"items\":[{\"ipAddr\":\"127.0.0.1\",\"ipPort\":\"\"," + "\"msgContent\":{\"items\":[{\"ipAddr\":\"127.0.0.1\",\"ipPort\":\"\"," +
"\"deviceType\":0,\"areaCode\":0,\"deviceName\":\"中移杭研实验室迪普清洗设备\"," + "\"deviceType\":999,\"areaCode\":0,\"deviceName\":\"中移杭研实验室迪普清洗设备\"," +
"\"manufacturer\":\"DPTech\",\"model\":\"UMC\",\"version\":\"5.7.13\"," + "\"manufacturer\":\"DPTech\",\"model\":\"UMC\",\"version\":\"5.7.13\"," +
"\"userName\":\"admin\",\"password\":\"testpassword\"," + "\"userName\":\"admin\",\"password\":\"testpassword\"," +
"\"urlPath\":\"UMC/service/AbnormalFlowCleaningService\",\"urlType\":0," + "\"urlPath\":\"UMC/service/AbnormalFlowCleaningService\",\"urlType\":0," +
@ -84,7 +84,7 @@ public class P2DeviceUpgrade {
.rspCode(ErrorCode.ERR_OK) .rspCode(ErrorCode.ERR_OK)
.autoLogin(true) .autoLogin(true)
.verifyCallback((VerifyProtoRespCallback<CommDeviceListRsp>) (v, e, c) -> { .verifyCallback((VerifyProtoRespCallback<CommDeviceListRsp>) (v, e, c) -> {
DisposeDevice dev = verifyDpTechDeviceAddResp(v, e, c, DisposeDeviceType.DPTECH_UMC, new HashMap<>()); DisposeDevice dev = verifyDpTechDeviceAddResp(v, e, c, DisposeDeviceType.VIRTUAL_DISPOSE, new HashMap<>());
Assert.assertEquals(dev.getDevCapacity().size(), 2); Assert.assertEquals(dev.getDevCapacity().size(), 2);
dev.getDevCapacity().forEach(k -> { dev.getDevCapacity().forEach(k -> {
@ -109,7 +109,7 @@ public class P2DeviceUpgrade {
.method(RequestMethod.POST) .method(RequestMethod.POST)
.caseJsonValue("{\"ver\":3,\"cryptoType\":0,\"timeStamp\":1599094454403," + .caseJsonValue("{\"ver\":3,\"cryptoType\":0,\"timeStamp\":1599094454403," +
"\"msgContent\":{\"items\":[{\"ipAddr\":\"127.0.0.1\",\"ipPort\":\"\"," + "\"msgContent\":{\"items\":[{\"ipAddr\":\"127.0.0.1\",\"ipPort\":\"\"," +
"\"deviceType\":0,\"areaCode\":0,\"deviceName\":\"中移杭研实验室迪普清洗设备\"," + "\"deviceType\":999,\"areaCode\":0,\"deviceName\":\"中移杭研实验室迪普清洗设备\"," +
"\"manufacturer\":\"DPTech\",\"model\":\"UMC\",\"version\":\"5.7.13\"," + "\"manufacturer\":\"DPTech\",\"model\":\"UMC\",\"version\":\"5.7.13\"," +
"\"userName\":\"admin\",\"password\":\"testpassword\"," + "\"userName\":\"admin\",\"password\":\"testpassword\"," +
"\"urlPath\":\"UMC/service/AbnormalFlowCleaningService\",\"urlType\":0," + "\"urlPath\":\"UMC/service/AbnormalFlowCleaningService\",\"urlType\":0," +
@ -119,7 +119,7 @@ public class P2DeviceUpgrade {
.rspCode(ErrorCode.ERR_OK) .rspCode(ErrorCode.ERR_OK)
.autoLogin(true) .autoLogin(true)
.verifyCallback((VerifyProtoRespCallback<CommDeviceListRsp>) (v, e, c) -> { .verifyCallback((VerifyProtoRespCallback<CommDeviceListRsp>) (v, e, c) -> {
DisposeDevice dev = verifyDpTechDeviceAddResp(v, e, c, DisposeDeviceType.DPTECH_UMC, new HashMap<>()); DisposeDevice dev = verifyDpTechDeviceAddResp(v, e, c, DisposeDeviceType.VIRTUAL_DISPOSE, new HashMap<>());
Assert.assertEquals(dev.getDevCapacity().size(), 1); Assert.assertEquals(dev.getDevCapacity().size(), 1);
dev.getDevCapacity().forEach(k -> { dev.getDevCapacity().forEach(k -> {
@ -141,7 +141,7 @@ public class P2DeviceUpgrade {
.method(RequestMethod.POST) .method(RequestMethod.POST)
.caseJsonValue("{\"ver\":3,\"cryptoType\":0,\"timeStamp\":1599094454403," + .caseJsonValue("{\"ver\":3,\"cryptoType\":0,\"timeStamp\":1599094454403," +
"\"msgContent\":{\"items\":[{\"ipAddr\":\"127.0.0.1\",\"ipPort\":\"\"," + "\"msgContent\":{\"items\":[{\"ipAddr\":\"127.0.0.1\",\"ipPort\":\"\"," +
"\"deviceType\":0,\"areaCode\":0,\"deviceName\":\"中移杭研实验室迪普清洗设备\"," + "\"deviceType\":999,\"areaCode\":0,\"deviceName\":\"中移杭研实验室迪普清洗设备\"," +
"\"manufacturer\":\"DPTech\",\"model\":\"UMC\",\"version\":\"5.7.13\"," + "\"manufacturer\":\"DPTech\",\"model\":\"UMC\",\"version\":\"5.7.13\"," +
"\"userName\":\"admin\",\"password\":\"testpassword\"," + "\"userName\":\"admin\",\"password\":\"testpassword\"," +
"\"urlPath\":\"UMC/service/AbnormalFlowCleaningService\",\"urlType\":0," + "\"urlPath\":\"UMC/service/AbnormalFlowCleaningService\",\"urlType\":0," +
@ -152,7 +152,7 @@ public class P2DeviceUpgrade {
.rspCode(ErrorCode.ERR_OK) .rspCode(ErrorCode.ERR_OK)
.autoLogin(true) .autoLogin(true)
.verifyCallback((VerifyProtoRespCallback<CommDeviceListRsp>) (v, e, c) -> { .verifyCallback((VerifyProtoRespCallback<CommDeviceListRsp>) (v, e, c) -> {
DisposeDevice dev = verifyDpTechDeviceAddResp(v, e, c, DisposeDeviceType.DPTECH_UMC, new HashMap<>()); DisposeDevice dev = verifyDpTechDeviceAddResp(v, e, c, DisposeDeviceType.VIRTUAL_DISPOSE, new HashMap<>());
Assert.assertEquals(dev.getDevCapacity().size(), 1); Assert.assertEquals(dev.getDevCapacity().size(), 1);
dev.getDevCapacity().forEach(k -> { dev.getDevCapacity().forEach(k -> {
@ -267,7 +267,7 @@ public class P2DeviceUpgrade {
.method(RequestMethod.POST) .method(RequestMethod.POST)
.caseJsonValue("{\"ver\":3,\"cryptoType\":0,\"timeStamp\":1599094454403," + .caseJsonValue("{\"ver\":3,\"cryptoType\":0,\"timeStamp\":1599094454403," +
"\"msgContent\":{\"items\":[{\"ipAddr\":\"127.0.0.1\",\"ipPort\":\"\"," + "\"msgContent\":{\"items\":[{\"ipAddr\":\"127.0.0.1\",\"ipPort\":\"\"," +
"\"deviceType\":0,\"areaCode\":0,\"deviceName\":\"中移杭研实验室迪普清洗设备\"," + "\"deviceType\":999,\"areaCode\":0,\"deviceName\":\"中移杭研实验室迪普清洗设备\"," +
"\"manufacturer\":\"DPTech\",\"model\":\"UMC\",\"version\":\"5.7.13\"," + "\"manufacturer\":\"DPTech\",\"model\":\"UMC\",\"version\":\"5.7.13\"," +
"\"userName\":\"admin\",\"password\":\"testpassword\"," + "\"userName\":\"admin\",\"password\":\"testpassword\"," +
"\"urlPath\":\"UMC/service/AbnormalFlowCleaningService\",\"urlType\":0," + "\"urlPath\":\"UMC/service/AbnormalFlowCleaningService\",\"urlType\":0," +
@ -278,7 +278,7 @@ public class P2DeviceUpgrade {
.rspCode(ErrorCode.ERR_OK) .rspCode(ErrorCode.ERR_OK)
.autoLogin(true) .autoLogin(true)
.verifyCallback((VerifyProtoRespCallback<CommDeviceListRsp>) (v, e, c) -> { .verifyCallback((VerifyProtoRespCallback<CommDeviceListRsp>) (v, e, c) -> {
DisposeDevice dev = verifyDpTechDeviceAddResp(v, e, c, DisposeDeviceType.DPTECH_UMC, DisposeDevice dev = verifyDpTechDeviceAddResp(v, e, c, DisposeDeviceType.VIRTUAL_DISPOSE,
new HashMap<>()); new HashMap<>());
Assert.assertEquals(dev.getDevCapacity().size(), 2); Assert.assertEquals(dev.getDevCapacity().size(), 2);
@ -985,23 +985,24 @@ public class P2DeviceUpgrade {
Assert.assertNotNull(k.getDevStatus()); Assert.assertNotNull(k.getDevStatus());
}); });
DisposeDevice dev = c.getDisposeDeviceMapper().getDeviceByAddress("127.0.0.1", ""); DisposeDevice dev = c.getDisposeDeviceMapper().getDeviceByAddress("127.0.0.1", "", DisposeDeviceType.VIRTUAL_DISPOSE
.getValue());
Assert.assertNotNull(dev); Assert.assertNotNull(dev);
if (deviceType == DisposeDeviceType.DPTECH_UMC) { if (deviceType == DisposeDeviceType.DPTECH_UMC) {
//Assert.assertEquals(dev.getUserName(), fixItems.getOrDefault("userName", "admin")); //Assert.assertEquals(dev.getUserName(), fixItems.getOrDefault("userName", "admin"));
Assert.assertEquals(dev.getDeviceType(), DisposeDeviceType.DPTECH_UMC); Assert.assertEquals(dev.getDeviceType(), DisposeDeviceType.DPTECH_UMC);
Assert.assertEquals(dev.getManufacturer(), "DPTech"); //Assert.assertEquals(dev.getManufacturer(), "DPTech");
Assert.assertEquals(dev.getVersion(), fixItems.getOrDefault("version", "5.7.13")); Assert.assertEquals(dev.getVersion(), fixItems.getOrDefault("version", "5.7.13"));
Assert.assertEquals(dev.getDeviceName(), fixItems.getOrDefault("deviceName", "中移杭研实验室迪普清洗设备")); //Assert.assertEquals(dev.getDeviceName(), fixItems.getOrDefault("deviceName", "中移杭研实验室迪普清洗设备"));
//Assert.assertEquals(dev.getUrlPath(), fixItems.getOrDefault("urlPath", "UMC/service" + //Assert.assertEquals(dev.getUrlPath(), fixItems.getOrDefault("urlPath", "UMC/service" +
// "/AbnormalFlowCleaningService")); // "/AbnormalFlowCleaningService"));
} else if (deviceType == DisposeDeviceType.VIRTUAL_DISPOSE) { } else if (deviceType == DisposeDeviceType.VIRTUAL_DISPOSE) {
//Assert.assertEquals(dev.getUserName(), fixItems.getOrDefault("userName", "test")); //Assert.assertEquals(dev.getUserName(), fixItems.getOrDefault("userName", "test"));
Assert.assertEquals(dev.getDeviceType(), DisposeDeviceType.VIRTUAL_DISPOSE); Assert.assertEquals(dev.getDeviceType(), DisposeDeviceType.VIRTUAL_DISPOSE);
Assert.assertEquals(dev.getManufacturer(), "Virtual"); //Assert.assertEquals(dev.getManufacturer(), "Virtual");
Assert.assertEquals(dev.getVersion(), fixItems.getOrDefault("version", "5.7.13")); Assert.assertEquals(dev.getVersion(), fixItems.getOrDefault("version", "5.7.13"));
Assert.assertEquals(dev.getDeviceName(), fixItems.getOrDefault("deviceName", "中移杭研实验室虚拟清洗设备")); //Assert.assertEquals(dev.getDeviceName(), fixItems.getOrDefault("deviceName", "中移杭研实验室虚拟清洗设备"));
//Assert.assertEquals(dev.getUrlPath(), fixItems.getOrDefault("urlPath", "UMC/service/")); //Assert.assertEquals(dev.getUrlPath(), fixItems.getOrDefault("urlPath", "UMC/service/"));
} }