sunty
2019-10-30 a1ef2d42d320f075c75e8cef52a879114441c103
Merge remote-tracking branch 'origin/master'
2个文件已添加
6个文件已修改
415 ■■■■ 已修改文件
config/test.yaml 15 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
controllers/panTilt.go 32 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
controllers/syssetcont.go 46 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
extend/config/config.go 56 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
extend/sys/system.go 96 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
extend/util/util.go 42 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
router/router.go 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
scripts/netconfig 122 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
config/test.yaml
@@ -19,6 +19,21 @@
  channelCount: 0
  #硬盘个数
  diskCount: 2
  #Exec root command
  sudoPassword: 123
  sysThresholds:
  -
    value: 60
    color: #13ce66
  -
    value: 80
    color: #FF9C4A
  -
    value: 95
    color: #f53d3d
  -
    value: 100
    color: #5d0000
database:
  driver: sqlite
  name: sqlite3
controllers/panTilt.go
New file
@@ -0,0 +1,32 @@
package controllers
import (
    "webserver/extend/code"
    "webserver/extend/util"
    "github.com/gin-gonic/gin"
)
type PanTiltController struct {
}
type PTInstruct struct {
    ChannelId string `json:"channelId"` //服务器id
    PTZType   string `json:"ptzType"`   //轮询周期
    PTZParam  int32  `json:"ptzParam"`  //延时时间
}
func (controller PanTiltController) Controlling(c *gin.Context) {
    var param PTInstruct
    if err := c.BindJSON(&param); err != nil {
        util.ResponseFormat(c, code.RequestParamError, "参数有误")
        return
    }
    b := true
    if b {
        util.ResponseFormat(c, code.Success, "")
    } else {
        util.ResponseFormat(c, code.ComError, "保存失败")
    }
}
controllers/syssetcont.go
@@ -159,11 +159,13 @@
    } else {
        resData["server_id"] = sysconf.GetServerId()
        resData["server_name"] = sysconf.GetServerName()
        ipv4, mask, _ := util.GetLocalIP(config.Server.NetworkAdapter)
        gateway, _ := util.GetDefaultRoute(config.Server.NetworkAdapter)
        ipv4, mask, _ := sys.GetLocalIP(config.Server.NetworkAdapter)
        gateway, _ := sys.GetDefaultRoute(config.Server.NetworkAdapter)
        dns, _ := sys.GetDnsServer()
        resData["ip"] = ipv4
        resData["subMask"] = mask
        resData["gateway"] = gateway
        resData["dns"] = dns
        resData["deviceNum"] = config.Server.DeviceNum
        resData["deviceType"] = config.Server.DeviceType
@@ -193,6 +195,14 @@
    var api dbapi.SysSetApi
    paramBody := make(map[string]interface{}, 0)
    paramBody["serverName"] = dev_name
    // 设置ip
    isOk, msg := sys.SetNetworkConfig(c.PostForm("ip"), c.PostForm("subMask"), c.PostForm("gateway"), c.PostForm("dns"))
    if !isOk {
        util.ResponseFormat(c, code.ComError, msg)
        return
    }
    b, data := api.SaveServerInfo(paramBody)
    if b { // 查询是否存在
        util.ResponseFormat(c, code.Success, data)
@@ -308,11 +318,6 @@
        return
    }
    if root := sys.CheckRootPermissions(); !root {
        util.ResponseFormat(c, code.ServiceInsideError, "服务器没有修改时间的权限")
        return
    }
    if args.TimeZone != "CST" && args.TimeZone != "UTC" {
        if r := sys.SetTimeZone(args.TimeZone); !r {
            util.ResponseFormat(c, code.RequestParamError, "时区参数错误")
@@ -346,3 +351,30 @@
    info := sys.GetSysInfo()
    util.ResponseFormat(c, code.UpdateSuccess, info)
}
// @Summary 查询系统状态阈值设置
// @Description 获取当前系统的运行状态,CPU, GPU, 内存的阈值配置
// @Produce json
// @Tags sysset
// @Success 200 {string} json "{"code":200, msg:"目录结构数据", success:true}"
// @Failure 500 {string} json "{"code":500,  msg:"返回错误信息", success:false}"
// @Router /data/api-v/sysset/sysThresholds [GET]
func (sset SysSetController) GetSysThresholds(c *gin.Context) {
    util.ResponseFormat(c, code.UpdateSuccess, config.Server.SysThresholds)
}
// @Summary 重启系统
// @Description 重启操作系统
// @Produce json
// @Tags sysset
// @Success 200 {string} json "{"code":200, msg:"目录结构数据", success:true}"
// @Failure 500 {string} json "{"code":500,  msg:"返回错误信息", success:false}"
// @Router /data/api-v/sysset/reboot [GET]
func (sset SysSetController) RebootOS(c *gin.Context) {
    if isOk, msg := sys.Reboot(); !isOk {
        util.ResponseFormat(c, code.UpdateFail, msg)
        return
    }
    util.ResponseFormat(c, code.Success, "正在重启")
}
extend/config/config.go
@@ -1,33 +1,41 @@
package config
import (
    "github.com/spf13/viper"
    "log"
    "github.com/spf13/viper"
)
type threshold struct {
    Value int    `mapstructure: "value"`
    Color string `mapstructure: "color"`
}
type server struct {
    Runmode   string `mapstructure: "runmode"`
    JwtSecret string `mapstructure: "jwtSecret"`
    JwtExpire string `mapstructure: "jwtExpire"`
    Url       string `mapstructure: "url"`
    AnalyServerId string `mapstructure: "analyServerId"`
    Runmode        string `mapstructure: "runmode"`
    JwtSecret      string `mapstructure: "jwtSecret"`
    JwtExpire      string `mapstructure: "jwtExpire"`
    Url            string `mapstructure: "url"`
    AnalyServerId  string `mapstructure: "analyServerId"`
    NetworkAdapter string `mapstructure: "networkAdapter"`
    DeviceNum string `mapstructure: "deviceNum"` //设备编号
    DeviceType string `mapstructure: "deviceType"`  //设备型号
    DeviceSerialNum string `mapstructure: "deviceSerialNum"`  //设备序列号
    MasterVersion string `mapstructure: "masterVersion"` //主控版本
    WebVersion string `mapstructure: "webVersion"`  //web版本
    ChannelCount string `mapstructure: "channelCount"`  //通道个数
    DiskCount string `mapstructure: "diskCount"`  //硬盘个数
    DeviceNum       string `mapstructure: "deviceNum"`       //设备编号
    DeviceType      string `mapstructure: "deviceType"`      //设备型号
    DeviceSerialNum string `mapstructure: "deviceSerialNum"` //设备序列号
    MasterVersion   string `mapstructure: "masterVersion"`   //主控版本
    WebVersion      string `mapstructure: "webVersion"`      //web版本
    ChannelCount    string `mapstructure: "channelCount"`    //通道个数
    DiskCount       string `mapstructure: "diskCount"`       //硬盘个数
    SudoPassword  string      `mapstructure: "sudoPassword"`
    SysThresholds []threshold `mapstructure: "sysThresholds"`
}
var Server = &server{}
// wp add es 索引 以及 IP port
type esinfo struct {
    Shards string         `mapstructure:"shards"`
    EsIndex  esindexlist `mapstructure:"index"`
    Shards  string      `mapstructure:"shards"`
    EsIndex esindexlist `mapstructure:"index"`
}
type esindexlist struct {
@@ -42,7 +50,7 @@
}
type sopath struct {
    Ip string `mapstructure:"ip"`
    Ip   string `mapstructure:"ip"`
    Port string `mapstructure:"port"`
}
@@ -51,18 +59,18 @@
var EsInfo = &esinfo{}
type facedetect struct {
    Ip string `mapstructure:"Ip"`
    Port int `mapstructure:"port"`
    Ip   string `mapstructure:"Ip"`
    Port int    `mapstructure:"port"`
}
type dbpersoncompare struct {
    Ip string `mapstructure:"ip"`
    Port int `mapstructure:"port"`
    Ip   string `mapstructure:"ip"`
    Port int    `mapstructure:"port"`
}
type espersoncompare struct {
    Port int `mapstructure:"port"`
    Ips []string `mapstructure:"ips"`
    Port int      `mapstructure:"port"`
    Ips  []string `mapstructure:"ips"`
}
var DbPersonCompInfo = &dbpersoncompare{}
@@ -84,8 +92,8 @@
    }
    viper.UnmarshalKey("es", EsInfo)
    viper.UnmarshalKey("server", Server)
    viper.UnmarshalKey("sopath",SoPath)
    viper.UnmarshalKey("sopath", SoPath)
    viper.UnmarshalKey("facedetect", FaceDetectSet)
    viper.UnmarshalKey("dbpersoncompare",DbPersonCompInfo)
    viper.UnmarshalKey("dbpersoncompare", DbPersonCompInfo)
    viper.UnmarshalKey("espersoncompare", EsCompServerInfo)
}
extend/sys/system.go
@@ -2,13 +2,24 @@
import (
    "errors"
    "os"
    "os/exec"
    "strconv"
    "webserver/extend/config"
    "webserver/extend/util"
    "fmt"
    "net"
    "strings"
    "time"
)
func execRootCommand(cmd string) ([]byte, error) {
    pwd := config.Server.SudoPassword
    cmdStr := fmt.Sprintf("echo %s | sudo -S %s", pwd, cmd)
    return exec.Command("/bin/sh", "-c", cmdStr).Output()
}
// 检查 root权限
func CheckRootPermissions() bool {
@@ -18,6 +29,79 @@
    }
    return true
}
// 获取本机网卡IP
func GetLocalIP(networkName string) (ipv4 string, mask string, err error) {
    interfaces, err := net.Interfaces()
    if err != nil {
        return "", "", err
    }
    for _, i := range interfaces {
        byName, err := net.InterfaceByName(i.Name)
        if err != nil {
            return "", "", err
        }
        addresses, err := byName.Addrs()
        for _, v := range addresses {
            if ipnet, ok := v.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
                if ipnet.IP.To4() != nil {
                    if byName.Name == networkName {
                        maskStr := ipnet.Mask.String()
                        mask64, _ := strconv.ParseUint(maskStr, 16, 32)
                        return ipnet.IP.String(), util.IpIntToString(int(mask64)), nil
                    }
                }
            }
        }
    }
    return "", "", errors.New("ipv4 not found")
}
// 获取本机网关ip
func GetDefaultRoute(networkName string) (route string, err error) {
    cmdStr := fmt.Sprintf("ip route show | grep -P \"^default.*%s\" | awk '{printf $3}'", networkName)
    cmd := exec.Command("/bin/sh", "-c", cmdStr)
    b, err := cmd.Output()
    if err != nil {
        return "", err
    }
    return string(b), nil
}
func GetDnsServer() (dns string, err error) {
    cmd := exec.Command("/bin/sh", "-c", "cat /etc/resolv.conf | grep nameserver | head -1 |awk '{printf $2}'")
    b, err := cmd.Output()
    if err != nil {
        return "", err
    }
    return string(b), nil
}
// 配置服务器网络
func SetNetworkConfig(ipv4, netmask, gateway, dns string) (bool, string) {
    networkConfigScript := "/opt/vasystem/bin/netconfig"
    ifname := config.Server.NetworkAdapter
    localIPv4, localNetMask, _ := GetLocalIP(ifname)
    localGW, _ := GetDefaultRoute(ifname)
    localDNS, _ := GetDnsServer()
    if localIPv4 == ipv4 && localNetMask == netmask && localGW == gateway && localDNS == dns {
        return true, ""
    }
    // 检查文件是否存在
    if _, err := os.Stat(networkConfigScript); err != nil {
        return false, "network Config Script not exist"
    }
    // # netconfig enp59s0f0 192.168.1.2 255.255.255.0 192.168.1.1 192.168.100.1
    cmdStr := fmt.Sprintf("%s %s %s %s %s %s", networkConfigScript, ifname, ipv4, netmask, gateway, dns)
    stdout, err := execRootCommand(cmdStr)
    return err == nil, string(stdout)
}
// 配置时区
@@ -76,8 +160,10 @@
        return false
    }
    args := []string{"-s", newTime}
    exec.Command("date", args...).Run()
    // args := []string{"-s", newTime}
    // exec.Command("date", args...).Run()
    dateCMD := fmt.Sprintf("date -s \"%s\"", newTime)
    execRootCommand(dateCMD)
    stopNTPCron()
    return true
