部分修改

This commit is contained in:
xiaojie
2024-03-06 17:36:30 +08:00
parent be4e3b4bae
commit d8f2e79d70
20 changed files with 242 additions and 317 deletions
+13 -6
View File
@@ -7,6 +7,7 @@ export function domainNameBindInfo(query) {
params: query
})
}
export function fetchList(query) {
return request({
url: '/domain/page',
@@ -15,10 +16,9 @@ export function fetchList(query) {
})
}
export function mappingModify(data) {
return request({
url: '/port-mapping/update',
url: '/domain/modify',
method: 'post',
data
})
@@ -26,7 +26,7 @@ export function mappingModify(data) {
export function deleteMapping(id) {
return request({
url: '/port-mapping/delete',
url: '/domain/delete',
method: 'post',
params: {
id: id
@@ -36,7 +36,7 @@ export function deleteMapping(id) {
export function updateEnableStatus(id, enable) {
return request({
url: '/port-mapping/update/enable-status',
url: '/domain/update/enable-status',
method: 'post',
data: {
id: id,
@@ -47,7 +47,7 @@ export function updateEnableStatus(id, enable) {
export function portMappingBindSecurityGroup(id, securityGroupId) {
return request({
url: '/port-mapping/bind/security-group',
url: '/domain/bind/security-group',
method: 'post',
data: {
id: id,
@@ -58,8 +58,15 @@ export function portMappingBindSecurityGroup(id, securityGroupId) {
export function portMappingUnbindSecurityGroup(id) {
return request({
url: `/port-mapping/unbind/security-group?id=${id}`,
url: `/domain/unbind/security-group?id=${id}`,
method: 'post'
})
}
export function domainAvailable(query) {
return request({
url: '/domain/available',
method: 'get',
params: query
})
}
@@ -54,6 +54,24 @@
prop: 'name',
label: 'License',
align: 'center'
},
{
prop: 'isOnline',
label: 'isOnline',
align: 'center',
render: (h, params) => {
switch (params.row.isOnline) {
case 1:
return h('el-tag', {
props: {type: 'success'}
}, '在线')
case 2:
return h('el-tag', {props:{type: 'danger'}}, '离线')
default:
return h('el-tag', {props:{type: 'danger'}}, '离线')
}
}
}
],
popVisible: false,
@@ -29,91 +29,67 @@
<span>{{ scope.row.id }}</span>
</template>
</el-table-column>
<el-table-column align="center" :label="$t('table.userName')" width="100">
<el-table-column align="center" :label="$t('table.userName')" width="80">
<template slot-scope="scope">
<span>{{ scope.row.userName }}</span>
</template>
</el-table-column>
<el-table-column align="center" :label="$t('table.licenseName')" width="120">
<el-table-column align="center" :label="$t('table.licenseName')" width="140">
<template slot-scope="scope">
<span>{{ scope.row.licenseName }}</span>
</template>
</el-table-column>
<el-table-column align="center" :label="$t('table.protocalName')" width="80">
<template slot-scope="scope">
<span>{{ scope.row.protocal }}</span>
</template>
</el-table-column>
<el-table-column align="center" :label="$t('table.domainName')" width="180">
<template slot-scope="scope">
<span>{{ scope.row.domain }}</span>
<el-link target="_blank" @click="handleOpenWebPage(scope.row)">http(s)://{{ scope.row.domain }}</el-link>
</template>
</el-table-column>
<el-table-column align="center" :label="$t('table.serverPort')" width="80">
<el-table-column align="center" :label="$t('目标路径')" width="240">
<template slot-scope="scope">
<span>{{ scope.row.serverPort }}</span>
<span v-html="scope.row.targetPath.replace(/(\n\r|\r\n|\r|\n)/g, '<br/>')"> </span>
</template>
</el-table-column>
<el-table-column align="center" :label="$t('table.proxyClient')" width="120">
<template slot-scope="scope">
<span>{{ scope.row.clientIp }}:{{ scope.row.clientPort }}</span>
</template>
</el-table-column>
<el-table-column align="center" :label="$t('限速')" width="100">
<el-table-column align="center" :label="$t('限速')" width="160">
<template slot-scope="scope">
<span>{{ scope.row.upLimitRate ? scope.row.upLimitRate : '--' }} / {{ scope.row.downLimitRate ? scope.row.downLimitRate : '--' }}</span>
</template>
</el-table-column>
<el-table-column align="center" :label="$t('table.desc')" width="120">
<el-table-column align="center" :label="$t('table.desc')" width="260">
<template slot-scope="scope">
<span>{{ scope.row.description }}</span>
</template>
</el-table-column>
<!-- <el-table-column width="150px" align="center" :label="$t('table.createTime')">-->
<!-- <template slot-scope="scope">-->
<!-- <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
<!-- </template>-->
<!-- </el-table-column>-->
<el-table-column width="150px" align="center" :label="$t('table.updateTime')">
<template slot-scope="scope">
<span>{{ scope.row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
</template>
</el-table-column>
<el-table-column class-name="status-col" :label="$t('table.enableStatus')" width="100">
<template slot-scope="scope">
<el-tag :type="colorOption[scope.row.enable]">{{ statusOptions[scope.row.enable] }}</el-tag>
</template>
</el-table-column>
<el-table-column class-name="status-col" :label="$t('table.isOnline')" width="100">
<template slot-scope="scope">
<el-tag :type="colorOption[scope.row.isOnline]">{{ onlineOptions[scope.row.isOnline] }}</el-tag>
</template>
</el-table-column>
<el-table-column class-name="status-col" :label="$t('table.access')" width="120">
<template slot-scope="scope">
<el-button size="mini" @click="handleOpenWebPage(scope.row)">{{ $t('table.openWebPage') }}</el-button>
</template>
</el-table-column>
<el-table-column align="center" :label="$t('table.actions')" width="320" class-name="small-padding fixed-width">
<template slot-scope="scope">
<el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
<el-button type="primary" size="mini" @click="toModify(scope.row)">{{ $t('table.edit') }}</el-button>
<el-button v-if="scope.row.enable == '1'" size="mini" type="danger" @click="handleModifyStatus(scope.row, 2)">{{ $t('table.disable') }}</el-button>
<el-button v-if="scope.row.enable == '2'" size="mini" type="success" @click="handleModifyStatus(scope.row, 1)">{{ $t('table.enable') }}</el-button>
<ButtonPopover @handleCommitClick="handleDelete(scope.row)" style="margin-left: 10px" />
</template>
</el-table-column>
</el-table>
@@ -124,10 +100,10 @@
</el-pagination>
</div>
<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
<el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="120px" style='width: 400px; margin-left:50px;'>
<el-dialog :title="textMap[dialogStatus]" :close-on-click-modal="false" :visible.sync="dialogFormVisible" top="20px">
<el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="110px">
<el-form-item :label="$t('License')" prop="licenseId">
<DropdownTable v-model="temp.licenseId" :name.sync="temp.licenseName" :tableData="licenseAuthList" @selectedData="selectedFeeItem" placeholder="请选择" :width="280"
<DropdownTable v-model="temp.licenseId" :name.sync="temp.licenseName" :tableData="licenseAuthList" @selectedData="selectedFeeItem" placeholder="请选择" :width="500"
:disabled="dialogStatus === 'update'" />
</el-form-item>
<el-form-item :label="$t('域名')" prop="domain">
@@ -136,10 +112,15 @@
</el-input>
</el-form-item>
<el-form-item :label="$t('目标地址')" prop="targetPath">
<el-input type="textarea" v-model="temp.targetPath" placeholder="请输入目标地址,"></el-input>
<el-input type="textarea" v-model="temp.targetPath" rows="3" placeholder="请输入目标地址,多个可实现负载均衡,如:
127.0.0.1:80
127.0.0.1:90"></el-input>
</el-form-item>
<el-form-item :label="$t('客户端端口')" prop="clientPort">
<el-input v-model="temp.clientPort"></el-input>
<el-form-item :label="$t('描述')" prop="description">
<el-input v-model="temp.description" type="textarea" placeholder="请输入描述"></el-input>
</el-form-item>
<el-form-item :label="$t('请求头部信息')" prop="requestHeader">
<el-input v-model="temp.requestHeader" type="textarea" placeholder="请输入请求头如:Cache-Control: no-cache"></el-input>
</el-form-item>
<el-form-item :label="$t('table.securityGroup')" prop="securityGroup">
<el-select style="width: 280px;" class="filter-item" v-model="temp.securityGroupId" clearable>
@@ -153,16 +134,12 @@
<el-form-item :label="$t('下载限速')" prop="downLimitRate">
<el-input v-model="temp.downLimitRate" placeholder="如:10240B、500K、1M"></el-input>
</el-form-item>
<el-form-item :label="$t('描述')" prop="description">
<el-input v-model="temp.description"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="
dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
<el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">{{ $t('table.confirm')
<el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
<el-button v-if="dialogStatus == 'create'" type="primary" @click="modifyData">{{ $t('table.confirm')
}}</el-button>
<el-button v-else type="primary" @click="updateData">{{ $t('table.confirm') }}</el-button>
<el-button v-else type="primary" @click="modifyData">{{ $t('table.confirm') }}</el-button>
</div>
</el-dialog>
@@ -180,12 +157,10 @@
</template>
<script>
import { fetchList, mappingModify, updateEnableStatus, deleteMapping } from '@/api/domain'
import { fetchList, mappingModify, updateEnableStatus, deleteMapping, domainAvailable } from '@/api/domain'
import { fetchGroupList } from '@/api/securityGroup'
import { availablePortList, portAvailable } from '@/api/portPool'
import { licenseList, licenseAuthList } from '@/api/license'
import { userList } from '@/api/user'
import { domainNameBindInfo } from '@/api/domain'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime } from '@/utils'
import ButtonPopover from '../../components/Button/buttonPopover'
@@ -200,18 +175,6 @@ export default {
ButtonPopover
},
data() {
const isPortAvailable = (rule, value, callback) => {
if (value != null) {
const param = { port: value, portMappingId: this.temp.id }
portAvailable(param).then(res => {
if (!res.data.data) {
return callback(new Error('该端口被占用'))
} else {
callback()
}
})
}
}
return {
tableKey: 0,
list: null,
@@ -240,6 +203,7 @@ export default {
licenseName: undefined,
domain: undefined,
targetPath: undefined,
requestHeader: undefined
},
statusOptions: {
1: '启用',
@@ -257,17 +221,17 @@ export default {
dialogStatus: '',
textMap: {
update: '编辑',
create: '新'
create: '新'
},
dialogPvVisible: false,
pvData: [],
rules: {
licenseId: [{ required: true, message: '请选择License', trigger: 'blur,change' }],
serverPort: [{ required: true, message: '请输入服务端端口', trigger: 'blur' },
// { validator: isPortAvailable, trigger: 'change' }
domain: [{ required: true, message: '请输入域名', trigger: 'blur' },
{pattern: '^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$', message: '域名格式不正确,请检查后重试', trigger: 'blur' },
{ validator: this.isDomainAvailable, trigger: 'blur' }
],
clientIp: [{ required: true, message: '请输入客户端IP', trigger: 'blur' }],
clientPort: [{ required: true, message: '请输入客户端端口', trigger: 'blur' }],
targetPath: [{ required: true, message: '请输入目标地址', trigger: 'blur' }],
},
more: true,
securityGroupList: []
@@ -282,6 +246,19 @@ export default {
this.fetchSecurityGroupList()
},
methods: {
isDomainAvailable(rule, value, callback) {
if (value != null) {
const param = { domain: value, id: this.temp.id }
domainAvailable(param).then(res => {
console.log(res)
if (!res.data.data) {
return callback(new Error('域名已被占用'))
} else {
callback()
}
})
}
},
getList() {
this.listLoading = true
fetchList(this.listQuery).then(response => {
@@ -368,15 +345,15 @@ export default {
this.$refs['dataForm'].clearValidate()
})
},
createData() {
modifyData() {
this.$refs['dataForm'].validate((valid) => {
if (valid) {
createUserPortMapping(this.temp).then(response => {
mappingModify(this.temp).then(response => {
if (response.data.code === 0) {
this.dialogFormVisible = false
this.$notify({
title: '成功',
message: '创建成功',
message: '操作成功',
type: 'success',
duration: 2000
})
@@ -386,29 +363,10 @@ export default {
}
})
},
updateData() {
this.$refs['dataForm'].validate((valid) => {
if (valid) {
const tempData = Object.assign({}, this.temp)
updateUserPortMapping(tempData).then(response => {
if (response.data.code === 0) {
this.$notify({
title: '成功',
message: '更新成功',
type: 'success',
duration: 2000
})
this.dialogFormVisible = false
this.getList()
}
})
}
})
},
handleOpenWebPage(row) {
open(location.protocol + '//' + row.domain)
},
handleUpdate(row) {
toModify(row) {
this.temp = Object.assign({}, row) // copy obj
if (row.securityGroupId === 0) {
this.temp.securityGroupId = null
@@ -254,7 +254,6 @@ export default {
description: undefined
},
calendarTypeOptions,
sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
statusOptions: ['published', 'draft', 'deleted'],
userList: [],
@@ -50,6 +50,9 @@ public interface Constants {
AttributeKey<InetSocketAddress> SENDER = AttributeKey.newInstance("sender");
AttributeKey<Integer> SERVER_PORT = AttributeKey.newInstance("serverPort");
AttributeKey<String> DOMAIN = AttributeKey.newInstance("domain");
AttributeKey<String> REAL_REMOTE_IP = AttributeKey.newInstance("realRemoteIp");
@@ -16,6 +16,7 @@ import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;
import org.noear.solon.validation.ValidatorException;
import java.lang.reflect.Method;
@@ -81,8 +82,12 @@ public class BaseAuthInterceptor implements RouterInterceptor {
return new ResponseBody<>()
.setCode(exception.getCode())
.setMsg(exception.getMsg());
} else if (result instanceof ValidatorException) {
return new ResponseBody<>()
.setCode(ExceptionConstant.DONAME_PATTEN_ERROR.getCode())
.setMsg(ExceptionConstant.DONAME_PATTEN_ERROR.getMsg())
.setStack(ExceptionUtils.getStackTrace((Throwable) result));
}
return new ResponseBody<>()
.setCode(ExceptionConstant.SYSTEM_ERROR.getCode())
.setMsg(ExceptionConstant.SYSTEM_ERROR.getMsg())
@@ -9,6 +9,7 @@ import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.validation.ValidatorException;
/**
* @author: aoshiguchen
@@ -22,9 +23,13 @@ public class GlobalExceptionFilter implements Filter {
public void doFilter(Context ctx, FilterChain chain) throws Throwable {
try {
chain.doFilter(ctx);
} catch (Throwable e) {
} catch(ValidatorException ve){
ctx.render(new ResponseBody<>()
.setCode(ExceptionConstant.DONAME_PATTEN_ERROR.getCode())
.setMsg(ExceptionConstant.DONAME_PATTEN_ERROR.getMsg())
.setStack(ExceptionUtils.getStackTrace(ve)));
} catch(Throwable e) {
log.error("global error", e);
if (e instanceof ServiceException) {
ServiceException serviceException = (ServiceException) e;
ctx.render(new ResponseBody<>()
@@ -32,7 +37,6 @@ public class GlobalExceptionFilter implements Filter {
.setMsg(serviceException.getMsg()));
return;
}
ctx.render(new ResponseBody<>()
.setCode(ExceptionConstant.SYSTEM_ERROR.getCode())
.setMsg(ExceptionConstant.SYSTEM_ERROR.getMsg())
@@ -61,6 +61,9 @@ public enum ExceptionConstant {
AN_UNSUPPORTED_PROTOCOL(14002, "不支持的协议[{}]"),
PORT_MAPPING_SUBDONAME_CONNOT_REPEAT(14003, "子域名不能重复使用!"),
DONAME_CONNOT_REPEAT(14004, "域名不能重复解析!"),
DONAME_PATTEN_ERROR(14005, "域名格式不正确!"),
// 调度管理(15000)
JOB_INFO_NOT_EXIST(15000, "调度管理记录不存在"),
SYSTEM_ERROR(500, "系统异常"),
@@ -9,16 +9,20 @@ import org.dromara.neutrinoproxy.server.constant.ExceptionConstant;
import org.dromara.neutrinoproxy.server.constant.NetworkProtocolEnum;
import org.dromara.neutrinoproxy.server.controller.req.proxy.*;
import org.dromara.neutrinoproxy.server.controller.res.proxy.*;
import org.dromara.neutrinoproxy.server.dal.entity.DomainMappingDO;
import org.dromara.neutrinoproxy.server.service.DomainMappingService;
import org.dromara.neutrinoproxy.server.service.PortMappingService;
import org.dromara.neutrinoproxy.server.util.ParamCheckUtil;
import org.noear.solon.annotation.*;
import org.noear.solon.validation.annotation.NotBlank;
import org.noear.solon.validation.annotation.Valid;
import org.noear.solon.validation.annotation.Validated;
/**
* @author: aoshiguchen
* @date: 2023/4/2
*/
@Slf4j
@Valid
@Mapping("/domain")
@Controller
public class DomainController {
@@ -44,7 +48,7 @@ public class DomainController {
@Post
@Mapping("/modify")
public PortMappingCreateRes modify(DomainMappingDto req) {
public PortMappingCreateRes modify(@Validated DomainMappingDO req) {
if (StringUtils.isBlank(req.getTargetPath())) {// targetPath,默认为127.0.0.1
req.setTargetPath("127.0.0.1");
}
@@ -95,5 +99,14 @@ public class DomainController {
/**
* 绑定安全组
* @param domain
*/
@Get
@Mapping("/available")
public boolean exitDomain(@NotBlank String domain, Integer id) {
return domainMappingService.exitDomain(domain, id);
}
}
@@ -32,7 +32,9 @@ import lombok.experimental.Accessors;
import org.dromara.neutrinoproxy.server.constant.EnableStatusEnum;
import org.dromara.neutrinoproxy.server.constant.OnlineStatusEnum;
import org.dromara.neutrinoproxy.server.controller.res.proxy.DomainMappingDto;
import org.dromara.neutrinoproxy.server.controller.res.proxy.PortMappingListRes;
import org.noear.solon.validation.annotation.NotBlank;
import org.noear.solon.validation.annotation.NotNull;
import org.noear.solon.validation.annotation.Pattern;
import java.util.Date;
@@ -51,14 +53,17 @@ public class DomainMappingDO {
/**
* licenseId
*/
@NotNull
private Integer licenseId;
/**
* 协议
*/
private String protocal;
/**
* 域名
* 域名 /^(\w+\.{1}\w+)$/g
*/
@NotBlank
@Pattern("^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$")
private String domain;
/**
* 描述
@@ -67,7 +72,9 @@ public class DomainMappingDO {
/**
* 目标地址(licenseId客户端,ip:port
*/
private String targetPath;
@NotBlank
private String targetPath;
/**
* 上传限速
*/
@@ -105,6 +112,8 @@ public class DomainMappingDO {
private Date updateTime;
public DomainMappingDto toRes() {
return (DomainMappingDto) this;
DomainMappingDto dto = new DomainMappingDto();
BeanUtil.copyProperties(this, dto);
return dto;
}
}
@@ -0,0 +1,34 @@
package org.dromara.neutrinoproxy.server.proxy.domain;
import lombok.Data;
/**
* @author xiaojie
* @date
*/
@Data
public class DomainMapping {
/**
* License
*/
private Integer licenseId;
/**
* 客户端信息 IP:port
*/
private String domain;
/**
* 目标地址(其中含有\n隔离多个 目标地址)
*/
private String targetPath;
public DomainMapping() {
}
public DomainMapping(Integer licenseId, String domain, String targetPath) {
this.licenseId = licenseId;
this.domain = domain;
this.targetPath = targetPath;
}
}
@@ -29,9 +29,11 @@ import org.noear.solon.core.event.EventListener;
public class HttpProxy implements EventListener<AppLoadEndEvent> {
@Inject
private ProxyConfig proxyConfig;
@Override
public void onEvent(AppLoadEndEvent appLoadEndEvent) throws Throwable {
if (StrUtil.isBlank(proxyConfig.getServer().getTcp().getDomainName()) || null == proxyConfig.getServer().getTcp().getHttpProxyPort()) {
// StrUtil.isBlank(proxyConfig.getServer().getTcp().getDomainName()) ||
if (null == proxyConfig.getServer().getTcp().getHttpProxyPort()) {
log.info("no config domain name,nonsupport http proxy.");
return;
}
@@ -45,11 +47,12 @@ public class HttpProxy implements EventListener<AppLoadEndEvent> {
.channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
if (null != proxyConfig.getServer().getTcp().getTransferLogEnable() && proxyConfig.getServer().getTcp().getTransferLogEnable()) {
if (null != proxyConfig.getServer().getTcp().getTransferLogEnable() &&
proxyConfig.getServer().getTcp().getTransferLogEnable()) {
ch.pipeline().addFirst(new LoggingHandler(HttpProxy.class));
}
ch.pipeline().addFirst(new BytesMetricsHandler());
ch.pipeline().addLast(new HttpVisitorSecurityChannelHandler(proxyConfig.getServer().getTcp().getDomainName()));
ch.pipeline().addLast(new HttpVisitorSecurityChannelHandler());
ch.pipeline().addLast("flowLimiter",new VisitorFlowLimiterChannelHandler());
ch.pipeline().addLast(new HttpVisitorChannelHandler());
}
@@ -38,8 +38,10 @@ public class HttpsProxy implements EventListener<AppLoadEndEvent> {
private ProxyConfig proxyConfig;
@Override
public void onEvent(AppLoadEndEvent appLoadEndEvent) throws Throwable {
if (StrUtil.isBlank(proxyConfig.getServer().getTcp().getDomainName()) || null == proxyConfig.getServer().getTcp().getHttpsProxyPort() ||
StringUtils.isEmpty(proxyConfig.getServer().getTcp().getJksPath()) || StringUtils.isEmpty(proxyConfig.getServer().getTcp().getKeyStorePassword())) {
// StrUtil.isBlank(proxyConfig.getServer().getTcp().getDomainName()) ||
if (null == proxyConfig.getServer().getTcp().getHttpsProxyPort() ||
StringUtils.isEmpty(proxyConfig.getServer().getTcp().getJksPath()) ||
StringUtils.isEmpty(proxyConfig.getServer().getTcp().getKeyStorePassword())) {
log.info("no config domain name,nonsupport https proxy.");
return;
}
@@ -58,7 +60,7 @@ public class HttpsProxy implements EventListener<AppLoadEndEvent> {
}
ch.pipeline().addLast(createSslHandler());
ch.pipeline().addFirst(new BytesMetricsHandler());
ch.pipeline().addLast(new HttpVisitorSecurityChannelHandler(proxyConfig.getServer().getTcp().getDomainName()));
ch.pipeline().addLast(new HttpVisitorSecurityChannelHandler()); // proxyConfig.getServer().getTcp().getDomainName()
ch.pipeline().addLast("flowLimiter",new VisitorFlowLimiterChannelHandler());
ch.pipeline().addLast(new HttpVisitorChannelHandler());
}
@@ -24,7 +24,6 @@ package org.dromara.neutrinoproxy.server.proxy.handler;
import cn.hutool.core.util.StrUtil;
import org.dromara.neutrinoproxy.core.*;
import org.dromara.neutrinoproxy.core.*;
import org.dromara.neutrinoproxy.core.dispatcher.Match;
import org.dromara.neutrinoproxy.server.base.proxy.ProxyConfig;
import org.dromara.neutrinoproxy.server.constant.ClientConnectTypeEnum;
@@ -23,49 +23,33 @@ import org.noear.solon.Solon;
public class HttpVisitorSecurityChannelHandler extends ChannelInboundHandlerAdapter {
private final SecurityGroupService securityGroupService = Solon.context().getBean(SecurityGroupService.class);
private final PortMappingService portMappingService = Solon.context().getBean(PortMappingService.class);
/**
* 域名
*/
private String domainName;
// /**
// * 域名
// */
// private String domainName;
public HttpVisitorSecurityChannelHandler(String domainName) {
this.domainName = domainName;
}
// public HttpVisitorSecurityChannelHandler(String domainName) {
// this.domainName = domainName;
// }
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 未配置域名则不支持通过域名访问
if (StrUtil.isBlank(domainName)) {
ctx.channel().close();
return;
}
ByteBuf buf = (ByteBuf) msg;
Integer serverPort = ctx.channel().attr(Constants.SERVER_PORT).get();
if (null == serverPort) {
String domain = ctx.channel().attr(Constants.DOMAIN).get();
if (StringUtils.isBlank(domain)) {
// 获取Host请求头
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String httpContent = new String(bytes);
String host = HttpUtil.getHostIgnorePort(httpContent);
domain = HttpUtil.getHostIgnorePort(httpContent);
log.debug("HttpProxy host: {}", host);
if (StringUtils.isBlank(host)) {
log.debug("HttpProxy host: {}", domain);
if (StringUtils.isBlank(domain)) {
ctx.channel().close();
return;
}
// 根据Host匹配端口映射
if (!host.endsWith(domainName)) {
ctx.channel().close();
return;
}
int index = host.lastIndexOf("." + domainName);
String subdomain = host.substring(0, index);
// 根据域名拿到绑定的映射对应的cmdChannel
serverPort = ProxyUtil.getServerPortBySubdomain(subdomain);
if (null == serverPort) {
// 未配置域名解析,不再解析
if (!ProxyUtil.domainMapingMap.containsKey(domain)) {
ctx.channel().close();
return;
}
@@ -75,14 +59,13 @@ public class HttpVisitorSecurityChannelHandler extends ChannelInboundHandlerAdap
if (ip == null) {
ip = IpUtil.getRemoteIp(ctx);
}
if (!securityGroupService.judgeAllow(ip, portMappingService.getSecurityGroupIdByMappingPort(serverPort))) {
// 不在安全组规则放行范围内
ctx.channel().close();
return;
}
// if (!securityGroupService.judgeAllow(ip, portMappingService.getSecurityGroupIdByMappingPort(serverPort))) {
// // 不在安全组规则放行范围内
// ctx.channel().close();
// return;
// }
ctx.channel().attr(Constants.REAL_REMOTE_IP).set(ip);
ctx.channel().attr(Constants.SERVER_PORT).set(serverPort);
ctx.channel().attr(Constants.DOMAIN).set(domain);
}
// 继续传播
@@ -31,7 +31,6 @@ public class UdpVisitorSecurityChannelHandler extends ChannelInboundHandlerAdapt
if (!securityGroupService.judgeAllow(datagramPacket.sender().getAddress().getHostAddress(), portMappingService.getSecurityGroupIdByMappingPort(sa.getPort()))) {
return;
}
// 继续传播
ctx.channel().attr(Constants.SERVER_PORT).set(sa.getPort());
ctx.fireChannelRead(msg);
@@ -3,6 +3,7 @@ package org.dromara.neutrinoproxy.server.service;
import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
@@ -30,8 +31,10 @@ import org.dromara.neutrinoproxy.server.dal.LicenseMapper;
import org.dromara.neutrinoproxy.server.dal.PortPoolMapper;
import org.dromara.neutrinoproxy.server.dal.UserMapper;
import org.dromara.neutrinoproxy.server.dal.entity.*;
import org.dromara.neutrinoproxy.server.proxy.domain.DomainMapping;
import org.dromara.neutrinoproxy.server.service.bo.FlowLimitBO;
import org.dromara.neutrinoproxy.server.util.ParamCheckUtil;
import org.dromara.neutrinoproxy.server.util.PortAvailableUtil;
import org.dromara.neutrinoproxy.server.util.ProxyUtil;
import org.dromara.neutrinoproxy.server.util.StringUtil;
import org.noear.solon.annotation.Component;
@@ -72,16 +75,6 @@ public class DomainMappingService implements LifecycleBean {
@Inject
private LicenseService licenseService;
/** 端口到安全组Id的映射 */
private final Map<String, Integer> mappingDomainToSecurityGroupMap = new ConcurrentHashMap<>();
/**
* 域名 到 域名解析id的映射
*/
private final Cache<String, Integer> domainToDomainMappingIdCache = CacheUtil.newLRUCache(500, 1000 * 60 * 10);
// 域名解析id到licenseId
private final Cache<Integer, Integer> idToLicenseIdCache = CacheUtil.newLRUCache(500, 1000 * 60 * 10);
// 流量限制缓存
private final Cache<Integer, FlowLimitBO> flowLimitCache = CacheUtil.newLRUCache(500, 1000 * 60 * 5);
public PageInfo<DomainMappingDto> page(PageQuery pageQuery, DomainMappingDto req) {
if (StringUtils.isNotEmpty(req.getDescription())) {
@@ -138,40 +131,35 @@ public class DomainMappingService implements LifecycleBean {
return PageInfo.of(respList, page.getTotal(), pageQuery.getCurrent(), pageQuery.getSize());
}
public PortMappingCreateRes modify(DomainMappingDto req) {
LicenseDO licenseDO = licenseMapper.findById(req.getLicenseId());
public PortMappingCreateRes modify(DomainMappingDO domainMappingDO) {
LicenseDO licenseDO = licenseMapper.findById(domainMappingDO.getLicenseId());
ParamCheckUtil.checkNotNull(licenseDO, ExceptionConstant.LICENSE_NOT_EXIST);
if (!SystemContextHolder.isAdmin()) {
// 临时处理,如果当前用户不是管理员,则操作userId不能为1
ParamCheckUtil.checkExpression(!licenseDO.getUserId().equals(1), ExceptionConstant.NO_PERMISSION_VISIT);
}
// PortPoolDO portPoolDO = portPoolMapper.findByPort(req.getDomain());
// ParamCheckUtil.checkNotNull(portPoolDO, ExceptionConstant.PORT_NOT_EXIST);
ParamCheckUtil.checkExpression(null == domainMappingMapper.findByDomain(req.getDomain(), null), ExceptionConstant.PORT_CANNOT_REPEAT_MAPPING, req.getDomain());
ParamCheckUtil.checkExpression(!domainMappingMapper.checkRepeatByDomain(req.getDomain(), null), ExceptionConstant.PORT_MAPPING_SUBDONAME_CONNOT_REPEAT);
if (null != domainMappingDO.getId()) { // 编辑
ParamCheckUtil.checkExpression(!domainMappingMapper.checkRepeatByDomain(domainMappingDO.getDomain(), new HashSet<>(){{add(domainMappingDO.getId());}}), ExceptionConstant.DONAME_CONNOT_REPEAT);
Date now = new Date();
DomainMappingDO domainMappingDO = (DomainMappingDO) req;
domainMappingDO.setIsOnline(OnlineStatusEnum.OFFLINE.getStatus());
domainMappingDO.setEnable(EnableStatusEnum.ENABLE.getStatus());
domainMappingDO.setCreateTime(now);
domainMappingDO.setUpdateTime(now);
domainMappingMapper.insert(domainMappingDO);
Date now = new Date();
domainMappingDO.setEnable(EnableStatusEnum.ENABLE.getStatus());
domainMappingDO.setUpdateTime(now);
domainMappingMapper.updateById(domainMappingDO);
} else { // 新增
ParamCheckUtil.checkExpression(!domainMappingMapper.checkRepeatByDomain(domainMappingDO.getDomain(), null), ExceptionConstant.DONAME_CONNOT_REPEAT);
Date now = new Date();
domainMappingDO.setIsOnline(OnlineStatusEnum.OFFLINE.getStatus());
domainMappingDO.setEnable(EnableStatusEnum.ENABLE.getStatus());
domainMappingDO.setCreateTime(now);
domainMappingDO.setUpdateTime(now);
domainMappingMapper.insert(domainMappingDO);
}
// 更新VisitorChannel
// visitorChannelService.addVisitorChannelByPortMapping(domainMappingDO);
// 更新域名映射
if (NetworkProtocolEnum.isHttp(domainMappingDO.getProtocal()) && StrUtil.isNotBlank(proxyConfig.getServer().getTcp().getDomainName()) && StrUtil.isNotBlank(domainMappingDO.getDomain())) {
// ProxyUtil.setSubdomainToServerPort(domainMappingDO.getDomain(), domainMappingDO.getServerPort());
}
updateMappingDomainToSecurityGroupMap(domainMappingDO.getDomain(), req.getSecurityGroupId());
// 更新端口到映射的缓存
domainToDomainMappingIdCache.put(req.getDomain(), domainMappingDO.getId());
// 更新端口映射到licenseId的缓存
idToLicenseIdCache.put(domainMappingDO.getId(), domainMappingDO.getLicenseId());
// 刷新流量限制缓存
refreshFlowLimitCache(domainMappingDO.getId(), domainMappingDO.getUpLimitRate(), domainMappingDO.getDownLimitRate());
ProxyUtil.domainMapingMap.put(domainMappingDO.getDomain(), new DomainMapping(domainMappingDO.getLicenseId(), domainMappingDO.getDomain(), domainMappingDO.getTargetPath()));
return new PortMappingCreateRes();
}
@@ -208,7 +196,6 @@ public class DomainMappingService implements LifecycleBean {
// 临时处理,如果当前用户不是管理员,则操作userId不能为1
ParamCheckUtil.checkExpression(!licenseDO.getUserId().equals(1), ExceptionConstant.NO_PERMISSION_VISIT);
}
domainMappingMapper.deleteById(id);
// 更新VisitorChannel
@@ -219,12 +206,6 @@ public class DomainMappingService implements LifecycleBean {
ProxyUtil.removeSubdomainToServerPort(domainMappingDO.getDomain());
}
updateMappingDomainToSecurityGroupMap(domainMappingDO.getDomain(), null);
// 删除id到licenseId的映射
idToLicenseIdCache.remove(id);
// 删除流量限制缓存
flowLimitCache.remove(id);
}
public void domainBindSecurityGroup(Integer portMappingId, Integer groupId) {
@@ -235,7 +216,6 @@ public class DomainMappingService implements LifecycleBean {
mappingDO.setSecurityGroupId(groupId);
mappingDO.setUpdateTime(new Date());
domainMappingMapper.updateById(mappingDO);
updateMappingDomainToSecurityGroupMap(mappingDO.getDomain(), groupId);
}
public void domainUnbindSecurityGroup(Integer portMappingId) {
@@ -246,7 +226,6 @@ public class DomainMappingService implements LifecycleBean {
mappingDO.setSecurityGroupId(0);
mappingDO.setUpdateTime(new Date());
domainMappingMapper.updateById(mappingDO);
updateMappingDomainToSecurityGroupMap(mappingDO.getDomain(), null);
}
/**
@@ -259,10 +238,6 @@ public class DomainMappingService implements LifecycleBean {
return domainMappingMapper.findEnableListByLicenseId(licenseId);
}
public Integer getSecurityGroupIdByMappingPort(Integer port) {
return mappingDomainToSecurityGroupMap.get(port);
}
/**
* 服务端项目停止、启动时,更新在线状态为离线
@@ -273,124 +248,16 @@ public class DomainMappingService implements LifecycleBean {
if (NativeDetector.isAotRuntime()) {
return;
}
// 服务刚启动,所以默认所有license都是离线状态。解决服务突然关闭,在线状态来不及更新的问题
// domainMappingMapper.updateOnlineStatus(OnlineStatusEnum.OFFLINE.getStatus(), new Date());
List<DomainMappingDO> allMappingDOList = domainMappingMapper.selectList(Wrappers.lambdaQuery(DomainMappingDO.class));
allMappingDOList.forEach(item -> {
Integer securityGroupId = item.getSecurityGroupId();
if (securityGroupId != null && securityGroupId > 0) {
updateMappingDomainToSecurityGroupMap(item.getDomain(), item.getSecurityGroupId());
}
// 更新端口到映射的缓存
domainToDomainMappingIdCache.put(item.getDomain(), item.getId());
// 更新端口映射到licenseId的缓存
idToLicenseIdCache.put(item.getId(), item.getLicenseId());
// 刷新流量限制缓存
refreshFlowLimitCache(item.getId(), item.getUpLimitRate(), item.getDownLimitRate());
});
// 未配置域名,则不需要处理域名映射逻辑
if (StrUtil.isBlank(proxyConfig.getServer().getTcp().getDomainName())) {
return;
if(CollectionUtil.isNotEmpty(allMappingDOList)) {
allMappingDOList.forEach(domain -> {
ProxyUtil.domainMapingMap.put(domain.getDomain(),
new DomainMapping(domain.getLicenseId(), domain.getDomain(), domain.getTargetPath()));
});
}
List<DomainMappingDO> portMappingDOList = allMappingDOList.stream()
.filter(item -> NetworkProtocolEnum.HTTP.getDesc().equals(item.getProtocal()) && item.getDomain() != null)
.collect(Collectors.toList());
if (CollectionUtil.isEmpty(portMappingDOList)) {
return;
}
portMappingDOList.forEach(item -> {
if (StrUtil.isBlank(item.getDomain())) {
return;
}
// ProxyUtil.setSubdomainToServerPort(item.getDomain(), item.getServerPort());
});
}
/**
* 刷新流量限制缓存
* @param id
* @param upLimitRate
* @param downLimitRate
*/
private void refreshFlowLimitCache(Integer id, String upLimitRate, String downLimitRate) {
if (null == id) {
return;
}
flowLimitCache.put(id, new FlowLimitBO()
.setUpLimitRate(StringUtil.parseBytes(upLimitRate))
.setDownLimitRate(StringUtil.parseBytes(downLimitRate))
);
}
/**
* 获取license的流量限制
* @param id
* @return
*/
public FlowLimitBO getFlowLimit(Integer id) {
FlowLimitBO res = flowLimitCache.get(id);
if (null == res) {
DomainMappingDO domainMappingDO = domainMappingMapper.findById(id);
if (null != domainMappingDO) {
refreshFlowLimitCache(id, domainMappingDO.getUpLimitRate(), domainMappingDO.getDownLimitRate());
res = flowLimitCache.get(id);
}
}
return res;
}
public Integer getDomainMappingIdByDomain(String domain) {
Integer id = domainToDomainMappingIdCache.get(domain);
if (null != id) {
return id;
}
List<DomainMappingDO> domainMappingDOList = domainMappingMapper.findListByServerPort(domain);
// 不存在 或者 有多条记录,都不处理
if (CollectionUtils.isEmpty(domainMappingDOList) || domainMappingDOList.size() > 1) {
return null;
}
id = domainMappingDOList.get(0).getId();
domainToDomainMappingIdCache.put(domain, id);
return id;
}
public Integer getLicenseIdById(Integer id) {
Integer licenseId = idToLicenseIdCache.get(id);
if (null == licenseId) {
DomainMappingDO domainMappingDO = domainMappingMapper.findById(id);
if (null != domainMappingDO) {
licenseId = domainMappingDO.getLicenseId();
idToLicenseIdCache.put(id, licenseId);
}
}
return licenseId;
}
public FlowLimitBO getFlowLimitByServerPort(String domain) {
Integer id = getDomainMappingIdByDomain(domain);
if (null == id) {
return null;
}
FlowLimitBO res = getFlowLimit(id);
if (null == res || (null == res.getUpLimitRate() && null == res.getDownLimitRate())) {
Integer licenseId = getLicenseIdById(id);
if (null != licenseId) {
res = licenseService.getFlowLimit(licenseId);
}
}
return res;
}
private void updateMappingDomainToSecurityGroupMap(String domain, Integer securityGroupId) {
if (securityGroupId == null || securityGroupId == 0) {
mappingDomainToSecurityGroupMap.remove(domain);
return;
}
mappingDomainToSecurityGroupMap.put(domain, securityGroupId);
}
@Override
public void start() throws Throwable {
@@ -423,4 +290,16 @@ public class DomainMappingService implements LifecycleBean {
}
return res;
}
/**
* 检查端口是否被占用
* 端口映射编辑时,如果端口号没有变动,则不验证。避免出现端口映射正在使用时,无法更新端口映射其他信息的问题
* @param domain
* @return
*/
public boolean exitDomain(String domain, Integer id) {
DomainMappingDO domainMappingDO = domainMappingMapper.findByDomain(domain, ObjectUtil.isNotNull(id) ? new HashSet<>(){{add(id);}} : new HashSet());
if (null == domainMappingDO) return Boolean.TRUE;
return Boolean.FALSE;
}
}
@@ -407,7 +407,6 @@ public class PortMappingService implements LifecycleBean {
return;
}
ProxyUtil.setSubdomainToServerPort(item.getSubdomain(), item.getServerPort());
});
}
@@ -5,13 +5,13 @@ import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.dromara.neutrinoproxy.core.ChannelAttribute;
import org.dromara.neutrinoproxy.core.Constants;
import org.dromara.neutrinoproxy.server.base.proxy.ProxyConfig;
import org.dromara.neutrinoproxy.server.constant.NetworkProtocolEnum;
import org.dromara.neutrinoproxy.server.proxy.domain.CmdChannelAttachInfo;
import org.dromara.neutrinoproxy.server.proxy.domain.ProxyAttachment;
import org.dromara.neutrinoproxy.server.proxy.domain.ProxyMapping;
import org.dromara.neutrinoproxy.server.proxy.domain.VisitorChannelAttachInfo;
import org.dromara.neutrinoproxy.server.proxy.domain.*;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import org.dromara.neutrinoproxy.server.service.DomainMappingService;
import org.noear.solon.annotation.Inject;
import java.net.InetSocketAddress;
import java.util.*;
@@ -64,11 +64,18 @@ public class ProxyUtil {
* 子域名 - 服务端端口映射
*/
private static Map<String, Integer> subdomainToServerPort = new HashMap<>();
/**
* 域名 解析 映射
*/
public static final Map<String, DomainMapping> domainMapingMap = new HashMap<>();
/**
* licenseId - 客户端Id映射
*/
private static Map<Integer, String> licenseIdToClientIdMap = new HashMap<>();
@Inject
private DomainMappingService domainMappingService;
/**
* 初始化代理信息
* @param licenseId licenseId
@@ -79,6 +86,7 @@ public class ProxyUtil {
addProxyInfo(licenseId, proxyMappingList);
}
public static void addProxyInfo(Integer licenseId, List<ProxyMapping> proxyMappingList) {
if (!CollectionUtil.isEmpty(proxyMappingList)) {
for (ProxyMapping proxyMapping : proxyMappingList) {
@@ -48,7 +48,7 @@
LEFT JOIN `user` u ON l.user_id = u.id
LEFT JOIN (SELECT license_id,sum(write_bytes) write_bytes,sum(read_bytes) read_bytes from flow_report_month GROUP BY license_id) frm ON l.id = frm.license_id
LEFT JOIN (SELECT license_id,sum(write_bytes) write_bytes,sum(read_bytes) read_bytes from flow_report_day
WHERE date >= #{curMonthBeginDate} AND #{curDayBeginDate}
WHERE date >= #{curMonthBeginDate} AND date &lt;= #{curDayBeginDate}
GROUP BY license_id) frd ON l.id = frd.license_id
LEFT JOIN (SELECT license_id,sum(write_bytes) write_bytes,sum(read_bytes) read_bytes from flow_report_minute
WHERE date >= #{curDayBeginDate} AND date &lt;= #{curDate}