diff --git a/.gitignore b/.gitignore index 3761a8e3..efc51414 100644 --- a/.gitignore +++ b/.gitignore @@ -61,3 +61,4 @@ logs data **/cert/** neutrino-proxy-server/src/main/resources/static/** +/neutrino-proxy-server/src/main/resources/static/ diff --git a/README.md b/README.md index 1e8f5641..fef9def5 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,11 @@ + + +# what is new? 在原版的基础上新增了【域名解析】功能,域名解析【无需】绑定【本地端口】 +

+ + + +

diff --git a/assets/run-example/domain.png b/assets/run-example/domain.png new file mode 100644 index 00000000..3801b51a Binary files /dev/null and b/assets/run-example/domain.png differ diff --git a/neutrino-proxy-admin/build/webpack.local.conf.js b/neutrino-proxy-admin/build/webpack.local.conf.js index 279389c9..b70851b7 100644 --- a/neutrino-proxy-admin/build/webpack.local.conf.js +++ b/neutrino-proxy-admin/build/webpack.local.conf.js @@ -1,36 +1,39 @@ -'use strict' -const path = require('path') -const utils = require('./utils') -const webpack = require('webpack') -const config = require('../config') -const merge = require('webpack-merge') -const baseWebpackConfig = require('./webpack.base.conf') -const HtmlWebpackPlugin = require('html-webpack-plugin') -const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') -const portfinder = require('portfinder') +"use strict"; +const path = require("path"); +const utils = require("./utils"); +const webpack = require("webpack"); +const config = require("../config"); +const merge = require("webpack-merge"); +const baseWebpackConfig = require("./webpack.base.conf"); +const HtmlWebpackPlugin = require("html-webpack-plugin"); +const FriendlyErrorsPlugin = require("friendly-errors-webpack-plugin"); +const portfinder = require("portfinder"); -function resolve (dir) { - return path.join(__dirname, '..', dir) +function resolve(dir) { + return path.join(__dirname, "..", dir); } -const HOST = process.env.HOST -const PORT = process.env.PORT && Number(process.env.PORT) +const HOST = process.env.HOST; +const PORT = process.env.PORT && Number(process.env.PORT); const devWebpackConfig = merge(baseWebpackConfig, { module: { - rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) + rules: utils.styleLoaders({ + sourceMap: config.dev.cssSourceMap, + usePostCSS: true + }) }, // cheap-module-eval-source-map is faster for development devtool: config.dev.devtool, - // these devServer options should be customized in /config/index.js devServer: { - clientLogLevel: 'warning', + clientLogLevel: "warning", historyApiFallback: true, hot: true, compress: true, host: HOST || config.dev.host, port: PORT || config.dev.port, + allowedHosts: ["localhost", "server.com", ".server.com"], open: config.dev.autoOpenBrowser, overlay: config.dev.errorOverlay ? { warnings: false, errors: true } @@ -39,50 +42,54 @@ const devWebpackConfig = merge(baseWebpackConfig, { proxy: config.dev.proxyTable, quiet: true, // necessary for FriendlyErrorsPlugin watchOptions: { - poll: config.dev.poll, + poll: config.dev.poll } }, plugins: [ new webpack.DefinePlugin({ - 'process.env': require('../config/local.env') + "process.env": require("../config/local.env") }), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update. new webpack.NoEmitOnErrorsPlugin(), // https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ - filename: 'index.html', - template: 'index.html', + filename: "index.html", + template: "index.html", inject: true, - favicon: resolve('favicon.ico'), - title: 'vue-element-admin', + favicon: resolve("favicon.ico"), + title: "vue-element-admin", path: config.dev.assetsPublicPath + config.dev.assetsSubDirectory - }), + }) ] -}) +}); module.exports = new Promise((resolve, reject) => { - portfinder.basePort = process.env.PORT || config.dev.port + portfinder.basePort = process.env.PORT || config.dev.port; portfinder.getPort((err, port) => { if (err) { - reject(err) + reject(err); } else { // publish the new Port, necessary for e2e tests - process.env.PORT = port + process.env.PORT = port; // add port to devServer config - devWebpackConfig.devServer.port = port - + devWebpackConfig.devServer.port = port; + console.log('devWebpackConfig', devWebpackConfig) // Add FriendlyErrorsPlugin - devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ - compilationSuccessInfo: { - messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`], - }, - onErrors: config.dev.notifyOnErrors - ? utils.createNotifierCallback() - : undefined - })) + devWebpackConfig.plugins.push( + new FriendlyErrorsPlugin({ + compilationSuccessInfo: { + messages: [ + `Your application is running here: http://${devWebpackConfig.devServer.host}:${port}` + ] + }, + onErrors: config.dev.notifyOnErrors + ? utils.createNotifierCallback() + : undefined + }) + ); - resolve(devWebpackConfig) + resolve(devWebpackConfig); } - }) -}) + }); +}); diff --git a/neutrino-proxy-admin/config/dev.env.js b/neutrino-proxy-admin/config/dev.env.js index 03fd65b0..6bb64a3f 100644 --- a/neutrino-proxy-admin/config/dev.env.js +++ b/neutrino-proxy-admin/config/dev.env.js @@ -1,7 +1,7 @@ module.exports = { NODE_ENV: '"development"', ENV_CONFIG: '"dev"', - BASE_API: '"https://neutrino-proxy.asgc.fun/neutrino-proxy-server"', + BASE_API: '"http://localhost:8888/neutrino-proxy-server"', USER_NAME: '"visitor"', USER_PWD: '"123456"' } diff --git a/neutrino-proxy-admin/config/index.js b/neutrino-proxy-admin/config/index.js index 7ec80132..99bb914b 100644 --- a/neutrino-proxy-admin/config/index.js +++ b/neutrino-proxy-admin/config/index.js @@ -11,7 +11,6 @@ module.exports = { assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, - // Various Dev Server settings host: 'localhost', // can be overwritten by process.env.HOST port: 9527, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined @@ -56,8 +55,8 @@ module.exports = { assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', - // you can set by youself according to actual condition - assetsPublicPath: './', + // you can set by youself according to actual condition + assetsPublicPath: '/', /** * Source Maps diff --git a/neutrino-proxy-admin/config/prod.env.js b/neutrino-proxy-admin/config/prod.env.js index 0c43ea73..0fde97f7 100644 --- a/neutrino-proxy-admin/config/prod.env.js +++ b/neutrino-proxy-admin/config/prod.env.js @@ -1,5 +1,5 @@ module.exports = { NODE_ENV: '"production"', ENV_CONFIG: '"prod"', - BASE_API: '"https://api-prod"' + BASE_API: '"http://np.myone.cc"' // 后端访问地址与 server配置一致 } diff --git a/neutrino-proxy-admin/package.json b/neutrino-proxy-admin/package.json index d2bdb819..b64788bb 100644 --- a/neutrino-proxy-admin/package.json +++ b/neutrino-proxy-admin/package.json @@ -36,7 +36,7 @@ "showdown": "1.8.5", "simplemde": "1.11.2", "sortablejs": "1.7.0", - "vue": "2.5.10", + "vue": "2.5.17", "vue-count-to": "1.0.13", "vue-i18n": "7.3.2", "vue-multiselect": "2.0.8", @@ -70,7 +70,7 @@ "friendly-errors-webpack-plugin": "1.6.1", "html-webpack-plugin": "2.30.1", "node-notifier": "5.1.2", - "node-sass": "^9.0.0", + "node-sass": "4.13.1", "optimize-css-assets-webpack-plugin": "3.2.0", "ora": "1.3.0", "portfinder": "1.0.13", @@ -88,7 +88,7 @@ "url-loader": "0.6.2", "vue-loader": "13.5.0", "vue-style-loader": "3.0.3", - "vue-template-compiler": "2.5.10", + "vue-template-compiler": "2.5.17", "webpack": "3.10.0", "webpack-bundle-analyzer": "2.9.1", "webpack-dev-server": "2.9.7", diff --git a/neutrino-proxy-admin/src/api/domain.js b/neutrino-proxy-admin/src/api/domain.js index d3a9f7fd..918720f1 100644 --- a/neutrino-proxy-admin/src/api/domain.js +++ b/neutrino-proxy-admin/src/api/domain.js @@ -1,8 +1,61 @@ import request from '@/utils/request' -export function domainNameBindInfo(query) { + +export function fetchList(query) { return request({ - url: '/domain-name/bind-info', + url: '/domain/page', + method: 'get', + params: query + }) +} + +export function mappingModify(data) { + return request({ + url: '/domain/modify', + method: 'post', + data + }) +} + +export function deleteMapping(id) { + return request({ + url: '/domain/delete/' + id, + method: 'get' + }) +} + +export function updateEnableStatus(id, enable) { + return request({ + url: '/domain/update/enable-status', + method: 'post', + data: { + id: id, + enable: enable + } + }) +} + +export function portMappingBindSecurityGroup(id, securityGroupId) { + return request({ + url: '/domain/bind/security-group', + method: 'post', + data: { + id: id, + securityGroupId: securityGroupId + } + }) +} + +export function portMappingUnbindSecurityGroup(id) { + return request({ + url: `/domain/unbind/security-group?id=${id}`, + method: 'post' + }) +} + +export function domainAvailable(query) { + return request({ + url: '/domain/available', method: 'get', params: query }) diff --git a/neutrino-proxy-admin/src/components/Dropdown/DropdownTable.vue b/neutrino-proxy-admin/src/components/Dropdown/DropdownTable.vue index ee41288c..80c11027 100644 --- a/neutrino-proxy-admin/src/components/Dropdown/DropdownTable.vue +++ b/neutrino-proxy-admin/src/components/Dropdown/DropdownTable.vue @@ -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, diff --git a/neutrino-proxy-admin/src/lang/zh.js b/neutrino-proxy-admin/src/lang/zh.js index 998795df..e613c8d9 100644 --- a/neutrino-proxy-admin/src/lang/zh.js +++ b/neutrino-proxy-admin/src/lang/zh.js @@ -55,6 +55,7 @@ export default { proxy: '代理配置', license: 'License管理', portMapping: '端口映射', + domainMapping: '域名解析', jobManager: '调度管理', jobLog: '调度日志', log: '日志管理', diff --git a/neutrino-proxy-admin/src/router/index.js b/neutrino-proxy-admin/src/router/index.js index 47a870f2..331573a8 100644 --- a/neutrino-proxy-admin/src/router/index.js +++ b/neutrino-proxy-admin/src/router/index.js @@ -61,7 +61,8 @@ export const asyncRouterMap = [ }, children: [ { path: 'license', component: _import('proxy/license'), name: 'license', meta: { title: 'license' }}, - { path: 'portMapping', component: _import('proxy/portMapping'), name: 'portMapping', meta: { title: 'portMapping' }} + { path: 'portMapping', component: _import('proxy/portMapping'), name: 'portMapping', meta: { title: 'portMapping' }}, + { path: 'domainMapping', component: _import('proxy/domainMapping'), name: 'domainMapping', meta: { title: 'domainMapping' }} ] }, { diff --git a/neutrino-proxy-admin/src/views/proxy/domainMapping.vue b/neutrino-proxy-admin/src/views/proxy/domainMapping.vue new file mode 100644 index 00000000..c4776aa4 --- /dev/null +++ b/neutrino-proxy-admin/src/views/proxy/domainMapping.vue @@ -0,0 +1,408 @@ + + + diff --git a/neutrino-proxy-admin/src/views/proxy/license.vue b/neutrino-proxy-admin/src/views/proxy/license.vue index 8cc70379..aad357e2 100644 --- a/neutrino-proxy-admin/src/views/proxy/license.vue +++ b/neutrino-proxy-admin/src/views/proxy/license.vue @@ -63,12 +63,13 @@ @@ -122,20 +123,6 @@ import { userList } from '@/api/user' import waves from '@/directive/waves' // 水波纹指令 import { parseTime } from '@/utils' - import ButtonPopover from '../../components/Button/buttonPopover' - - const calendarTypeOptions = [ - { key: 'CN', display_name: 'China' }, - { key: 'US', display_name: 'USA' }, - { key: 'JP', display_name: 'Japan' }, - { key: 'EU', display_name: 'Eurozone' } - ] - - // arr to obj ,such as { CN : "China", US : "USA" } - const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => { - acc[cur.key] = cur.display_name - return acc - }, {}) export default { name: 'complexTable', @@ -143,7 +130,6 @@ waves }, components: { - ButtonPopover }, data() { return { @@ -159,7 +145,6 @@ userId: null }, importanceOptions: [1, 2, 3], - calendarTypeOptions, userList: [], sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }], statusOptions: ['published', 'draft', 'deleted'], @@ -214,9 +199,6 @@ } return statusMap[status] }, - typeFilter(type) { - return calendarTypeKeyValue[type] - } }, created() { this.getDataList() @@ -368,19 +350,6 @@ }) }).catch(() => {}) }, - handleDelete2(row) { - deleteLicense(row.id).then(response => { - if (response.data.code === 0) { - this.$notify({ - title: '成功', - message: '删除成功', - type: 'success', - duration: 2000 - }) - this.getList() - } - }) - }, handleDownload() { this.downloadLoading = true import('@/vendor/Export2Excel').then(excel => { diff --git a/neutrino-proxy-admin/src/views/proxy/portMapping.vue b/neutrino-proxy-admin/src/views/proxy/portMapping.vue index 06852884..e60f3c12 100644 --- a/neutrino-proxy-admin/src/views/proxy/portMapping.vue +++ b/neutrino-proxy-admin/src/views/proxy/portMapping.vue @@ -49,11 +49,11 @@ {{ scope.row.protocal }} - + @@ -119,39 +117,22 @@ - - - - - - - - - + + - + @selectedData="selectedFeeItem" placeholder="请选择" :width="500" :disabled="dialogStatus === 'update'" /> - + - - + - + @@ -181,7 +162,7 @@ - + @@ -225,27 +206,12 @@ import { availablePortList, portAvailable } from '@/api/portPool' import { licenseList, licenseAuthList } from '@/api/license' import { protocalList } from '@/api/protocal' 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' import DropdownTable from '../../components/Dropdown/DropdownTable' // 下拉选择加载组件 import loadSelect from "@/components/Select/SelectLoadMore"; - -const calendarTypeOptions = [ - { key: 'CN', display_name: 'China' }, - { key: 'US', display_name: 'USA' }, - { key: 'JP', display_name: 'Japan' }, - { key: 'EU', display_name: 'Eurozone' } -] - -// arr to obj ,such as { CN : "China", US : "USA" } -const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => { - acc[cur.key] = cur.display_name - return acc -}, {}) - export default { name: 'complexTable', directives: { @@ -277,7 +243,6 @@ export default { listQuery: { current: 1, size: 10, - importance: undefined, title: undefined, type: undefined, userId: undefined, @@ -288,8 +253,6 @@ export default { description: undefined }, - importanceOptions: [1, 2, 3], - calendarTypeOptions, sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }], statusOptions: ['published', 'draft', 'deleted'], userList: [], @@ -328,7 +291,9 @@ export default { // { validator: isPortAvailable, trigger: 'change' } ], clientIp: [{ required: true, message: '请输入客户端IP', trigger: 'blur' }], - clientPort: [{ required: true, message: '请输入客户端端口', trigger: 'blur' }], + clientPort: [{ required: true, message: '请输入客户端端口', trigger: 'blur' }, + { pattern: /^([0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/,message: '端口号请选择0-65535间的数字',trigger: 'blur'} + ], protocal: [{ required: true, message: '请选择协议', trigger: 'blur' }] }, downloadLoading: false, @@ -367,12 +332,8 @@ export default { } return statusMap[status] }, - typeFilter(type) { - return calendarTypeKeyValue[type] - } }, created() { - this.getDomainNameBindInfo() this.getDataList() this.getLicenseList() this.getLicenseAuthList() @@ -406,11 +367,6 @@ export default { } }) }, - getDomainNameBindInfo() { - domainNameBindInfo().then(response => { - this.domainName = response.data.data - }) - }, getAvailablePortList(licenseId) { this.loadServerPortQuery.licenseId = licenseId; this.serverPortList = []; //清掉数据 @@ -571,29 +527,6 @@ export default { }) }).catch(() => { }) }, - handleDelete2(row) { - deletePortMapping(row.id).then(response => { - if (response.data.code === 0) { - this.$notify({ - title: '成功', - message: '删除成功', - type: 'success', - duration: 2000 - }) - this.getList() - } - }) - }, - handleDownload() { - this.downloadLoading = true - import('@/vendor/Export2Excel').then(excel => { - const tHeader = ['timestamp', 'title', 'type', 'importance', 'status'] - const filterVal = ['timestamp', 'title', 'type', 'importance', 'status'] - const data = this.formatJson(filterVal, this.list) - excel.export_json_to_excel(tHeader, data, 'table-list') - this.downloadLoading = false - }) - }, formatJson(filterVal, jsonData) { return jsonData.map(v => filterVal.map(j => { if (j === 'timestamp') { diff --git a/neutrino-proxy-admin/src/views/system/portPool.vue b/neutrino-proxy-admin/src/views/system/portPool.vue index 61b3b9b5..0cb5bdc9 100644 --- a/neutrino-proxy-admin/src/views/system/portPool.vue +++ b/neutrino-proxy-admin/src/views/system/portPool.vue @@ -63,7 +63,8 @@ - + + @@ -158,7 +159,10 @@ const calendarTypeOptions = [ dialogPvVisible: false, pvData: [], rules: { - port: [{ required: true, message: '端口必填', trigger: 'blur' }] + port: [ + { required: true, message: '端口必填', trigger: 'blur' }, + { pattern: /^([0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/,message: '端口号请选择0-65535间的数字',trigger: 'blur'} + ] }, downloadLoading: false, checkBoxData:[], //表单勾选的行 diff --git a/neutrino-proxy-client/src/main/java/org/dromara/neutrinoproxy/client/core/CmdChannelHandler.java b/neutrino-proxy-client/src/main/java/org/dromara/neutrinoproxy/client/core/CmdChannelHandler.java index 68db2a0e..4032265c 100644 --- a/neutrino-proxy-client/src/main/java/org/dromara/neutrinoproxy/client/core/CmdChannelHandler.java +++ b/neutrino-proxy-client/src/main/java/org/dromara/neutrinoproxy/client/core/CmdChannelHandler.java @@ -43,7 +43,6 @@ public class CmdChannelHandler extends SimpleChannelInboundHandler if (realServerChannel != null) { realServerChannel.config().setOption(ChannelOption.AUTO_READ, ctx.channel().isWritable()); } - super.channelWritabilityChanged(ctx); } diff --git a/neutrino-proxy-client/src/main/java/org/dromara/neutrinoproxy/client/core/RealServerChannelHandler.java b/neutrino-proxy-client/src/main/java/org/dromara/neutrinoproxy/client/core/RealServerChannelHandler.java index aafec97a..43e3c7c7 100644 --- a/neutrino-proxy-client/src/main/java/org/dromara/neutrinoproxy/client/core/RealServerChannelHandler.java +++ b/neutrino-proxy-client/src/main/java/org/dromara/neutrinoproxy/client/core/RealServerChannelHandler.java @@ -67,11 +67,18 @@ public class RealServerChannelHandler extends SimpleChannelInboundHandler SENDER = AttributeKey.newInstance("sender"); AttributeKey SERVER_PORT = AttributeKey.newInstance("serverPort"); + + AttributeKey DOMAIN = AttributeKey.newInstance("domain"); + AttributeKey REAL_REMOTE_IP = AttributeKey.newInstance("realRemoteIp"); diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/db/DBInitialize.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/db/DBInitialize.java index a387e1ce..51ad71b2 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/db/DBInitialize.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/db/DBInitialize.java @@ -109,7 +109,6 @@ public class DBInitialize implements EventListener { } for (String tableName : initDataTableNameList) { // 表里没有数据的时候,才进行初始化操作 - Object result = dbContext.exe(String.format("select count(1) from `%s`", tableName)); if (result != null && ((Number) result).intValue() > 0) { continue; diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/proxy/ProxyConfig.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/proxy/ProxyConfig.java index 60f89e23..eb48ca3b 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/proxy/ProxyConfig.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/proxy/ProxyConfig.java @@ -63,7 +63,6 @@ public class ProxyConfig { public static class Tcp { private Integer bossThreadCount; private Integer workThreadCount; - private String domainName; private Integer httpProxyPort; private Integer httpsProxyPort; private String keyStorePassword; diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/rest/interceptor/BaseAuthInterceptor.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/rest/interceptor/BaseAuthInterceptor.java index adb1cb68..0d15e5d3 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/rest/interceptor/BaseAuthInterceptor.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/rest/interceptor/BaseAuthInterceptor.java @@ -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()) diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/rest/interceptor/GlobalExceptionFilter.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/rest/interceptor/GlobalExceptionFilter.java index 4ce17769..eb8d240d 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/rest/interceptor/GlobalExceptionFilter.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/base/rest/interceptor/GlobalExceptionFilter.java @@ -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()) diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/constant/ExceptionConstant.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/constant/ExceptionConstant.java index ed149c80..adb3b4f2 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/constant/ExceptionConstant.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/constant/ExceptionConstant.java @@ -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, "系统异常"), diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/DomainController.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/DomainController.java new file mode 100644 index 00000000..4fd6d669 --- /dev/null +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/DomainController.java @@ -0,0 +1,105 @@ +package org.dromara.neutrinoproxy.server.controller; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.dromara.neutrinoproxy.server.base.page.PageInfo; +import org.dromara.neutrinoproxy.server.base.page.PageQuery; +import org.dromara.neutrinoproxy.server.base.proxy.ProxyConfig; +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.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 { + @Inject + private ProxyConfig proxyConfig; + + @Inject + private DomainMappingService domainMappingService; + + @Get + @Mapping("/page") + public PageInfo page(PageQuery pageQuery, DomainMappingDto req) { + ParamCheckUtil.checkNotNull(pageQuery, "pageQuery"); + return domainMappingService.page(pageQuery, req); + } + + @Post + @Mapping("/modify") + public PortMappingCreateRes modify(@Validated DomainMappingDO req) { + if (StringUtils.isBlank(req.getTargetPath())) {// targetPath,默认为127.0.0.1 + req.setTargetPath("127.0.0.1"); + } + req.setProtocal(NetworkProtocolEnum.HTTP.getDesc()); + if (null == req.getSecurityGroupId()) { + req.setSecurityGroupId(0); + } + return domainMappingService.modify(req); + } + + @Get + @Mapping("/one/{id}") + public DomainMappingDto one(Integer id) { + return domainMappingService.one(id); + } + + @Post + @Mapping("/update/enable-status") + public PortMappingUpdateEnableStatusRes updateEnableStatus(PortMappingUpdateEnableStatusReq req) { + return domainMappingService.updateEnableStatus(req); + } + + @Get + @Mapping("/delete/{id}") + public void delete(Integer id) { + domainMappingService.delete(id); + } + + /** + * 绑定安全组 + * @param req portMappingId和securityGroupId + */ + @Post + @Mapping("/bind/security-group") + public void bindSecurityGroup(PortMappingBindSecurityGroupReq req) { + domainMappingService.domainBindSecurityGroup(req.getId(), req.getSecurityGroupId()); + } + + /** + * 安全组解绑 + * @param id 端口映射Id + */ + @Post + @Mapping("/unbind/security-group") + public void unbindSecurityGroup(Integer id) { + domainMappingService.domainUnbindSecurityGroup(id); + } + + + + /** + * 绑定安全组 + * @param domain + */ + @Get + @Mapping("/available") + public boolean exitDomain(@NotBlank String domain, Integer id) { + return domainMappingService.exitDomain(domain, id); + } + +} diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/DomainNameController.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/DomainNameController.java deleted file mode 100644 index 3f64d661..00000000 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/DomainNameController.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.dromara.neutrinoproxy.server.controller; - -import lombok.extern.slf4j.Slf4j; -import org.dromara.neutrinoproxy.server.base.proxy.ProxyConfig; -import org.noear.solon.annotation.Controller; -import org.noear.solon.annotation.Get; -import org.noear.solon.annotation.Inject; -import org.noear.solon.annotation.Mapping; - -/** - * @author: aoshiguchen - * @date: 2023/4/2 - */ -@Slf4j -@Mapping("/domain-name") -@Controller -public class DomainNameController { - @Inject - private ProxyConfig proxyConfig; - - @Get - @Mapping("/bind-info") - public String bindInfo () { - return proxyConfig.getServer().getTcp().getDomainName(); - } - -} diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/LicenseController.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/LicenseController.java index e6034972..1c71679a 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/LicenseController.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/LicenseController.java @@ -31,6 +31,8 @@ import org.dromara.neutrinoproxy.server.controller.res.proxy.*; import org.dromara.neutrinoproxy.server.service.LicenseService; import org.dromara.neutrinoproxy.server.util.ParamCheckUtil; import org.noear.solon.annotation.*; +import org.noear.solon.validation.annotation.Valid; +import org.noear.solon.validation.annotation.Validated; import java.util.List; @@ -39,6 +41,8 @@ import java.util.List; * @author: aoshiguchen * @date: 2022/8/6 */ + +@Valid @Mapping("/license") @Controller public class LicenseController { @@ -101,18 +105,14 @@ public class LicenseController { @Post @Mapping("/update/enable-status") @Authorization(onlyAdmin = true) - public LicenseUpdateEnableStatusRes updateEnableStatus(LicenseUpdateEnableStatusReq req) { - ParamCheckUtil.checkNotNull(req, "req"); - ParamCheckUtil.checkNotNull(req.getId(), "id"); - ParamCheckUtil.checkNotNull(req.getEnable(), "enable"); - + public LicenseUpdateEnableStatusRes updateEnableStatus(@Validated LicenseUpdateEnableStatusReq req) { return licenseService.updateEnableStatus(req); } @Post @Mapping("/delete") @Authorization(onlyAdmin = true) - public void delete(LicenseDeleteReq req) { + public void delete(@Validated LicenseDeleteReq req) { ParamCheckUtil.checkNotNull(req, "req"); ParamCheckUtil.checkNotNull(req.getId(), "id"); diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/PortMappingController.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/PortMappingController.java index ea1dcbe5..3fe90f51 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/PortMappingController.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/PortMappingController.java @@ -51,10 +51,7 @@ public class PortMappingController { } NetworkProtocolEnum networkProtocolEnum = NetworkProtocolEnum.of(req.getProtocal()); ParamCheckUtil.checkNotNull(networkProtocolEnum, ExceptionConstant.AN_UNSUPPORTED_PROTOCOL, req.getProtocal()); - if (networkProtocolEnum != NetworkProtocolEnum.HTTP) { - // 目前仅HTTP支持绑定域名 - req.setSubdomain(null); - } + req.setProtocal(networkProtocolEnum.getDesc()); if (null == req.getProxyResponses()) { req.setProxyResponses(0); @@ -86,10 +83,7 @@ public class PortMappingController { } NetworkProtocolEnum networkProtocolEnum = NetworkProtocolEnum.of(req.getProtocal()); ParamCheckUtil.checkNotNull(networkProtocolEnum, ExceptionConstant.AN_UNSUPPORTED_PROTOCOL, req.getProtocal()); - if (networkProtocolEnum != NetworkProtocolEnum.HTTP) { - // 目前仅HTTP支持绑定域名 - req.setSubdomain(null); - } + req.setProtocal(networkProtocolEnum.getDesc()); if (null == req.getProxyResponses()) { req.setProxyResponses(0); diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/LicenseDeleteReq.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/LicenseDeleteReq.java index 9091d3b8..0264b62f 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/LicenseDeleteReq.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/LicenseDeleteReq.java @@ -1,6 +1,8 @@ package org.dromara.neutrinoproxy.server.controller.req.proxy; import lombok.Data; +import org.noear.solon.validation.annotation.Min; +import org.noear.solon.validation.annotation.NotNull; /** * license删除请求 @@ -9,5 +11,7 @@ import lombok.Data; */ @Data public class LicenseDeleteReq { + @NotNull + @Min(value=2, message="服务端禁止删除") private Integer id; } diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/LicenseUpdateEnableStatusReq.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/LicenseUpdateEnableStatusReq.java index 54c3641e..cea6b988 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/LicenseUpdateEnableStatusReq.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/LicenseUpdateEnableStatusReq.java @@ -23,6 +23,7 @@ package org.dromara.neutrinoproxy.server.controller.req.proxy; import lombok.Data; import org.dromara.neutrinoproxy.server.constant.EnableStatusEnum; +import org.noear.solon.validation.annotation.NotNull; /** * 更新启用状态请求 @@ -31,13 +32,15 @@ import org.dromara.neutrinoproxy.server.constant.EnableStatusEnum; */ @Data public class LicenseUpdateEnableStatusReq { - /** - * id - */ - private Integer id; + /** + * id + */ + @NotNull + private Integer id; /** * 启用状态 * {@link EnableStatusEnum} */ - private Integer enable; + @NotNull + private Integer enable; } diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/PortMappingCreateReq.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/PortMappingCreateReq.java index 87ae362d..56e2b9b9 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/PortMappingCreateReq.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/PortMappingCreateReq.java @@ -38,10 +38,6 @@ public class PortMappingCreateReq { * 协议 */ private String protocal; - /** - * 子域名 - */ - private String subdomain; /** * 服务端端口 */ diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/PortMappingUpdateEnableStatusReq.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/PortMappingUpdateEnableStatusReq.java index 0c832fb1..d89b3986 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/PortMappingUpdateEnableStatusReq.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/PortMappingUpdateEnableStatusReq.java @@ -22,6 +22,7 @@ package org.dromara.neutrinoproxy.server.controller.req.proxy; import lombok.Data; +import lombok.NonNull; /** * 端口映射更新启用状态请求 @@ -34,10 +35,12 @@ public class PortMappingUpdateEnableStatusReq { /** * id */ + @NonNull private Integer id; /** * 启用状态 */ + @NonNull private Integer enable; } diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/PortMappingUpdateReq.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/PortMappingUpdateReq.java index 31f85a01..a61eb2bd 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/PortMappingUpdateReq.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/req/proxy/PortMappingUpdateReq.java @@ -42,10 +42,6 @@ public class PortMappingUpdateReq { * 协议 */ private String protocal; - /** - * 子域名 - */ - private String subdomain; /** * 服务端端口 */ diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/res/proxy/DomainMappingDto.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/res/proxy/DomainMappingDto.java new file mode 100644 index 00000000..ad05d7fe --- /dev/null +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/res/proxy/DomainMappingDto.java @@ -0,0 +1,31 @@ +package org.dromara.neutrinoproxy.server.controller.res.proxy; + + +import lombok.Data; +import lombok.experimental.Accessors; +import org.dromara.neutrinoproxy.server.dal.entity.DomainMappingDO; + +/** + * + * @author xiaojie + * @date + */ +@Accessors(chain = true) +@Data +public class DomainMappingDto extends DomainMappingDO { + + /** + * licenseId + */ + private String licenseName; + + /** + * 用户ID + */ + private Integer userId; + + /** + * 用户名称 + */ + private String userName; +} diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/res/proxy/PortMappingListRes.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/res/proxy/PortMappingListRes.java index 465f9a6d..b9042d28 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/res/proxy/PortMappingListRes.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/controller/res/proxy/PortMappingListRes.java @@ -43,10 +43,6 @@ public class PortMappingListRes { * 协议 */ private String protocal; - /** - * 子域名 - */ - private String subdomain; /** * 域名 */ diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/DomainMappingMapper.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/DomainMappingMapper.java new file mode 100644 index 00000000..39d146e6 --- /dev/null +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/DomainMappingMapper.java @@ -0,0 +1,79 @@ +package org.dromara.neutrinoproxy.server.dal; + +import cn.hutool.core.collection.CollectionUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.toolkit.StringUtils; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.dromara.neutrinoproxy.server.constant.EnableStatusEnum; +import org.dromara.neutrinoproxy.server.controller.req.proxy.PortMappingListReq; +import org.dromara.neutrinoproxy.server.controller.res.proxy.DomainMappingDto; +import org.dromara.neutrinoproxy.server.dal.entity.DomainMappingDO; +import org.dromara.neutrinoproxy.server.dal.entity.DomainMappingDO; + +import java.util.Date; +import java.util.List; +import java.util.Set; + +/** + * + * @author: aoshiguchen + * @date: 2022/8/8 + */ +@Mapper +public interface DomainMappingMapper extends BaseMapper { + + default DomainMappingDO findById(Integer id) { + return this.selectById(id); + } + + default void updateEnableStatus(Integer id, Integer enable, Date updateTime) { + this.update(null, new LambdaUpdateWrapper() + .eq(DomainMappingDO::getId, id) + .set(DomainMappingDO::getEnable, enable) + .set(DomainMappingDO::getUpdateTime, updateTime) + ); + } + + default DomainMappingDO findByDomain(String domain, Set excludeIds) { + return this.selectOne(new LambdaQueryWrapper() + .eq(DomainMappingDO::getDomain, domain) + .notIn(!CollectionUtil.isEmpty(excludeIds), DomainMappingDO::getId, excludeIds) + .last("limit 1") + ); + } + + + default List findEnableListByLicenseId(Integer licenseId) { + return this.selectList(new LambdaQueryWrapper() + .eq(DomainMappingDO::getLicenseId, licenseId) + .eq(DomainMappingDO::getEnable, EnableStatusEnum.ENABLE.getStatus()) + ); + } + + default List findListByServerPort(String domain) { + return this.selectList(new LambdaQueryWrapper() + .eq(DomainMappingDO::getDomain, domain) + ); + } + + default List findListByLicenseId(Integer licenseId) { + return this.selectList(new LambdaQueryWrapper() + .eq(DomainMappingDO::getLicenseId, licenseId) + ); + } + + default DomainMappingDO findByLicenseIdAndServerPort(Integer licenseId, String domain) { + return this.selectOne(new LambdaQueryWrapper() + .eq(DomainMappingDO::getLicenseId, licenseId) + .eq(DomainMappingDO::getDomain, domain) + .last("limit 1") + ); + } + + + List selectDomainMappingByCondition(IPage page, @Param("req") DomainMappingDto req); +} diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/LicenseMapper.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/LicenseMapper.java index c1663f98..e163def4 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/LicenseMapper.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/LicenseMapper.java @@ -26,6 +26,7 @@ import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.dromara.neutrinoproxy.server.dal.entity.LicenseDO; import org.apache.ibatis.annotations.Mapper; +import org.dromara.neutrinoproxy.server.proxy.domain.ProxyMapping; import java.util.Date; import java.util.List; @@ -64,16 +65,18 @@ public interface LicenseMapper extends BaseMapper { default void updateOnlineStatus(Integer id, Integer isOnline, Date updateTime) { this.update(null, new LambdaUpdateWrapper() - .eq(LicenseDO::getId, id) - .set(LicenseDO::getIsOnline, isOnline) - .set(LicenseDO::getUpdateTime, updateTime) + .eq(LicenseDO::getId, id) + .set(LicenseDO::getIsOnline, isOnline) + .set(LicenseDO::getUpdateTime, updateTime) ); } + +// .ne(LicenseDO::getId, 1) default void updateOnlineStatus(Integer isOnline, Date updateTime) { this.update(null, new LambdaUpdateWrapper() - .set(LicenseDO::getIsOnline, isOnline) - .set(LicenseDO::getUpdateTime, updateTime) + .set(LicenseDO::getIsOnline, isOnline) + .set(LicenseDO::getUpdateTime, updateTime) ); } @@ -115,4 +118,8 @@ public interface LicenseMapper extends BaseMapper { .eq(LicenseDO::getKey, licenseKey) ); } + + List findEnableProxyMappingListByLicenseId(Integer licenseId); + + List findAllProxyMappingListByLicenseId(Integer licenseId); } diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/PortMappingMapper.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/PortMappingMapper.java index 71364325..acf0a0f1 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/PortMappingMapper.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/PortMappingMapper.java @@ -44,18 +44,6 @@ public interface PortMappingMapper extends BaseMapper { ); } - /** - * 校验子域名是否重复 - * @param subdomain - * @return - */ - default Boolean checkRepeatBySubdomain(String subdomain, Set excludeIds) { - return StringUtils.isEmpty(subdomain)? Boolean.FALSE : this.selectCount(new LambdaQueryWrapper() - .eq(PortMappingDO::getSubdomain, subdomain) - .notIn(!CollectionUtil.isEmpty(excludeIds), PortMappingDO::getId, excludeIds) - ).intValue() > 0; - } - default List findEnableListByLicenseId(Integer licenseId) { return this.selectList(new LambdaQueryWrapper() .eq(PortMappingDO::getLicenseId, licenseId) diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/entity/DomainMappingDO.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/entity/DomainMappingDO.java new file mode 100644 index 00000000..9a00e1da --- /dev/null +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/entity/DomainMappingDO.java @@ -0,0 +1,120 @@ +/** + * Copyright (c) 2022 aoshiguchen + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.dromara.neutrinoproxy.server.dal.entity; + +import cn.hutool.core.bean.BeanUtil; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.ToString; +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.noear.solon.validation.annotation.NotBlank; +import org.noear.solon.validation.annotation.NotNull; +import org.noear.solon.validation.annotation.Pattern; + +import java.util.Date; + +/** + * 端口映射 + * @author: aoshiguchen + * @date: 2022/8/8 + */ +@ToString +@Accessors(chain = true) +@Data +@TableName("domain_mapping") +public class DomainMappingDO { + @TableId(type = IdType.AUTO) + private Integer id; + /** + * 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; + /** + * 描述 + */ + private String description; + /** + * 目标地址(licenseId客户端,ip:port) + */ + @NotBlank + private String targetPath; + + /** + * 上传限速 + */ + private String upLimitRate; + /** + * 下载限速 + */ + private String downLimitRate; + + /** + * 是否在线 + * {@link OnlineStatusEnum} + */ + @TableField(exist=false) + private Integer isOnline; + + /** + * 启用状态 + * {@link EnableStatusEnum} + */ + private Integer enable; + + /** + * 安全组Id + */ + private Integer securityGroupId = 0; // 设置为null不生效,不知道为啥 + + /** + * 创建时间 + */ + private Date createTime; + /** + * 更新时间 + */ + private Date updateTime; + + public DomainMappingDto toRes() { + DomainMappingDto dto = new DomainMappingDto(); + BeanUtil.copyProperties(this, dto); + return dto; + } + +} diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/entity/LicenseDO.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/entity/LicenseDO.java index c170c381..505f724f 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/entity/LicenseDO.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/entity/LicenseDO.java @@ -87,6 +87,23 @@ public class LicenseDO { */ private Date updateTime; + + public LicenseDO() { + } + + public LicenseDO(Integer id, String name, String key, Integer userId, String upLimitRate, String downLimitRate, Integer isOnline, Integer enable, Date createTime, Date updateTime) { + this.id = id; + this.name = name; + this.key = key; + this.userId = userId; + this.upLimitRate = upLimitRate; + this.downLimitRate = downLimitRate; + this.isOnline = isOnline; + this.enable = enable; + this.createTime = createTime; + this.updateTime = updateTime; + } + public LicenseListRes toRes() { LicenseListRes res = new LicenseListRes(); BeanUtil.copyProperties(this, res); diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/entity/PortMappingDO.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/entity/PortMappingDO.java index 16745fda..8d519c9b 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/entity/PortMappingDO.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/dal/entity/PortMappingDO.java @@ -31,6 +31,7 @@ import lombok.Data; import lombok.ToString; import lombok.experimental.Accessors; import org.dromara.neutrinoproxy.server.controller.res.proxy.PortMappingListRes; +import org.dromara.neutrinoproxy.server.proxy.domain.ProxyMapping; import java.util.Date; @@ -54,10 +55,6 @@ public class PortMappingDO { * 协议 */ private String protocal; - /** - * 子域名 - */ - private String subdomain; /** * 服务端端口 */ @@ -121,4 +118,5 @@ public class PortMappingDO { BeanUtil.copyProperties(this, res); return res; } + } diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/job/DemoJob.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/job/DemoJob.java index 4696dca2..782acce1 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/job/DemoJob.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/job/DemoJob.java @@ -13,7 +13,7 @@ import org.noear.solon.annotation.Component; @Slf4j @Component @JobHandler(name = "DemoJob", cron = "0/10 * * * * ?", param = "{\"a\":1}") -public class DemoJob implements IJobHandler { +public class DemoJob implements IJobHandler { @Override public void execute(String param) throws Exception { diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/core/ProxyTunnelServer.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/core/ProxyTunnelServer.java index d45d2a25..286ed1f2 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/core/ProxyTunnelServer.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/core/ProxyTunnelServer.java @@ -63,9 +63,9 @@ public class ProxyTunnelServer implements EventListener { }); try { bootstrap.bind(proxyConfig.getTunnel().getPort()).sync(); - log.info("proxy server started,port:{}", proxyConfig.getTunnel().getPort()); + log.info("ProxyTunnelServer,port:{}", proxyConfig.getTunnel().getPort()); } catch (Exception e) { - log.error("proxy server error", e); + log.error("ProxyTunnelServer error", e); } } @@ -84,9 +84,9 @@ public class ProxyTunnelServer implements EventListener { }); try { bootstrap.bind(proxyConfig.getTunnel().getSslPort()).sync(); - log.info("proxy server started,SSL port: {}", proxyConfig.getTunnel().getSslPort()); + log.info("ProxyTunnelServer,SSL port: {}", proxyConfig.getTunnel().getSslPort()); } catch (Exception e) { - log.error("proxy server error", e); + log.error("ProxyTunnelServer error", e); } } diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/domain/DomainMapping.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/domain/DomainMapping.java new file mode 100644 index 00000000..02a0776b --- /dev/null +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/domain/DomainMapping.java @@ -0,0 +1,39 @@ +package org.dromara.neutrinoproxy.server.proxy.domain; + +import lombok.Data; + +/** + * @author xiaojie + * @date + */ +@Data +public class DomainMapping { + + /** + * domainMapping 主键id + */ + private Integer id; + /** + * License + */ + private Integer licenseId; + /** + * 客户端信息 IP:port + */ + private String domain; + /** + * 目标地址(其中含有\n隔离多个 目标地址) + */ + private String targetPath; + + + public DomainMapping() { + } + + public DomainMapping(Integer id, Integer licenseId, String domain, String targetPath) { + this.id = id; + this.licenseId = licenseId; + this.domain = domain; + this.targetPath = targetPath; + } +} diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/domain/ProxyMapping.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/domain/ProxyMapping.java index f535fb35..8db6e2c3 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/domain/ProxyMapping.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/domain/ProxyMapping.java @@ -16,6 +16,10 @@ import java.util.List; @Accessors(chain = true) @Data public class ProxyMapping { + /** + * licenseId + */ + private Integer licenseId; /** * 服务端端口 */ @@ -24,8 +28,23 @@ public class ProxyMapping { * 客户端信息 IP:port */ private String lanInfo; + /** + * 协议 + */ + private String protocal; - public static List buildList(List portMappingList) { + + public ProxyMapping() { + } + + public ProxyMapping(Integer licenseId, Integer serverPort, String lanInfo, String protocal) { + this.licenseId = licenseId; + this.serverPort = serverPort; + this.lanInfo = lanInfo; + this.protocal = protocal; + } + + public static List buildList(List portMappingList) { List list = new ArrayList<>(); if (CollectionUtil.isEmpty(portMappingList)) { return list; @@ -38,8 +57,13 @@ public class ProxyMapping { public static ProxyMapping build(PortMappingDO portMappingDO) { return new ProxyMapping() - .setServerPort(portMappingDO.getServerPort()) - .setLanInfo(String.format("%s:%s", portMappingDO.getClientIp(), portMappingDO.getClientPort())); + .setLicenseId(portMappingDO.getLicenseId()) + .setServerPort(portMappingDO.getServerPort()) + .setLanInfo(String.format("%s:%s", portMappingDO.getClientIp(), portMappingDO.getClientPort())) + .setProtocal(portMappingDO.getProtocal()); } + + + } diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/enhance/HttpProxy.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/enhance/HttpProxy.java index ce1197db..a0db65a1 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/enhance/HttpProxy.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/enhance/HttpProxy.java @@ -1,8 +1,9 @@ package org.dromara.neutrinoproxy.server.proxy.enhance; -import cn.hutool.core.util.StrUtil; import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.*; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; @@ -10,7 +11,6 @@ import io.netty.handler.logging.LoggingHandler; import lombok.extern.slf4j.Slf4j; import org.dromara.neutrinoproxy.server.base.proxy.ProxyConfig; import org.dromara.neutrinoproxy.server.proxy.core.BytesMetricsHandler; -import org.dromara.neutrinoproxy.server.proxy.core.ProxyTunnelServer; import org.dromara.neutrinoproxy.server.proxy.security.HttpVisitorSecurityChannelHandler; import org.dromara.neutrinoproxy.server.proxy.security.VisitorFlowLimiterChannelHandler; import org.noear.solon.annotation.Component; @@ -19,7 +19,8 @@ import org.noear.solon.core.event.AppLoadEndEvent; import org.noear.solon.core.event.EventListener; /** - * HTTP代理 + * 应用加载完成事件(即启动完成)- 判断是否配置域名-配置了域名则启动HTTP代理 + * 默认端口 80 * @author: aoshiguchen * @date: 2023/4/2 */ @@ -28,35 +29,55 @@ import org.noear.solon.core.event.EventListener; public class HttpProxy implements EventListener { @Inject private ProxyConfig proxyConfig; + + /** + * NioServerSocketChannel对应的future + */ + protected ChannelFuture httpFuture; @Override public void onEvent(AppLoadEndEvent appLoadEndEvent) throws Throwable { - if (StrUtil.isBlank(proxyConfig.getServer().getTcp().getDomainName()) || null == proxyConfig.getServer().getTcp().getHttpProxyPort()) { + if (null == proxyConfig.getServer().getTcp().getHttpProxyPort()) { log.info("no config domain name,nonsupport http proxy."); return; } + this.start(); } private void start() { + // 处理网络连接---接受请求 + EventLoopGroup bossGroup = new NioEventLoopGroup(1); + // 进行socketChannel的网络读写 + EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); - bootstrap.group(new NioEventLoopGroup(1), new NioEventLoopGroup()) - .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer() { - @Override - public void initChannel(SocketChannel ch) throws Exception { - 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("flowLimiter",new VisitorFlowLimiterChannelHandler()); - ch.pipeline().addLast(new HttpVisitorChannelHandler()); - } - }); - bootstrap.bind("0.0.0.0", proxyConfig.getServer().getTcp().getHttpProxyPort()).sync(); - log.info("Http proxy server start success!port:{}", proxyConfig.getServer().getTcp().getHttpProxyPort()); + bootstrap.group(bossGroup, workerGroup) + .channel(NioServerSocketChannel.class) + .childHandler(new ChannelInitializer() { + @Override + public void initChannel(SocketChannel ch) throws Exception { + if (null != proxyConfig.getServer().getTcp().getTransferLogEnable() && + proxyConfig.getServer().getTcp().getTransferLogEnable()) { + ch.pipeline().addFirst(new LoggingHandler(HttpProxy.class)); + } + ch.pipeline().addFirst(new BytesMetricsHandler()) + .addLast(new HttpVisitorSecurityChannelHandler()) + .addLast("flowLimiter",new VisitorFlowLimiterChannelHandler()) + .addLast(new HttpVisitorChannelHandler()); + } + }); + httpFuture = bootstrap.bind("0.0.0.0", proxyConfig.getServer().getTcp().getHttpProxyPort()).sync(); + log.info("Http proxy server started success!port:{}", proxyConfig.getServer().getTcp().getHttpProxyPort()); + //添加关闭重启的监听器,3秒后尝试重启 +// httpFuture.channel().closeFuture().addListener(genericFutureListener); +// httpFuture.channel().closeFuture().sync(); } catch (Exception e) { log.error("http proxy start err!", e); + } finally { +// bossGroup.shutdownGracefully(); +// workerGroup.shutdownGracefully(); +// httpFuture.channel().close(); } } + } diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/enhance/HttpVisitorChannelHandler.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/enhance/HttpVisitorChannelHandler.java index 40a18a0f..f05e8f3d 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/enhance/HttpVisitorChannelHandler.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/enhance/HttpVisitorChannelHandler.java @@ -19,6 +19,7 @@ import org.noear.solon.Solon; import java.net.InetSocketAddress; /** + * HTTP 访客处理器 * @author: aoshiguchen * @date: 2023/5/27 */ @@ -30,6 +31,7 @@ public class HttpVisitorChannelHandler extends SimpleChannelInboundHandler { Channel proxyChannel = channel.attr(Constants.NEXT_CHANNEL).get(); if (null == proxyChannel) { @@ -37,14 +39,11 @@ public class HttpVisitorChannelHandler extends SimpleChannelInboundHandler { @Inject private ProxyConfig proxyConfig; + /** + * NioServerSocketChannel对应的future + */ + private ChannelFuture httpsFuture; @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())) { + 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; } @@ -46,26 +56,38 @@ public class HttpsProxy implements EventListener { } private void start() { + // 处理网络连接---接受请求 + EventLoopGroup bossGroup = new NioEventLoopGroup(1); + // 进行socketChannel的网络读写 + EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); - bootstrap.group(new NioEventLoopGroup(1), new NioEventLoopGroup()) - .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer() { - @Override - public void initChannel(SocketChannel ch) throws Exception { - if (null != proxyConfig.getServer().getTcp().getTransferLogEnable() && proxyConfig.getServer().getTcp().getTransferLogEnable()) { - ch.pipeline().addFirst(new LoggingHandler(HttpsProxy.class)); - } - ch.pipeline().addLast(createSslHandler()); - ch.pipeline().addFirst(new BytesMetricsHandler()); - ch.pipeline().addLast(new HttpVisitorSecurityChannelHandler(proxyConfig.getServer().getTcp().getDomainName())); - ch.pipeline().addLast("flowLimiter",new VisitorFlowLimiterChannelHandler()); - ch.pipeline().addLast(new HttpVisitorChannelHandler()); - } - }); - bootstrap.bind("0.0.0.0", proxyConfig.getServer().getTcp().getHttpsProxyPort()).sync(); + bootstrap.group(bossGroup, workerGroup); + bootstrap.channel(NioServerSocketChannel.class); + bootstrap.childHandler(new ChannelInitializer() { + @Override + public void initChannel(SocketChannel ch) throws Exception { + if (null != proxyConfig.getServer().getTcp().getTransferLogEnable() && proxyConfig.getServer().getTcp().getTransferLogEnable()) { + ch.pipeline().addFirst(new LoggingHandler(HttpsProxy.class)); + } + ch.pipeline().addLast(createSslHandler()) + .addFirst(new BytesMetricsHandler()) + .addLast(new HttpVisitorSecurityChannelHandler()) + .addLast("flowLimiter", new VisitorFlowLimiterChannelHandler()) + .addLast(new HttpVisitorChannelHandler()); + } + }); + httpsFuture = bootstrap.bind("0.0.0.0", proxyConfig.getServer().getTcp().getHttpsProxyPort()).sync(); log.info("Https proxy server started!port:{}", proxyConfig.getServer().getTcp().getHttpsProxyPort()); + //添加关闭重启的监听器,3秒后尝试重启 +// httpsFuture.channel().closeFuture().addListener(genericFutureListener); +// httpsFuture.channel().closeFuture().sync(); } catch (Exception e) { log.error("https proxy start err!", e); + } finally { +// bossGroup.shutdownGracefully(); +// workerGroup.shutdownGracefully(); +// httpsFuture.channel().close(); } } diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/handler/ProxyMessageAuthHandler.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/handler/ProxyMessageAuthHandler.java index 79cc0613..1fc27ffa 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/handler/ProxyMessageAuthHandler.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/handler/ProxyMessageAuthHandler.java @@ -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; diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/security/HttpVisitorSecurityChannelHandler.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/security/HttpVisitorSecurityChannelHandler.java index eccd2914..d87311cc 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/security/HttpVisitorSecurityChannelHandler.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/security/HttpVisitorSecurityChannelHandler.java @@ -1,6 +1,5 @@ package org.dromara.neutrinoproxy.server.proxy.security; -import cn.hutool.core.util.StrUtil; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; @@ -9,79 +8,59 @@ import org.apache.commons.lang3.StringUtils; import org.dromara.neutrinoproxy.core.Constants; import org.dromara.neutrinoproxy.core.util.HttpUtil; import org.dromara.neutrinoproxy.core.util.IpUtil; +import org.dromara.neutrinoproxy.server.proxy.domain.DomainMapping; import org.dromara.neutrinoproxy.server.service.PortMappingService; import org.dromara.neutrinoproxy.server.service.SecurityGroupService; import org.dromara.neutrinoproxy.server.util.ProxyUtil; import org.noear.solon.Solon; /** + * HTTP 访问安全检测 * @author: aoshiguchen * @date: 2023/12/14 */ @Slf4j 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 SecurityGroupService securityGroupService = Solon.context().getBean(SecurityGroupService.class); + private PortMappingService portMappingService = Solon.context().getBean(PortMappingService.class); - 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) { + Integer domainId = ctx.channel().attr(Constants.SERVER_PORT).get(); + if (null == domainId) { // 获取Host请求头 byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); String httpContent = new String(bytes); - String host = HttpUtil.getHostIgnorePort(httpContent); + String 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; } + DomainMapping dm = ProxyUtil.domainMapingMap.get(domain); // 判断IP是否在该端口绑定的安全组允许的规则内 String ip = IpUtil.getRealRemoteIp(httpContent); if (ip == null) { ip = IpUtil.getRemoteIp(ctx); } - if (!securityGroupService.judgeAllow(ip, portMappingService.getSecurityGroupIdByMappingPort(serverPort))) { + if (null==dm.getId() || !securityGroupService.judgeAllow(ip, portMappingService.getSecurityGroupIdByMappingPort(dm.getId()))) { // 不在安全组规则放行范围内 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.SERVER_PORT).set(dm.getId()); + ctx.channel().attr(Constants.LICENSE_ID).set(dm.getLicenseId()); } // 继续传播 diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/security/UdpVisitorSecurityChannelHandler.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/security/UdpVisitorSecurityChannelHandler.java index 8e9d43f0..7a2417b9 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/security/UdpVisitorSecurityChannelHandler.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/proxy/security/UdpVisitorSecurityChannelHandler.java @@ -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); diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/DomainMappingService.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/DomainMappingService.java new file mode 100644 index 00000000..23af481f --- /dev/null +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/DomainMappingService.java @@ -0,0 +1,298 @@ +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; +import com.baomidou.mybatisplus.core.toolkit.StringUtils; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.solon.plugins.pagination.Page; +import com.google.common.collect.Sets; +import org.apache.ibatis.solon.annotation.Db; +import org.dromara.neutrinoproxy.server.base.db.DBInitialize; +import org.dromara.neutrinoproxy.server.base.page.PageInfo; +import org.dromara.neutrinoproxy.server.base.page.PageQuery; +import org.dromara.neutrinoproxy.server.base.proxy.ProxyConfig; +import org.dromara.neutrinoproxy.server.base.rest.SystemContextHolder; +import org.dromara.neutrinoproxy.server.constant.EnableStatusEnum; +import org.dromara.neutrinoproxy.server.constant.ExceptionConstant; +import org.dromara.neutrinoproxy.server.constant.NetworkProtocolEnum; +import org.dromara.neutrinoproxy.server.constant.OnlineStatusEnum; +import org.dromara.neutrinoproxy.server.controller.req.proxy.PortMappingCreateReq; +import org.dromara.neutrinoproxy.server.controller.req.proxy.PortMappingListReq; +import org.dromara.neutrinoproxy.server.controller.req.proxy.PortMappingUpdateEnableStatusReq; +import org.dromara.neutrinoproxy.server.controller.req.proxy.PortMappingUpdateReq; +import org.dromara.neutrinoproxy.server.controller.res.proxy.*; +import org.dromara.neutrinoproxy.server.dal.DomainMappingMapper; +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.proxy.domain.ProxyMapping; +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; +import org.noear.solon.annotation.Init; +import org.noear.solon.annotation.Inject; +import org.noear.solon.core.bean.LifecycleBean; +import org.noear.solon.core.runtime.NativeDetector; +import org.noear.solon.data.annotation.Tran; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * + * 域名解析 service + * author xiaojie + */ +@Component +public class DomainMappingService implements LifecycleBean { + @Db + private DomainMappingMapper domainMappingMapper; + @Db + private LicenseMapper licenseMapper; + @Db + private UserMapper userMapper; + @Db + private PortPoolMapper portPoolMapper; + @Inject + private VisitorChannelService visitorChannelService; + + @Inject + private PortPoolService portPoolService; + @Inject + private ProxyConfig proxyConfig; + @Inject + private DBInitialize dbInitialize; + @Inject + private LicenseService licenseService; + + + public PageInfo page(PageQuery pageQuery, DomainMappingDto req) { + if (StringUtils.isNotEmpty(req.getDescription())) { + //描述字段为模糊查询,在应用层处理,否则sqlite不支持 + req.setDescription("%" + req.getDescription() + "%"); + } + + // 协议名称转换 + if (StringUtils.isNotBlank(req.getProtocal())) { + NetworkProtocolEnum networkProtocolEnum = NetworkProtocolEnum.of(req.getProtocal()); + req.setProtocal(networkProtocolEnum.getDesc()); + } + + Page page = new Page<>(pageQuery.getCurrent(), pageQuery.getSize()); + List list = domainMappingMapper.selectDomainMappingByCondition(page, req); + List respList = list.stream().map(DomainMappingDO::toRes).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(list)) { + return PageInfo.of(respList, page.getTotal(), pageQuery.getCurrent(), pageQuery.getSize()); + } + + Set licenseIds = respList.stream().map(DomainMappingDto::getLicenseId).collect(Collectors.toSet()); + List licenseList = licenseMapper.findByIds(licenseIds); + if (CollectionUtil.isEmpty(licenseList)) { + return PageInfo.of(respList, page.getTotal(), pageQuery.getCurrent(), pageQuery.getSize()); + } + Set userIds = licenseList.stream().map(LicenseDO::getUserId).collect(Collectors.toSet()); + List userList = userMapper.findByIds(userIds); + Map licenseMap = licenseList.stream().collect(Collectors.toMap(LicenseDO::getId, Function.identity())); + Map userMap = userList.stream().collect(Collectors.toMap(UserDO::getId, Function.identity())); + + respList.forEach(item -> { + LicenseDO license = licenseMap.get(item.getLicenseId()); + if (null == license) { + return; + } + item.setLicenseName(license.getName()); + item.setUserId(license.getUserId()); + UserDO user = userMap.get(license.getUserId()); + if (null == user) { + return; + } + item.setUserName(user.getName()); + if (NetworkProtocolEnum.HTTP.getDesc().equals(item.getProtocal())) { + item.setProtocal("HTTP(S)"); + } + }); + //sorted [userId asc] [licenseId asc] [createTime asc] + respList = respList.stream() + .filter(e -> null != e.getUserId()) + .sorted(Comparator.comparing(DomainMappingDto::getUserId).thenComparing(DomainMappingDto::getLicenseId).thenComparing(DomainMappingDto::getCreateTime)).collect(Collectors.toList()); + return PageInfo.of(respList, page.getTotal(), pageQuery.getCurrent(), pageQuery.getSize()); + } + + @Tran + public PortMappingCreateRes modify(DomainMappingDO dmd) { + LicenseDO licenseDO = licenseMapper.findById(dmd.getLicenseId()); + ParamCheckUtil.checkNotNull(licenseDO, ExceptionConstant.LICENSE_NOT_EXIST); + if (!SystemContextHolder.isAdmin()) { + // 临时处理,如果当前用户不是管理员,则操作userId不能为1 + ParamCheckUtil.checkExpression(!licenseDO.getUserId().equals(1), ExceptionConstant.NO_PERMISSION_VISIT); + } + if (null != dmd.getId()) { // 编辑 + Date now = new Date(); + dmd.setEnable(EnableStatusEnum.ENABLE.getStatus()); + dmd.setUpdateTime(now); + domainMappingMapper.updateById(dmd); + // 更新VisitorChannel + DomainMappingDO oldDmd = domainMappingMapper.findById(dmd.getId()); + ParamCheckUtil.checkNotNull(oldDmd, ExceptionConstant.PORT_MAPPING_NOT_EXIST); + ProxyMapping oldProxy = new ProxyMapping(oldDmd.getLicenseId(),oldDmd.getId(),oldDmd.getTargetPath(), NetworkProtocolEnum.HTTP.getDesc()); + visitorChannelService.updateVisitorChannelByProxyMapping(oldProxy, new ProxyMapping(dmd.getLicenseId(),dmd.getId(),dmd.getTargetPath(), NetworkProtocolEnum.HTTP.getDesc())); + } else { // 新增 + Date now = new Date(); + dmd.setEnable(EnableStatusEnum.ENABLE.getStatus()); + dmd.setCreateTime(now); + dmd.setUpdateTime(now); + domainMappingMapper.insert(dmd); + // 新增 + visitorChannelService.addVisitorChannelByProxyMapping(new ProxyMapping(dmd.getLicenseId(),dmd.getId(),dmd.getTargetPath(), NetworkProtocolEnum.HTTP.getDesc())); + } + // 更新域名映射 + ProxyUtil.domainMapingMap.put(dmd.getDomain(), new DomainMapping(dmd.getId(), dmd.getLicenseId(), dmd.getDomain(), dmd.getTargetPath())); + + return new PortMappingCreateRes(); + } + @Tran + public PortMappingUpdateEnableStatusRes updateEnableStatus(PortMappingUpdateEnableStatusReq req) { + DomainMappingDO domainMappingDO = domainMappingMapper.findById(req.getId()); + ParamCheckUtil.checkNotNull(domainMappingDO, ExceptionConstant.PORT_MAPPING_NOT_EXIST); + + LicenseDO licenseDO = licenseMapper.findById(domainMappingDO.getLicenseId()); + ParamCheckUtil.checkNotNull(licenseDO, ExceptionConstant.LICENSE_NOT_EXIST); + if (!SystemContextHolder.isAdmin()) { + ParamCheckUtil.checkExpression(!licenseDO.getUserId().equals(1), ExceptionConstant.NO_PERMISSION_VISIT); + } + + domainMappingMapper.updateEnableStatus(req.getId(), req.getEnable(), new Date()); + + // 更新VisitorChannel + domainMappingDO.setEnable(req.getEnable()); + if (EnableStatusEnum.ENABLE == EnableStatusEnum.of(req.getEnable())) { + visitorChannelService.addVisitorChannelByProxyMapping(new ProxyMapping(domainMappingDO.getLicenseId(),domainMappingDO.getId(),domainMappingDO.getTargetPath(), NetworkProtocolEnum.HTTP.getDesc())); + } else { + visitorChannelService.removeVisitorChannelByProxyMapping(new ProxyMapping(domainMappingDO.getLicenseId(),domainMappingDO.getId(),domainMappingDO.getTargetPath(), NetworkProtocolEnum.HTTP.getDesc())); + } + + return new PortMappingUpdateEnableStatusRes(); + } + + public void delete(Integer id) { + DomainMappingDO domain = domainMappingMapper.findById(id); + ParamCheckUtil.checkNotNull(domain, ExceptionConstant.PORT_MAPPING_NOT_EXIST); + + LicenseDO licenseDO = licenseMapper.findById(domain.getLicenseId()); + if (null != licenseDO && !SystemContextHolder.isAdmin()) { + // 临时处理,如果当前用户不是管理员,则操作userId不能为1 + ParamCheckUtil.checkExpression(!licenseDO.getUserId().equals(1), ExceptionConstant.NO_PERMISSION_VISIT); + } + domainMappingMapper.deleteById(id); + + // 更新VisitorChannel + visitorChannelService.removeVisitorChannelByProxyMapping(new ProxyMapping(domain.getLicenseId(),domain.getId(),domain.getTargetPath(), NetworkProtocolEnum.HTTP.getDesc())); + } + + public void domainBindSecurityGroup(Integer portMappingId, Integer groupId) { + DomainMappingDO mappingDO = domainMappingMapper.findById(portMappingId); + if (mappingDO == null) { + throw new RuntimeException("指定的端口映射不存在"); + } + mappingDO.setSecurityGroupId(groupId); + mappingDO.setUpdateTime(new Date()); + domainMappingMapper.updateById(mappingDO); + } + + public void domainUnbindSecurityGroup(Integer portMappingId) { + DomainMappingDO mappingDO = domainMappingMapper.findById(portMappingId); + if (mappingDO == null) { + throw new RuntimeException("指定的端口映射不存在"); + } + mappingDO.setSecurityGroupId(0); + mappingDO.setUpdateTime(new Date()); + domainMappingMapper.updateById(mappingDO); + } + + /** + * 根据license查询可用的端口映射列表 + * + * @param licenseId + * @return + */ + public List findEnableListByLicenseId(Integer licenseId) { + return domainMappingMapper.findEnableListByLicenseId(licenseId); + } + + + /** + * 服务端项目停止、启动时,更新在线状态为离线 + */ + @Init + public void init() { + // aot 阶段,不初始化 + if (NativeDetector.isAotRuntime()) { + return; + } + List allMappingDOList = domainMappingMapper.selectList(Wrappers.lambdaQuery(DomainMappingDO.class)); + if(CollectionUtil.isNotEmpty(allMappingDOList)) { + allMappingDOList.forEach(domain -> { + ProxyUtil.domainMapingMap.put(domain.getDomain(), + new DomainMapping(domain.getId(), domain.getLicenseId(), domain.getDomain(), domain.getTargetPath())); + }); + } + } + + + + @Override + public void start() throws Throwable { + + } + + /** + * 服务端项目停止、启动时,更新在线状态为离线 + */ + @Override + public void stop() throws Throwable { +// domainMappingMapper.updateOnlineStatus(OnlineStatusEnum.OFFLINE.getStatus(), new Date()); + } + + public DomainMappingDto one(Integer id) { + DomainMappingDO domainMappingDO = domainMappingMapper.findById(id); + if (null == domainMappingDO) { + return null; + } + DomainMappingDto res = (DomainMappingDto)domainMappingDO; + + LicenseDO license = licenseMapper.findById(domainMappingDO.getLicenseId()); + if (null != license) { + res.setLicenseName(license.getName()); + res.setUserId(license.getUserId()); + UserDO user = userMapper.findById(license.getUserId()); + if (null != user) { + res.setUserName(user.getName()); + } + } + 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; + } +} diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/LicenseService.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/LicenseService.java index 4d649029..1becd487 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/LicenseService.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/LicenseService.java @@ -40,6 +40,7 @@ import org.noear.solon.annotation.Init; import org.noear.solon.annotation.Inject; import org.noear.solon.core.bean.LifecycleBean; import org.noear.solon.core.runtime.NativeDetector; +import org.noear.solon.data.annotation.Tran; import java.util.Arrays; import java.util.Date; @@ -107,17 +108,16 @@ public class LicenseService implements LifecycleBean { private List assembleConvertLicenses(List list) { List licenseList = list.stream().map(LicenseDO::toRes).collect(Collectors.toList()); - if (!CollectionUtil.isEmpty(licenseList)) { - Set userIds = licenseList.stream().map(LicenseListRes::getUserId).collect(Collectors.toSet()); - List userList = userMapper.findByIds(userIds); - Map userMap = userList.stream().collect(Collectors.toMap(UserDO::getId, Function.identity())); - for (LicenseListRes item : licenseList) { - UserDO userDO = userMap.get(item.getUserId()); - if (null != userDO) { - item.setUserName(userDO.getName()); - } - item.setKey(desensitization(item.getUserId(), item.getKey())); + // 插入用户名 + Set userIds = licenseList.stream().map(LicenseListRes::getUserId).collect(Collectors.toSet()); + List userList = userMapper.findByIds(userIds); + Map userMap = userList.stream().collect(Collectors.toMap(UserDO::getId, Function.identity())); + for (LicenseListRes item : licenseList) { + UserDO userDO = userMap.get(item.getUserId()); + if (null != userDO) { + item.setUserName(userDO.getName()); } + item.setKey(desensitization(item.getUserId(), item.getKey())); } return licenseList; } @@ -203,10 +203,20 @@ public class LicenseService implements LifecycleBean { * @param req * @return */ + @Tran public LicenseUpdateEnableStatusRes updateEnableStatus(LicenseUpdateEnableStatusReq req) { - licenseMapper.updateEnableStatus(req.getId(), req.getEnable(), new Date()); - // 更新VisitorChannel - visitorChannelService.updateVisitorChannelByLicenseId(req.getId(), req.getEnable()); + // 服务端免通道 直接转发,所以无需建立客户端通道。启用即在线,禁用即离线 20240311 设计取消 +// if (req.getId() == 1) { +// licenseMapper.update(null, new LambdaUpdateWrapper() +// .eq(LicenseDO::getId, req.getId()) +// .set(LicenseDO::getEnable, req.getEnable()) +// .set(LicenseDO::getIsOnline, req.getEnable()) +// .set(LicenseDO::getUpdateTime, new Date())); +// } else { + licenseMapper.updateEnableStatus(req.getId(), req.getEnable(), new Date()); + // 更新VisitorChannel + visitorChannelService.updateVisitorChannelByLicenseId(req.getId(), req.getEnable()); +// } return new LicenseUpdateEnableStatusRes(); } @@ -338,6 +348,7 @@ public class LicenseService implements LifecycleBean { .eq(LicenseDO::getEnable, EnableStatusEnum.ENABLE.getStatus()) .eq(LicenseDO::getUserId, SystemContextHolder.getUserId()) ); + if (CollectionUtil.isEmpty(list)) return null; List licenseList = assembleConvertLicenses(list); return licenseList; } diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/PortMappingService.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/PortMappingService.java index 5ce15105..6b202137 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/PortMappingService.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/PortMappingService.java @@ -39,6 +39,7 @@ import org.dromara.neutrinoproxy.server.dal.entity.LicenseDO; import org.dromara.neutrinoproxy.server.dal.entity.PortMappingDO; import org.dromara.neutrinoproxy.server.dal.entity.PortPoolDO; import org.dromara.neutrinoproxy.server.dal.entity.UserDO; +import org.dromara.neutrinoproxy.server.proxy.domain.ProxyMapping; import org.dromara.neutrinoproxy.server.service.bo.FlowLimitBO; import org.dromara.neutrinoproxy.server.util.ParamCheckUtil; import org.dromara.neutrinoproxy.server.util.ProxyUtil; @@ -130,9 +131,6 @@ public class PortMappingService implements LifecycleBean { return; } item.setUserName(user.getName()); - if (StrUtil.isNotBlank(proxyConfig.getServer().getTcp().getDomainName()) && StrUtil.isNotBlank(item.getSubdomain())) { - item.setDomain(item.getSubdomain() + "." + proxyConfig.getServer().getTcp().getDomainName()); - } if (NetworkProtocolEnum.HTTP.getDesc().equals(item.getProtocal())) { item.setProtocal("HTTP(S)"); } @@ -154,13 +152,11 @@ public class PortMappingService implements LifecycleBean { PortPoolDO portPoolDO = portPoolMapper.findByPort(req.getServerPort()); ParamCheckUtil.checkNotNull(portPoolDO, ExceptionConstant.PORT_NOT_EXIST); ParamCheckUtil.checkExpression(null == portMappingMapper.findByPort(req.getServerPort(), null), ExceptionConstant.PORT_CANNOT_REPEAT_MAPPING, req.getServerPort()); - ParamCheckUtil.checkExpression(!portMappingMapper.checkRepeatBySubdomain(req.getSubdomain(), null), ExceptionConstant.PORT_MAPPING_SUBDONAME_CONNOT_REPEAT); Date now = new Date(); PortMappingDO portMappingDO = new PortMappingDO(); portMappingDO.setLicenseId(req.getLicenseId()); portMappingDO.setProtocal(req.getProtocal()); - portMappingDO.setSubdomain(req.getSubdomain()); portMappingDO.setServerPort(req.getServerPort()); portMappingDO.setClientIp(req.getClientIp()); portMappingDO.setClientPort(req.getClientPort()); @@ -175,11 +171,7 @@ public class PortMappingService implements LifecycleBean { portMappingDO.setUpdateTime(now); portMappingMapper.insert(portMappingDO); // 更新VisitorChannel - visitorChannelService.addVisitorChannelByPortMapping(portMappingDO); - // 更新域名映射 - if (NetworkProtocolEnum.isHttp(portMappingDO.getProtocal()) && StrUtil.isNotBlank(proxyConfig.getServer().getTcp().getDomainName()) && StrUtil.isNotBlank(portMappingDO.getSubdomain())) { - ProxyUtil.setSubdomainToServerPort(portMappingDO.getSubdomain(), portMappingDO.getServerPort()); - } + visitorChannelService.addVisitorChannelByProxyMapping(ProxyMapping.build(portMappingDO)); updateMappingPortToSecurityGroupMap(portMappingDO.getServerPort(), req.getSecurityGroupId()); @@ -203,7 +195,6 @@ public class PortMappingService implements LifecycleBean { PortPoolDO portPoolDO = portPoolMapper.findByPort(req.getServerPort()); ParamCheckUtil.checkNotNull(portPoolDO, ExceptionConstant.PORT_NOT_EXIST); ParamCheckUtil.checkExpression(null == portMappingMapper.findByPort(req.getServerPort(), Sets.newHashSet(req.getId())), ExceptionConstant.PORT_CANNOT_REPEAT_MAPPING, req.getServerPort()); - ParamCheckUtil.checkExpression(!portMappingMapper.checkRepeatBySubdomain(req.getSubdomain(), Sets.newHashSet(req.getId())), ExceptionConstant.PORT_MAPPING_SUBDONAME_CONNOT_REPEAT); // 查询原端口映射 PortMappingDO oldPortMappingDO = portMappingMapper.findById(req.getId()); @@ -213,7 +204,6 @@ public class PortMappingService implements LifecycleBean { portMappingMapper.update(null, new LambdaUpdateWrapper() .eq(PortMappingDO::getId, req.getId()) .set(PortMappingDO::getProtocal, req.getProtocal()) - .set(PortMappingDO::getSubdomain, req.getSubdomain()) .set(PortMappingDO::getServerPort, req.getServerPort()) .set(PortMappingDO::getClientIp, req.getClientIp()) .set(PortMappingDO::getClientPort, req.getClientPort()) @@ -228,15 +218,7 @@ public class PortMappingService implements LifecycleBean { // 更新VisitorChannel PortMappingDO portMappingDO = portMappingMapper.findById(req.getId()); - visitorChannelService.updateVisitorChannelByPortMapping(oldPortMappingDO, portMappingDO); - // 删除老的域名映射 - if (NetworkProtocolEnum.isHttp(oldPortMappingDO.getProtocal()) && StrUtil.isNotBlank(oldPortMappingDO.getSubdomain())) { - ProxyUtil.removeSubdomainToServerPort(oldPortMappingDO.getSubdomain()); - } - // 更新域名映射 - if (NetworkProtocolEnum.isHttp(portMappingDO.getProtocal()) && StrUtil.isNotBlank(proxyConfig.getServer().getTcp().getDomainName()) && StrUtil.isNotBlank(portMappingDO.getSubdomain())) { - ProxyUtil.setSubdomainToServerPort(portMappingDO.getSubdomain(), portMappingDO.getServerPort()); - } + visitorChannelService.updateVisitorChannelByProxyMapping(ProxyMapping.build(oldPortMappingDO), ProxyMapping.build(portMappingDO)); updateMappingPortToSecurityGroupMap(portMappingDO.getServerPort(), req.getSecurityGroupId()); @@ -294,9 +276,9 @@ public class PortMappingService implements LifecycleBean { // 更新VisitorChannel portMappingDO.setEnable(req.getEnable()); if (EnableStatusEnum.ENABLE == EnableStatusEnum.of(req.getEnable())) { - visitorChannelService.addVisitorChannelByPortMapping(portMappingDO); + visitorChannelService.addVisitorChannelByProxyMapping(ProxyMapping.build(portMappingDO)); } else { - visitorChannelService.removeVisitorChannelByPortMapping(portMappingDO); + visitorChannelService.removeVisitorChannelByProxyMapping(ProxyMapping.build(portMappingDO)); } return new PortMappingUpdateEnableStatusRes(); @@ -315,11 +297,8 @@ public class PortMappingService implements LifecycleBean { portMappingMapper.deleteById(id); // 更新VisitorChannel - visitorChannelService.removeVisitorChannelByPortMapping(portMappingDO); + visitorChannelService.removeVisitorChannelByProxyMapping(ProxyMapping.build(portMappingDO)); // 更新域名映射 - if (NetworkProtocolEnum.isHttp(portMappingDO.getProtocal()) && StrUtil.isNotBlank(portMappingDO.getSubdomain())) { - ProxyUtil.removeSubdomainToServerPort(portMappingDO.getSubdomain()); - } updateMappingPortToSecurityGroupMap(portMappingDO.getServerPort(), null); @@ -392,23 +371,6 @@ public class PortMappingService implements LifecycleBean { refreshFlowLimitCache(item.getId(), item.getUpLimitRate(), item.getDownLimitRate()); }); - // 未配置域名,则不需要处理域名映射逻辑 - if (StrUtil.isBlank(proxyConfig.getServer().getTcp().getDomainName())) { - return; - } - List portMappingDOList = allMappingDOList.stream() - .filter(item -> NetworkProtocolEnum.HTTP.getDesc().equals(item.getProtocal()) && item.getSubdomain() != null) - .collect(Collectors.toList()); - if (CollectionUtil.isEmpty(portMappingDOList)) { - return; - } - portMappingDOList.forEach(item -> { - if (StrUtil.isBlank(item.getSubdomain())) { - return; - } - ProxyUtil.setSubdomainToServerPort(item.getSubdomain(), item.getServerPort()); - - }); } /** diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/PortPoolService.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/PortPoolService.java index e651daca..b7dd240c 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/PortPoolService.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/PortPoolService.java @@ -130,6 +130,7 @@ public class PortPoolService { log.warn("bulk add port err:{}",e.getMessage()); } } + }else{ throw ServiceException.create(PORT_RANGE_FAIL); } diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/VisitorChannelService.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/VisitorChannelService.java index 81ebc2ab..00c67498 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/VisitorChannelService.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/service/VisitorChannelService.java @@ -59,17 +59,18 @@ public class VisitorChannelService { private PortPoolMapper portPoolMapper; /** - * 初始化 + * 初始化 - 域名id/端口号,客户端通道绑定初始化 * @param licenseId */ public void initVisitorChannel(Integer licenseId, Channel cmdChannel) { - List portMappingList = portMappingMapper.findEnableListByLicenseId(licenseId); +// List portMappingList = portMappingMapper.findEnableListByLicenseId(licenseId); + List proxyMappingList = licenseMapper.findEnableProxyMappingListByLicenseId(licenseId); // 没有端口映射仍然保持连接 - ProxyUtil.initProxyInfo(licenseId, ProxyMapping.buildList(portMappingList)); + ProxyUtil.initProxyInfo(licenseId, proxyMappingList); //ProxyMapping.buildList(portMappingList)); - ProxyUtil.addCmdChannel(licenseId, cmdChannel, portMappingList.stream().map(PortMappingDO::getServerPort).collect(Collectors.toSet())); + ProxyUtil.addCmdChannel(licenseId, cmdChannel, proxyMappingList.stream().map(ProxyMapping::getServerPort).collect(Collectors.toSet())); - startUserPortServer(ProxyUtil.getAttachInfo(cmdChannel), portMappingList); + startUserPortServer(ProxyUtil.getAttachInfo(cmdChannel), proxyMappingList); // portMappingList } /** @@ -89,9 +90,9 @@ public class VisitorChannelService { EnableStatusEnum enableStatusEnum = EnableStatusEnum.of(enable); for (PortMappingDO portMappingDO : portMappingDOList) { if (EnableStatusEnum.DISABLE == enableStatusEnum) { - removeVisitorChannelByPortMapping(portMappingDO); + removeVisitorChannelByProxyMapping(ProxyMapping.build(portMappingDO)); } else if (EnableStatusEnum.ENABLE == EnableStatusEnum.of(portMappingDO.getEnable())) { - addVisitorChannelByPortMapping(portMappingDO); + addVisitorChannelByProxyMapping(ProxyMapping.build(portMappingDO)); } } } @@ -130,82 +131,82 @@ public class VisitorChannelService { return; } EnableStatusEnum enableStatusEnum = EnableStatusEnum.of(enable); - List portMappingDOList = portMappingMapper.findListByLicenseId(licenseId); - if (!CollectionUtil.isEmpty(portMappingDOList)) { - for (PortMappingDO portMappingDO : portMappingDOList) { - if (EnableStatusEnum.DISABLE == enableStatusEnum) { - removeVisitorChannelByPortMapping(portMappingDO); - } else if (EnableStatusEnum.ENABLE == EnableStatusEnum.of(portMappingDO.getEnable())) { - addVisitorChannelByPortMapping(portMappingDO); - } + if (EnableStatusEnum.DISABLE == enableStatusEnum) { // 禁用删除,关闭所有链接及配置 + List allProxyMappingList = licenseMapper.findAllProxyMappingListByLicenseId(licenseId); + for (ProxyMapping proxy : allProxyMappingList) { + removeVisitorChannelByProxyMapping(proxy); + } + } else { // if (EnableStatusEnum.ENABLE == enableStatusEnum) 如果实启用,则开启所有 + List enableProxyMappingList = licenseMapper.findEnableProxyMappingListByLicenseId(licenseId); + for (ProxyMapping eproxy : enableProxyMappingList) { + addVisitorChannelByProxyMapping(eproxy); } } } - /** * 更新 * 触发时机:修改端口映射 - * @param oldPortMappingDO - * @param newPortMappingDO + * @param oldProxyMapping + * @param newProxyMapping */ - public void updateVisitorChannelByPortMapping(PortMappingDO oldPortMappingDO, PortMappingDO newPortMappingDO) { - if (null == oldPortMappingDO || null == newPortMappingDO) { + public void updateVisitorChannelByProxyMapping(ProxyMapping oldProxyMapping, ProxyMapping newProxyMapping) { + if (null == oldProxyMapping || null == newProxyMapping) { return; } - removeVisitorChannelByPortMapping(oldPortMappingDO); - addVisitorChannelByPortMapping(newPortMappingDO); + removeVisitorChannelByProxyMapping(oldProxyMapping); + addVisitorChannelByProxyMapping(newProxyMapping); } /** * 新增VisitorChannel * 触发时机:新增端口映射、启用端口映射 - * @param portMappingDO + * @param proxyMapping */ - public void addVisitorChannelByPortMapping(PortMappingDO portMappingDO) { - if (null == portMappingDO) { + public void addVisitorChannelByProxyMapping(ProxyMapping proxyMapping) { + if (null == proxyMapping) { return; } - Channel cmdChannel = ProxyUtil.getCmdChannelByLicenseId(portMappingDO.getLicenseId()); + Channel cmdChannel = ProxyUtil.getCmdChannelByLicenseId(proxyMapping.getLicenseId()); if (null == cmdChannel) { // 如果不存在有效的cmdChannel,则无需更新VisitorChannel return; } // 判断端口映射是否启用 - if (EnableStatusEnum.DISABLE != EnableStatusEnum.of(portMappingDO.getEnable())) { - LicenseDO licenseDO = licenseMapper.findById(portMappingDO.getLicenseId()); +// if (EnableStatusEnum.DISABLE != EnableStatusEnum.of(portMappingDO.getEnable())) { + LicenseDO licenseDO = licenseMapper.findById(proxyMapping.getLicenseId()); // 判断license是否启用 if (null != licenseDO && EnableStatusEnum.ENABLE == EnableStatusEnum.of(licenseDO.getEnable())) { UserDO userDO = userMapper.findById(licenseDO.getUserId()); // 判断用户是否启用 if (null != userDO && EnableStatusEnum.ENABLE == EnableStatusEnum.of(userDO.getEnable())) { - PortPoolDO portPoolDO = portPoolMapper.findByPort(portMappingDO.getServerPort()); - // 判断端口池是否启用 - if (null != portPoolDO && EnableStatusEnum.ENABLE == EnableStatusEnum.of(portPoolDO.getEnable())) { + PortPoolDO portPoolDO = portPoolMapper.findByPort(proxyMapping.getServerPort()); + // 端口池大于65535 为域名解析,小于65535为端口映射,端口映射要判断端口池是否启用 + if (proxyMapping.getServerPort() > 65535 || (null != portPoolDO && EnableStatusEnum.ENABLE == EnableStatusEnum.of(portPoolDO.getEnable()))) { // 未删除且未禁用,则开启代理 - ProxyUtil.addProxyInfo(portMappingDO.getLicenseId(), ProxyMapping.build(portMappingDO)); - ProxyUtil.addCmdChannel(portMappingDO.getLicenseId(), cmdChannel, Sets.newHashSet(portMappingDO.getServerPort())); - startUserPortServer(ProxyUtil.getAttachInfo(cmdChannel), Lists.newArrayList(portMappingDO)); + ProxyUtil.addProxyInfo(proxyMapping.getLicenseId(), proxyMapping); + ProxyUtil.addCmdChannel(proxyMapping.getLicenseId(), cmdChannel, Sets.newHashSet(proxyMapping.getServerPort())); + startUserPortServer(ProxyUtil.getAttachInfo(cmdChannel), Lists.newArrayList(proxyMapping)); } } } - } +// } } /** * 删除VisitorChannel * 触发时机:删除端口映射、禁用端口映射 - * @param portMappingDO + * @param proxyMapping */ - public void removeVisitorChannelByPortMapping(PortMappingDO portMappingDO) { - if (null == portMappingDO) { + public void removeVisitorChannelByProxyMapping(ProxyMapping proxyMapping) { + if (null == proxyMapping) { return; } - Channel cmdChannel = ProxyUtil.getCmdChannelByLicenseId(portMappingDO.getLicenseId()); + Channel cmdChannel = ProxyUtil.getCmdChannelByLicenseId(proxyMapping.getLicenseId()); if (null == cmdChannel) { // 如果不存在有效的cmdChannel,则无需更新VisitorChannel return; } - Channel visitorChannel = ProxyUtil.getVisitorChannelByServerPort(portMappingDO.getServerPort()); + Channel visitorChannel = ProxyUtil.getVisitorChannelByServerPort(proxyMapping.getServerPort()); if (null != visitorChannel) { Channel proxyChannel = visitorChannel.attr(Constants.NEXT_CHANNEL).get(); if (null != proxyChannel) { @@ -214,29 +215,28 @@ public class VisitorChannelService { // TODO 此处如果时UDP的visitorChannel,则不能close,后续重构考虑 // visitorChannel.close(); } - ProxyUtil.removeProxyInfo(portMappingDO.getServerPort()); + ProxyUtil.removeProxyInfo(proxyMapping.getServerPort()); } - private void startUserPortServer(CmdChannelAttachInfo cmdChannelAttachInfo, List portMappingList) { - if (CollectionUtil.isEmpty(portMappingList)) { + private void startUserPortServer(CmdChannelAttachInfo cmdChannelAttachInfo, List proxyMappingList) { + if (CollectionUtil.isEmpty(proxyMappingList)) { return; } - - for (PortMappingDO portMapping : portMappingList) { - if (EnableStatusEnum.DISABLE.getStatus().equals(portMapping.getEnable())) { - // 端口映射被禁用了,忽略 TODO 映射没被禁用,但端口被禁用了也需要处理 - continue; - } + for (ProxyMapping proxyMapping : proxyMappingList) { +// if (EnableStatusEnum.DISABLE.getStatus().equals(proxyMapping.getEnable())) { +// // 端口映射被禁用了,忽略 TODO 映射没被禁用,但端口被禁用了也需要处理 修改方案 20240306查询时就处理了【端口禁用】和【端口映射禁用】的情况,待验证 +// continue; +// } try { - proxyMutualService.bindServerPort(cmdChannelAttachInfo, portMapping.getServerPort()); + proxyMutualService.bindServerPort(cmdChannelAttachInfo, proxyMapping.getServerPort()); - NetworkProtocolEnum networkProtocolEnum = NetworkProtocolEnum.of(portMapping.getProtocal()); + NetworkProtocolEnum networkProtocolEnum = NetworkProtocolEnum.of(proxyMapping.getProtocal()); if (networkProtocolEnum == NetworkProtocolEnum.UDP) { - udpServerBootstrap.bind(portMapping.getServerPort()).get(); - log.info("bind UDP user port: {}", portMapping.getServerPort()); - } else { - tcpServerBootstrap.bind(portMapping.getServerPort()).get(); - log.info("bind TCP user port: {}", portMapping.getServerPort()); + udpServerBootstrap.bind(proxyMapping.getServerPort()).get(); + log.info("bind UDP user port: {}", proxyMapping.getServerPort()); + } else if (proxyMapping.getServerPort() <= 65535){// 大于65535 的端口号是域名解析无需绑定服务端端口号 + tcpServerBootstrap.bind(proxyMapping.getServerPort()).get(); + log.info("bind TCP ServerPort: {}", proxyMapping.getServerPort()); } } catch (Exception ex) { // BindException表示该端口已经绑定过 diff --git a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/util/ProxyUtil.java b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/util/ProxyUtil.java index 14ecd297..e4c9460e 100644 --- a/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/util/ProxyUtil.java +++ b/neutrino-proxy-server/src/main/java/org/dromara/neutrinoproxy/server/util/ProxyUtil.java @@ -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.*; @@ -60,15 +60,19 @@ public class ProxyUtil { * 代理 - connect附加映射 */ private static Map proxyConnectAttachmentMap = new HashMap<>(); - /** - * 子域名 - 服务端端口映射 - */ - private static Map subdomainToServerPort = new HashMap<>(); + + + /** + * 域名 解析 映射 + */ + public static final Map domainMapingMap = new HashMap<>(); + /** * licenseId - 客户端Id映射 */ private static Map licenseIdToClientIdMap = new HashMap<>(); - + @Inject + private DomainMappingService domainMappingService; /** * 初始化代理信息 * @param licenseId licenseId @@ -79,6 +83,7 @@ public class ProxyUtil { addProxyInfo(licenseId, proxyMappingList); } + public static void addProxyInfo(Integer licenseId, List proxyMappingList) { if (!CollectionUtil.isEmpty(proxyMappingList)) { for (ProxyMapping proxyMapping : proxyMappingList) { @@ -338,31 +343,6 @@ public class ProxyUtil { proxyConnectAttachmentMap.remove(visitorId); } - /** - * 设置子域名到服务端端口的映射 - * @param subdomain - * @param serverPort - */ - public static void setSubdomainToServerPort(String subdomain, Integer serverPort) { - subdomainToServerPort.put(subdomain, serverPort); - } - - /** - * 删除子域名到服务端端口的映射 - * @param subdomain - */ - public static void removeSubdomainToServerPort(String subdomain) { - subdomainToServerPort.remove(subdomain); - } - - /** - * 根据子域名获取外网端口 - * @param subdomain - * @return - */ - public static Integer getServerPortBySubdomain(String subdomain) { - return subdomainToServerPort.get(subdomain); - } /** * 关闭http响应channel diff --git a/neutrino-proxy-server/src/main/resources/app.yml b/neutrino-proxy-server/src/main/resources/app.yml index c62aa9d0..53f75922 100644 --- a/neutrino-proxy-server/src/main/resources/app.yml +++ b/neutrino-proxy-server/src/main/resources/app.yml @@ -55,14 +55,14 @@ neutrino: boss-thread-count: 5 work-thread-count: 20 # http代理端口,默认80 - http-proxy-port: ${HTTP_PROXY_PORT:80} + http-proxy-port: ${HTTP_PR0OXY_PORT:80} # https代理端口,默认443 (需要配置域名、证书) https-proxy-port: ${HTTPS_PROXY_PORT:443} # 如果不配置,则不支持域名映射 - domain-name: ${DOMAIN_NAME:} + domain-name: ${DOMAIN_NAME:server.com} # https证书配置 - key-store-password: ${HTTPS_STORE_PASS:} - jks-path: ${HTTPS_JKS_PATH:} + key-store-password: ${HTTPS_STORE_PASS:123456} + jks-path: ${HTTPS_JKS_PATH:classpath:/test.jks} # 是否开启代理服务报文日志(日志级别为debug时开启才有效) transfer-log-enable: ${SERVER_LOG:false} udp: diff --git a/neutrino-proxy-server/src/main/resources/mapper/DomainMappingMapper.xml b/neutrino-proxy-server/src/main/resources/mapper/DomainMappingMapper.xml new file mode 100644 index 00000000..912fb5cb --- /dev/null +++ b/neutrino-proxy-server/src/main/resources/mapper/DomainMappingMapper.xml @@ -0,0 +1,34 @@ + + + + + + \ No newline at end of file diff --git a/neutrino-proxy-server/src/main/resources/mapper/LicenseMapper.xml b/neutrino-proxy-server/src/main/resources/mapper/LicenseMapper.xml new file mode 100644 index 00000000..19d5b3eb --- /dev/null +++ b/neutrino-proxy-server/src/main/resources/mapper/LicenseMapper.xml @@ -0,0 +1,28 @@ + + + + + + + + diff --git a/neutrino-proxy-server/src/main/resources/mapper/ReportMapper.xml b/neutrino-proxy-server/src/main/resources/mapper/ReportMapper.xml index 8c4aa5c9..d8eb17aa 100644 --- a/neutrino-proxy-server/src/main/resources/mapper/ReportMapper.xml +++ b/neutrino-proxy-server/src/main/resources/mapper/ReportMapper.xml @@ -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 <= #{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 <= #{curDate} diff --git a/neutrino-proxy-server/src/main/resources/sql/h2/init-structure.sql b/neutrino-proxy-server/src/main/resources/sql/h2/init-structure.sql index bfeaeda7..4ad4dda8 100644 --- a/neutrino-proxy-server/src/main/resources/sql/h2/init-structure.sql +++ b/neutrino-proxy-server/src/main/resources/sql/h2/init-structure.sql @@ -97,7 +97,6 @@ CREATE TABLE IF NOT EXISTS `port_mapping` ( `id` INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, `license_id` INTEGER(20) NOT NULL, `protocal` VARCHAR(10) NOT NULL DEFAULT 'TCP', - `subdomain` VARCHAR(50) DEFAULT NULL, `server_port` INTEGER NOT NULL, `client_ip` VARCHAR(20) NOT NULL, `client_port` INTEGER NOT NULL, @@ -229,3 +228,21 @@ CREATE INDEX IF NOT EXISTS I_flow_report_month_create_time ON flow_report_month( CREATE INDEX IF NOT EXISTS I_flow_report_month_date ON flow_report_month(`date`); CREATE INDEX IF NOT EXISTS I_flow_report_month_user_id ON flow_report_month(`user_id`); CREATE INDEX IF NOT EXISTS I_flow_report_month_license_id ON flow_report_month(`license_id`); + +# 域名 映射表 AUTO_INCREMENT 设置65550 避开端口号0-65535,减少域名解析代码修改 +CREATE TABLE IF NOT EXISTS `domain_mapping` ( + `id` INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, + `license_id` INTEGER(20) NOT NULL, + `protocal` VARCHAR(10) NOT NULL DEFAULT 'HTTP', + `domain` VARCHAR(50) DEFAULT NULL, + `target_path` VARCHAR(50) NOT NULL, + `up_limit_rate` VARCHAR(20) DEFAULT NULL, + `down_limit_rate` VARCHAR(20) DEFAULT NULL, + `description` VARCHAR(100) DEFAULT NULL, + `request_header` INTEGER(20) NOT NULL DEFAULT 0, + `enable` INTEGER(2) NOT NULL, + `security_group_id` INTEGER(20) NOT NULL DEFAULT 0, + `create_time` TIMESTAMP NOT NULL, + `update_time` TIMESTAMP NOT NULL +) AUTO_INCREMENT = 65550; +CREATE UNIQUE INDEX IF NOT EXISTS I_domain_mapping_domain ON domain_mapping (`domain` ASC); \ No newline at end of file diff --git a/neutrino-proxy-server/src/main/resources/sql/h2/license.data.sql b/neutrino-proxy-server/src/main/resources/sql/h2/license.data.sql index f7e239a2..529ae9d5 100644 --- a/neutrino-proxy-server/src/main/resources/sql/h2/license.data.sql +++ b/neutrino-proxy-server/src/main/resources/sql/h2/license.data.sql @@ -1,3 +1,3 @@ #license INSERT INTO license(`id`, `name`, `key`, `user_id`, `is_online`, `enable`, `create_time`, `update_time`) VALUES -(1, '我的mac', 'b0a907332b474b25897c4dcb31fc7eb6', 1, 2, 1, now(), now()); +(1, '测试客户端', 'b0a907332b474b25897c4dcb31fc7eb6', 1, 1, 1, now(), now()); diff --git a/neutrino-proxy-server/src/main/resources/sql/h2/port_mapping.data.sql b/neutrino-proxy-server/src/main/resources/sql/h2/port_mapping.data.sql index 403143a1..461da66d 100644 --- a/neutrino-proxy-server/src/main/resources/sql/h2/port_mapping.data.sql +++ b/neutrino-proxy-server/src/main/resources/sql/h2/port_mapping.data.sql @@ -1,7 +1,7 @@ #port_mapping -INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `subdomain`,`client_ip`, `client_port`, `is_online`, `enable`,`description`,`create_time`, `update_time`) VALUES -(1, 1, 9101, 'HTTP', 'test1', '127.0.0.1', 8080, 2, 1,'test1', now(), now()); -INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `subdomain`, `client_ip`, `client_port`, `is_online`, `enable`,`description`, `create_time`, `update_time`) VALUES -(2, 1, 9102, 'TCP', '', '127.0.0.1', 3306, 2, 1,'test2', now(), now()); -INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `subdomain`, `client_ip`, `client_port`, `is_online`, `enable`,`description`, `create_time`, `update_time`) VALUES -(3, 1, 9103, 'HTTP', 'test2', '127.0.0.1', 8081, 2, 1,'test3', now(), now()); \ No newline at end of file +INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `client_ip`, `client_port`, `is_online`, `enable`,`description`,`create_time`, `update_time`) VALUES +(1, 1, 9101, 'HTTP', '127.0.0.1', 8080, 2, 1,'test1', now(), now()); +INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `client_ip`, `client_port`, `is_online`, `enable`,`description`, `create_time`, `update_time`) VALUES +(2, 1, 9102, 'TCP', '127.0.0.1', 3306, 2, 1,'test2', now(), now()); +INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `client_ip`, `client_port`, `is_online`, `enable`,`description`, `create_time`, `update_time`) VALUES +(3, 1, 9103, 'HTTP', '127.0.0.1', 8081, 2, 1,'test3', now(), now()); \ No newline at end of file diff --git a/neutrino-proxy-server/src/main/resources/sql/h2/port_pool.data.sql b/neutrino-proxy-server/src/main/resources/sql/h2/port_pool.data.sql index 056dc93f..136349f3 100644 --- a/neutrino-proxy-server/src/main/resources/sql/h2/port_pool.data.sql +++ b/neutrino-proxy-server/src/main/resources/sql/h2/port_pool.data.sql @@ -9,33 +9,3 @@ INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update (4, 1, 9104, 1, now(), now()); INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES (5, 1, 9105, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(6, 1, 9106, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(7, 1, 9107, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(8, 1, 9108, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(9, 1, 9109, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(10, 1, 9110, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(11, 1, 9111, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(12, 1, 9112, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(13, 1, 9113, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(14, 1, 9114, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(15, 1, 9115, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(16, 1, 9116, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(17, 1, 9117, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(18, 1, 9118, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(19, 1, 9119, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(20, 1, 9120, 1, now(), now()); diff --git a/neutrino-proxy-server/src/main/resources/sql/h2/update/UPDATE-20230318.SQL b/neutrino-proxy-server/src/main/resources/sql/h2/update/UPDATE-20230318.SQL deleted file mode 100644 index 257f83e4..00000000 --- a/neutrino-proxy-server/src/main/resources/sql/h2/update/UPDATE-20230318.SQL +++ /dev/null @@ -1,12 +0,0 @@ -ALTER TABLE port_pool ADD group_id INTEGER NOT NULL DEFAULT 1; - -#端口分组 -CREATE TABLE IF NOT EXISTS `port_group` ( - `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - `name` VARCHAR(255) NOT NULL, - `possessor_type` INTEGER NOT NULL DEFAULT '0', - `possessor_id` INTEGER NOT NULL DEFAULT '-1', - `enable` INTEGER NOT NULL, - `create_time` datetime(3) NOT NULL, - `update_time` datetime(3) NOT NULL -); \ No newline at end of file diff --git a/neutrino-proxy-server/src/main/resources/sql/h2/update/UPDATE-20230402.SQL b/neutrino-proxy-server/src/main/resources/sql/h2/update/UPDATE-20230402.SQL deleted file mode 100644 index c5e91f3c..00000000 --- a/neutrino-proxy-server/src/main/resources/sql/h2/update/UPDATE-20230402.SQL +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE port_mapping ADD `protocal` varchar(10) NOT NULL DEFAULT 'TCP'; -ALTER TABLE port_mapping ADD `subdomain` varchar(50) DEFAULT NULL; -ALTER TABLE port_mapping ADD `description` varchar(100); diff --git a/neutrino-proxy-server/src/main/resources/sql/h2/update/UPDATE-20230922.SQL b/neutrino-proxy-server/src/main/resources/sql/h2/update/UPDATE-20230922.SQL deleted file mode 100644 index 7a2eeb6d..00000000 --- a/neutrino-proxy-server/src/main/resources/sql/h2/update/UPDATE-20230922.SQL +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE port_mapping ADD `proxy_responses` INTEGER(20) NOT NULL DEFAULT 0; -ALTER TABLE port_mapping ADD `proxy_timeout_ms` INTEGER(20) NOT NULL DEFAULT 0; diff --git a/neutrino-proxy-server/src/main/resources/sql/h2/update/UPDATE-20231215.SQL b/neutrino-proxy-server/src/main/resources/sql/h2/update/UPDATE-20231215.SQL deleted file mode 100644 index aaaa137b..00000000 --- a/neutrino-proxy-server/src/main/resources/sql/h2/update/UPDATE-20231215.SQL +++ /dev/null @@ -1,38 +0,0 @@ -#安全组 -CREATE TABLE IF NOT EXISTS `security_group` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `name` VARCHAR(20) NOT NULL, - `description` VARCHAR(255), - `user_id` INTEGER NOT NULL, - `enable` INTEGER NOT NULL, - `default_pass_type` INTEGER NOT NULL, - `create_time` TIMESTAMP NOT NULL, - `update_time` TIMESTAMP NOT NULL, - PRIMARY KEY (`id`) -); - -#安全组规则 -CREATE TABLE IF NOT EXISTS `security_rule` ( - `id` INTEGER NOT NULL AUTO_INCREMENT, - `group_id` INTEGER NOT NULL, - `name` VARCHAR(20) NOT NULL, - `description` VARCHAR(255) NOT NULL, - `rule` text NOT NULL, - `pass_type` INTEGER NOT NULL, - `priority` INTEGER NOT NULL, - `user_id` INTEGER NOT NULL, - `enable` INTEGER NOT NULL, - `create_time` TIMESTAMP NOT NULL, - `update_time` TIMESTAMP NOT NULL, - PRIMARY KEY (`id`) -); -CREATE INDEX IF NOT EXISTS I_security_rule_group_id ON security_rule(group_id); - -# port_mapping表增加字段 -ALTER TABLE `port_mapping` ADD COLUMN `security_group_id` INTEGER DEFAULT 0; -ALTER TABLE `port_mapping` ADD COLUMN `up_limit_rate` varchar(20) DEFAULT NULL; -ALTER TABLE `port_mapping` ADD COLUMN `down_limit_rate` varchar(20) DEFAULT NULL; - -# license表增加字段 -ALTER TABLE `license` ADD COLUMN `up_limit_rate` varchar(20) DEFAULT NULL; -ALTER TABLE `license` ADD COLUMN `down_limit_rate` varchar(20) DEFAULT NULL; diff --git a/neutrino-proxy-server/src/main/resources/sql/mariadb/init-structure.sql b/neutrino-proxy-server/src/main/resources/sql/mariadb/init-structure.sql index 76300f97..db756fbf 100644 --- a/neutrino-proxy-server/src/main/resources/sql/mariadb/init-structure.sql +++ b/neutrino-proxy-server/src/main/resources/sql/mariadb/init-structure.sql @@ -102,7 +102,6 @@ CREATE TABLE IF NOT EXISTS `port_mapping` ( `id` int NOT NULL AUTO_INCREMENT COMMENT '主键ID', `license_id` int NOT NULL COMMENT 'licenseID', `protocal` varchar(10) NOT NULL DEFAULT 'TCP' COMMENT '协议', - `subdomain` varchar(50) DEFAULT NULL COMMENT '子域名(仅HTTP时有效)', `server_port` int NOT NULL COMMENT '服务端端口', `client_ip` varchar(20) NOT NULL COMMENT '客户端IP', `client_port` int NOT NULL COMMENT '客户端端口', @@ -242,3 +241,22 @@ CREATE TABLE IF NOT EXISTS `flow_report_month` ( KEY `I_flow_report_month_user_id` (`user_id`), KEY `I_flow_report_month_license_id` (`license_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + + +# 域名 映射表 AUTO_INCREMENT 设置65550 避开端口号0-65535,减少域名解析代码修改 +CREATE TABLE IF NOT EXISTS `domain_mapping` ( + `id` INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, + `license_id` INTEGER(20) NOT NULL, + `protocal` VARCHAR(10) NOT NULL DEFAULT 'HTTP', + `domain` VARCHAR(50) DEFAULT NULL, + `target_path` VARCHAR(50) NOT NULL, + `up_limit_rate` VARCHAR(20) DEFAULT NULL, + `down_limit_rate` VARCHAR(20) DEFAULT NULL, + `description` VARCHAR(100) DEFAULT NULL, + `request_header` INTEGER(20) NOT NULL DEFAULT 0, + `enable` INTEGER(2) NOT NULL, + `security_group_id` INTEGER(20) NOT NULL DEFAULT 0, + `create_time` TIMESTAMP NOT NULL, + `update_time` TIMESTAMP NOT NULL +) AUTO_INCREMENT = 65550; +CREATE UNIQUE INDEX IF NOT EXISTS I_domain_mapping_domain ON domain_mapping (`domain` ASC); \ No newline at end of file diff --git a/neutrino-proxy-server/src/main/resources/sql/mariadb/license.data.sql b/neutrino-proxy-server/src/main/resources/sql/mariadb/license.data.sql index f7e239a2..990d6806 100644 --- a/neutrino-proxy-server/src/main/resources/sql/mariadb/license.data.sql +++ b/neutrino-proxy-server/src/main/resources/sql/mariadb/license.data.sql @@ -1,3 +1,3 @@ #license INSERT INTO license(`id`, `name`, `key`, `user_id`, `is_online`, `enable`, `create_time`, `update_time`) VALUES -(1, '我的mac', 'b0a907332b474b25897c4dcb31fc7eb6', 1, 2, 1, now(), now()); +(1, '服务端(不可编辑删除,可禁用)', 'b0a907332b474b25897c4dcb31fc7eb6', 1, 1, 1, now(), now()); diff --git a/neutrino-proxy-server/src/main/resources/sql/mariadb/port_mapping.data.sql b/neutrino-proxy-server/src/main/resources/sql/mariadb/port_mapping.data.sql index 9063ecea..461da66d 100644 --- a/neutrino-proxy-server/src/main/resources/sql/mariadb/port_mapping.data.sql +++ b/neutrino-proxy-server/src/main/resources/sql/mariadb/port_mapping.data.sql @@ -1,7 +1,7 @@ #port_mapping -INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `subdomain`, `client_ip`, `client_port`, `is_online`, `enable`, `create_time`, `update_time`) VALUES -(1, 1, 9101, 'HTTP', 'test1', '127.0.0.1', 8080, 2, 1, now(), now()); -INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `subdomain`, `client_ip`, `client_port`, `is_online`, `enable`, `create_time`, `update_time`) VALUES -(2, 1, 9102, 'TCP', '', '127.0.0.1', 3306, 2, 1, now(), now()); -INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `subdomain`, `client_ip`, `client_port`, `is_online`, `enable`, `create_time`, `update_time`) VALUES -(3, 1, 9103, 'HTTP', 'test2', '127.0.0.1', 8081, 2, 1, now(), now()); +INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `client_ip`, `client_port`, `is_online`, `enable`,`description`,`create_time`, `update_time`) VALUES +(1, 1, 9101, 'HTTP', '127.0.0.1', 8080, 2, 1,'test1', now(), now()); +INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `client_ip`, `client_port`, `is_online`, `enable`,`description`, `create_time`, `update_time`) VALUES +(2, 1, 9102, 'TCP', '127.0.0.1', 3306, 2, 1,'test2', now(), now()); +INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `client_ip`, `client_port`, `is_online`, `enable`,`description`, `create_time`, `update_time`) VALUES +(3, 1, 9103, 'HTTP', '127.0.0.1', 8081, 2, 1,'test3', now(), now()); \ No newline at end of file diff --git a/neutrino-proxy-server/src/main/resources/sql/mariadb/port_pool.data.sql b/neutrino-proxy-server/src/main/resources/sql/mariadb/port_pool.data.sql index e4288b13..136349f3 100644 --- a/neutrino-proxy-server/src/main/resources/sql/mariadb/port_pool.data.sql +++ b/neutrino-proxy-server/src/main/resources/sql/mariadb/port_pool.data.sql @@ -9,33 +9,3 @@ INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update (4, 1, 9104, 1, now(), now()); INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES (5, 1, 9105, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(6, 1, 9106, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(7, 1, 9107, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(8, 1, 9108, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(9, 1, 9109, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(10, 1, 9110, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(11, 1, 9111, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(12, 1, 9112, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(13, 1, 9113, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(14, 1, 9114, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(15, 1, 9115, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(16, 1, 9116, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(17, 1, 9117, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(18, 1, 9118, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(19, 1, 9119, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(20, 1, 9120, 1, now(), now()); diff --git a/neutrino-proxy-server/src/main/resources/sql/mysql/init-structure.sql b/neutrino-proxy-server/src/main/resources/sql/mysql/init-structure.sql index d61fb9ac..293f296c 100644 --- a/neutrino-proxy-server/src/main/resources/sql/mysql/init-structure.sql +++ b/neutrino-proxy-server/src/main/resources/sql/mysql/init-structure.sql @@ -102,7 +102,6 @@ CREATE TABLE IF NOT EXISTS `port_mapping` ( `id` int NOT NULL AUTO_INCREMENT COMMENT '主键ID', `license_id` int NOT NULL COMMENT 'licenseID', `protocal` varchar(10) NOT NULL DEFAULT 'TCP' COMMENT '协议', - `subdomain` varchar(50) DEFAULT NULL COMMENT '子域名(仅HTTP时有效)', `server_port` int NOT NULL COMMENT '服务端端口', `client_ip` varchar(20) NOT NULL COMMENT '客户端IP', `client_port` int NOT NULL COMMENT '客户端端口', @@ -243,3 +242,20 @@ CREATE TABLE IF NOT EXISTS `flow_report_month` ( KEY `I_flow_report_month_license_id` (`license_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +# 域名 映射表 AUTO_INCREMENT 设置65550 避开端口号0-65535,减少域名解析代码修改 +CREATE TABLE IF NOT EXISTS `domain_mapping` ( + `id` INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, + `license_id` INTEGER(20) NOT NULL, + `protocal` VARCHAR(10) NOT NULL DEFAULT 'HTTP', + `domain` VARCHAR(50) DEFAULT NULL, + `target_path` VARCHAR(50) NOT NULL, + `up_limit_rate` VARCHAR(20) DEFAULT NULL, + `down_limit_rate` VARCHAR(20) DEFAULT NULL, + `description` VARCHAR(100) DEFAULT NULL, + `request_header` INTEGER(20) NOT NULL DEFAULT 0, + `enable` INTEGER(2) NOT NULL COMMENT '是否启用(1、启用 2、禁用)', + `security_group_id` INTEGER(20) NOT NULL DEFAULT 0, + `create_time` TIMESTAMP NOT NULL, + `update_time` TIMESTAMP NOT NULL +) AUTO_INCREMENT = 65550; +CREATE UNIQUE INDEX IF NOT EXISTS I_domain_mapping_domain ON domain_mapping (`domain` ASC); \ No newline at end of file diff --git a/neutrino-proxy-server/src/main/resources/sql/mysql/license.data.sql b/neutrino-proxy-server/src/main/resources/sql/mysql/license.data.sql index f7e239a2..990d6806 100644 --- a/neutrino-proxy-server/src/main/resources/sql/mysql/license.data.sql +++ b/neutrino-proxy-server/src/main/resources/sql/mysql/license.data.sql @@ -1,3 +1,3 @@ #license INSERT INTO license(`id`, `name`, `key`, `user_id`, `is_online`, `enable`, `create_time`, `update_time`) VALUES -(1, '我的mac', 'b0a907332b474b25897c4dcb31fc7eb6', 1, 2, 1, now(), now()); +(1, '服务端(不可编辑删除,可禁用)', 'b0a907332b474b25897c4dcb31fc7eb6', 1, 1, 1, now(), now()); diff --git a/neutrino-proxy-server/src/main/resources/sql/mysql/port_mapping.data.sql b/neutrino-proxy-server/src/main/resources/sql/mysql/port_mapping.data.sql index 9063ecea..461da66d 100644 --- a/neutrino-proxy-server/src/main/resources/sql/mysql/port_mapping.data.sql +++ b/neutrino-proxy-server/src/main/resources/sql/mysql/port_mapping.data.sql @@ -1,7 +1,7 @@ #port_mapping -INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `subdomain`, `client_ip`, `client_port`, `is_online`, `enable`, `create_time`, `update_time`) VALUES -(1, 1, 9101, 'HTTP', 'test1', '127.0.0.1', 8080, 2, 1, now(), now()); -INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `subdomain`, `client_ip`, `client_port`, `is_online`, `enable`, `create_time`, `update_time`) VALUES -(2, 1, 9102, 'TCP', '', '127.0.0.1', 3306, 2, 1, now(), now()); -INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `subdomain`, `client_ip`, `client_port`, `is_online`, `enable`, `create_time`, `update_time`) VALUES -(3, 1, 9103, 'HTTP', 'test2', '127.0.0.1', 8081, 2, 1, now(), now()); +INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `client_ip`, `client_port`, `is_online`, `enable`,`description`,`create_time`, `update_time`) VALUES +(1, 1, 9101, 'HTTP', '127.0.0.1', 8080, 2, 1,'test1', now(), now()); +INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `client_ip`, `client_port`, `is_online`, `enable`,`description`, `create_time`, `update_time`) VALUES +(2, 1, 9102, 'TCP', '127.0.0.1', 3306, 2, 1,'test2', now(), now()); +INSERT INTO port_mapping(`id`, `license_id`, `server_port`, `protocal`, `client_ip`, `client_port`, `is_online`, `enable`,`description`, `create_time`, `update_time`) VALUES +(3, 1, 9103, 'HTTP', '127.0.0.1', 8081, 2, 1,'test3', now(), now()); \ No newline at end of file diff --git a/neutrino-proxy-server/src/main/resources/sql/mysql/port_pool.data.sql b/neutrino-proxy-server/src/main/resources/sql/mysql/port_pool.data.sql index e4288b13..136349f3 100644 --- a/neutrino-proxy-server/src/main/resources/sql/mysql/port_pool.data.sql +++ b/neutrino-proxy-server/src/main/resources/sql/mysql/port_pool.data.sql @@ -9,33 +9,3 @@ INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update (4, 1, 9104, 1, now(), now()); INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES (5, 1, 9105, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(6, 1, 9106, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(7, 1, 9107, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(8, 1, 9108, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(9, 1, 9109, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(10, 1, 9110, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(11, 1, 9111, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(12, 1, 9112, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(13, 1, 9113, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(14, 1, 9114, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(15, 1, 9115, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(16, 1, 9116, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(17, 1, 9117, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(18, 1, 9118, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(19, 1, 9119, 1, now(), now()); -INSERT INTO port_pool(`id`, `group_id`, `port`, `enable`, `create_time`, `update_time`) VALUES -(20, 1, 9120, 1, now(), now()); diff --git a/neutrino-proxy-server/src/main/resources/sql/mysql/update/UPDATE-20230318.SQL b/neutrino-proxy-server/src/main/resources/sql/mysql/update/UPDATE-20230318.SQL deleted file mode 100644 index a8b1ed01..00000000 --- a/neutrino-proxy-server/src/main/resources/sql/mysql/update/UPDATE-20230318.SQL +++ /dev/null @@ -1,13 +0,0 @@ -ALTER TABLE port_pool ADD group_id INT NOT NULL DEFAULT 1 COMMENT "分组ID"; - -#端口分组 -CREATE TABLE IF NOT EXISTS `port_group` ( - `id` int NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `name` varchar(255) NOT NULL COMMENT '分组名称', - `possessor_type` int NOT NULL DEFAULT '0' COMMENT '所有者类型 (0、全局共享 1、用户所有 2License所有) ', - `possessor_id` int NOT NULL DEFAULT '-1' COMMENT '所有者id(当type为0时 固定为-1、当type为1时为用户id 、当type为2时为licenseid)', - `enable` int NOT NULL COMMENT '是否启用(1、启用 2、禁用)', - `create_time` datetime(3) NOT NULL COMMENT '创建时间', - `update_time` datetime(3) NOT NULL COMMENT '更新时间', - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='端口分组'; \ No newline at end of file diff --git a/neutrino-proxy-server/src/main/resources/sql/mysql/update/UPDATE-20230402.SQL b/neutrino-proxy-server/src/main/resources/sql/mysql/update/UPDATE-20230402.SQL deleted file mode 100644 index 2fcdf2bf..00000000 --- a/neutrino-proxy-server/src/main/resources/sql/mysql/update/UPDATE-20230402.SQL +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE port_mapping ADD `protocal` varchar(10) NOT NULL DEFAULT 'TCP' COMMENT '协议'; -ALTER TABLE port_mapping ADD `subdomain` varchar(50) DEFAULT NULL COMMENT '子域名(仅HTTP时有效)'; -ALTER TABLE port_mapping ADD `description` varchar(100) DEFAULT NULL COMMENT '描述'; \ No newline at end of file diff --git a/neutrino-proxy-server/src/main/resources/sql/mysql/update/UPDATE-20230922.SQL b/neutrino-proxy-server/src/main/resources/sql/mysql/update/UPDATE-20230922.SQL deleted file mode 100644 index 1d036d65..00000000 --- a/neutrino-proxy-server/src/main/resources/sql/mysql/update/UPDATE-20230922.SQL +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE port_mapping ADD `proxy_responses` int NOT NULL DEFAULT 0 COMMENT '代理响应数据包数量'; -ALTER TABLE port_mapping ADD `proxy_timeout_ms` int NOT NULL DEFAULT 0 COMMENT '代理超时毫秒数'; diff --git a/neutrino-proxy-server/src/main/resources/sql/mysql/update/UPDATE-20231126.SQL b/neutrino-proxy-server/src/main/resources/sql/mysql/update/UPDATE-20231126.SQL deleted file mode 100644 index c5c6e33e..00000000 --- a/neutrino-proxy-server/src/main/resources/sql/mysql/update/UPDATE-20231126.SQL +++ /dev/null @@ -1,8 +0,0 @@ -ALTER TABLE `flow_report_minute` MODIFY COLUMN `read_bytes` BIGINT NOT NULL COMMENT '读取流量'; -ALTER TABLE `flow_report_minute` MODIFY COLUMN `write_bytes` BIGINT NOT NULL COMMENT '写入流量'; -ALTER TABLE `flow_report_hour` MODIFY COLUMN `read_bytes` BIGINT NOT NULL COMMENT '读取流量'; -ALTER TABLE `flow_report_hour` MODIFY COLUMN `write_bytes` BIGINT NOT NULL COMMENT '写入流量'; -ALTER TABLE `flow_report_day` MODIFY COLUMN `read_bytes` BIGINT NOT NULL COMMENT '读取流量'; -ALTER TABLE `flow_report_day` MODIFY COLUMN `write_bytes` BIGINT NOT NULL COMMENT '写入流量'; -ALTER TABLE `flow_report_month` MODIFY COLUMN `read_bytes` BIGINT NOT NULL COMMENT '读取流量'; -ALTER TABLE `flow_report_month` MODIFY COLUMN `write_bytes` BIGINT NOT NULL COMMENT '写入流量'; diff --git a/neutrino-proxy-server/src/main/resources/sql/mysql/update/UPDATE-20231215.SQL b/neutrino-proxy-server/src/main/resources/sql/mysql/update/UPDATE-20231215.SQL deleted file mode 100644 index fc454066..00000000 --- a/neutrino-proxy-server/src/main/resources/sql/mysql/update/UPDATE-20231215.SQL +++ /dev/null @@ -1,38 +0,0 @@ -#安全组 -CREATE TABLE IF NOT EXISTS `security_group` ( - `id` int NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `name` varchar(20) NOT NULL COMMENT '安全组名称', - `description` varchar(255) COMMENT '安全组描述', - `user_id` int NOT NULL COMMENT '用户ID', - `enable` int NOT NULL COMMENT '是否启用(1、启用 2、禁用)', - `default_pass_type` int NOT NULL COMMENT '默认放行类型', - `create_time` datetime(3) NOT NULL COMMENT '创建时间', - `update_time` datetime(3) NOT NULL COMMENT '更新时间', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; - -#安全组规则 -CREATE TABLE IF NOT EXISTS `security_rule` ( - `id` int NOT NULL AUTO_INCREMENT COMMENT '主键ID', - `group_id` int NOT NULL COMMENT '关联安全组', - `name` varchar(20) NOT NULL COMMENT '规则名称', - `description` varchar(255) NOT NULL COMMENT '规则描述', - `rule` text NOT NULL COMMENT '规则内容', - `pass_type`int NOT NULL COMMENT '放行类型', - `priority` int(1) NOT NULL COMMENT '优先级', - `user_id` int NOT NULL COMMENT '用户ID', - `enable` int NOT NULL COMMENT '是否启用(1、启用 2、禁用)', - `create_time` datetime(3) NOT NULL COMMENT '创建时间', - `update_time` datetime(3) NOT NULL COMMENT '更新时间', - PRIMARY KEY (`id`), - KEY `I_security_rule_group_id_priority` (`group_id`, `priority`) USING BTREE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; - -# port_mapping表增加字段 -ALTER TABLE `port_mapping` ADD COLUMN `security_group_id` int DEFAULT 0 COMMENT '安全组Id'; -ALTER TABLE `port_mapping` ADD COLUMN `up_limit_rate` varchar(20) DEFAULT NULL COMMENT '上传限速'; -ALTER TABLE `port_mapping` ADD COLUMN `down_limit_rate` varchar(20) DEFAULT NULL COMMENT '下载限速'; - -# license表增加字段 -ALTER TABLE `license` ADD COLUMN `up_limit_rate` varchar(20) DEFAULT NULL COMMENT '上传限速'; -ALTER TABLE `license` ADD COLUMN `down_limit_rate` varchar(20) DEFAULT NULL COMMENT '下载限速';