@@ -111,3 +197,9 @@
    ntpdate := fmt.Sprintf("/usr/sbin/ntpdate %s", server)
    return true, exec.Command("/bin/sh", "-c", ntpdate).Run()
}
func Reboot() (bool, string) {
    stdout, err := execRootCommand("reboot")
    return err == nil, string(stdout)
}
extend/util/util.go
@@ -3,12 +3,9 @@
import (
    "bytes"
    "encoding/json"
    "errors"
    "image"
    "io/ioutil"
    "net"
    "net/http"
    "os/exec"
    "strconv"
    "webserver/extend/code"
@@ -134,45 +131,6 @@
        y1_new = int(i.Height)
    }
    return
}
// 获取本机网卡IP
func GetLocalIP(networkName string) (ipv4 string, mask string, err error) {
    interfaces, err := net.Interfaces()
    if err != nil {
        return "", "", err
    }
    for _, i := range interfaces {
        byName, err := net.InterfaceByName(i.Name)
        if err != nil {
            return "", "", err
        }
        addresses, err := byName.Addrs()
        for _, v := range addresses {
            if ipnet, ok := v.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
                if ipnet.IP.To4() != nil {
                    if byName.Name == networkName {
                        maskStr := ipnet.Mask.String()
                        mask64, _ := strconv.ParseUint(maskStr, 16, 32)
                        return ipnet.IP.String(), IpIntToString(int(mask64)), nil
                    }
                }
            }
        }
    }
    return "", "", errors.New("ipv4 not found")
}
func GetDefaultRoute(networkName string) (route string, err error) {
    cmdStr := fmt.Sprintf("ip route show | grep -P \"^default.*%s\" | awk '{print $3}'", networkName)
    cmd := exec.Command("/bin/sh", "-c", cmdStr)
    b, err := cmd.Output()
    if err != nil {
        return "", err
    }
    return string(b), nil
}
func StringIpToInt(ipstring string) int {
router/router.go
@@ -42,6 +42,7 @@
    sysMenuController := new(controllers.SysMenuController)
    clusterController := new(controllers.ClusterController)
    sysRoleController := new(controllers.RoleController)
    ptController := new(controllers.PanTiltController)
    sysApi := r.Group("/data/api-u/sys")
    {
@@ -99,6 +100,8 @@
        camera.POST("/updateRunEnable", cameraController.UpdateRunEnable)
        camera.POST("/changeRunType", cameraController.ChangeRunType)
        camera.GET("/getAllCamerasByServer", cameraController.GetAllCamerasByServer)
        camera.POST("/ptControl", ptController.Controlling)
    }
    cameraTaskArgsApi := r.Group(urlPrefix + "/cameraTaskArgs")
@@ -203,6 +206,9 @@
        vsset.POST("/updateClock", ssController.SetSysClock)
        vsset.GET("/ntpTest", ssController.TestNTPServer)
        vsset.GET("/sysinfo", ssController.GetSysInfo)
        vsset.GET("/sysThresholds", ssController.GetSysThresholds)
        vsset.GET("/reboot", ssController.RebootOS)
    }
    //算法库操作
scripts/netconfig
New file
@@ -0,0 +1,122 @@
#!/bin/bash
# 系统网络配置文件
NETWORK_CONFIG_FILE="/etc/network/interfaces"
LOG_FILE="/opt/vasystem/logs/netconfig.log"
# basic系统服务关闭脚本
SERVICE_STOP_CMD=""
# basic系统服务启动脚本
SERVICE_START_CMD=""
INTERFACE="$1"
IPADDR="$2"
NETMASK="$3"
GATEWAY="$4"
DNSSERVER="$5"
Usage(){
    cat <<EOF
$0 : missing operand
Usage:
    $0 <ifname> <ipaddr> <netmask> <gateway> [dns-server]
EOF
    exit 1
}
n_log() {
    v_time=$(date "+%Y-%m-%d %H:%M:%S")
    echo "$v_time $*" >>$LOG_FILE
}
write_interfaces()
{
echo "auto lo
iface lo inet loopback
auto $INTERFACE
iface $INTERFACE inet static
address $IPADDR
netmask $NETMASK
gateway $GATEWAY
dns-nameserver $DNSSERVER
" > $NETWORK_CONFIG_FILE
ret=$?
n_log "write_interfaces. ret: $ret"
return $ret
}
validate_ip()
{
    if [[ $1 =~ ^([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$ ]]; then
        return 0
    fi
    return 1
}
network_restart()
{
    # 重启网络
    /etc/init.d/networking restart
    ip addr flush dev $INTERFACE
    ifdown $INTERFACE
    ifup $INTERFACE
    n_log "network restart."
    sleep 3
}
service_restart()
{
    n_log "service restart." >>$LOG_FILE
    # 重启basic服务
    su basic -c "sh /opt/startAllServices.sh &"
}
# Start Execution
n_log "Start NetConfig Execution, CMD: $*"
# 校验参数个数
if [ $# -lt 4 ]; then
    Usage
fi
# 验证接口是否存在
ifconfig | grep -q $INTERFACE || exit 1
# 校验IP合法性
i=0
while [ $# -ne 0 ]
do
    if [ $i -gt 0 -a $i -lt 4 ]; then
        validate_ip $1 || exit 1
    fi
    shift
    let i+=1
done
if [ "$DNSSERVER" == "" ]; then
    DNSSERVER=$GATEWAY
fi
# 配置接口
write_interfaces || {
    echo -n "write interfaces failure"
    exit 1
}
# 重启网络
network_restart
# 重启相关服务, 不更改ip的情况下, 重启网络即可
localip=$(/sbin/ifconfig $INTERFACE | grep inet | grep -v inet6 | awk '{printf $2}' | tr -d "addr:")
if [ "$localip" != "$IPADDR" ]; then
    service_restart
fi
exit 0