diff --git a/.gitignore b/.gitignore index 85e7c1dfcb7fbb33f932c81024018cd8c10519da..3f9d9ae30d8811757c50214f9481fd95b17def61 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,5 @@ /.idea/ +/vendor/ +/out/ +/vendor +/.vscode/ \ No newline at end of file diff --git a/app/console/.gitignore b/app/console/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ac7af2e80e3a7920c6989974744a27c21db8cd33 --- /dev/null +++ b/app/console/.gitignore @@ -0,0 +1 @@ +/html/ diff --git a/app/console/config/cluster.yaml b/app/console/config/cluster.yaml index d6490fbd113844571c6bca8881421d116de73b47..27cb5a8a054bc9493ff156fe8df947acec78abdf 100644 --- a/app/console/config/cluster.yaml +++ b/app/console/config/cluster.yaml @@ -1,6 +1,5 @@ cluster: - - - name: "Default" + - name: "Default" title: "默认机房" note: "默认机房" db: diff --git a/app/console/main.go b/app/console/main.go index 5f395a3af0428a10cc487c5d19f6d44e0d6d8344..e07e2c95ed896d475539f735432df1fbed6ad730 100644 --- a/app/console/main.go +++ b/app/console/main.go @@ -15,17 +15,16 @@ var ( UserPassword string UserName string ConfFilepath = "./config/goku.conf" - ) func main() { flag.StringVar(&ConfFilepath, "c", "./config/goku.conf", "Please provide a valid configuration file path") flag.StringVar(&UserName, "u", "", "Please provide user name") flag.StringVar(&UserPassword, "p", "", "Please provide user password") - isDebug := flag.Bool("debug",false,"") + isDebug := flag.Bool("debug", false, "") flag.Parse() - if *isDebug{ + if *isDebug { log.StartDebug() } // 初始化配置 @@ -42,11 +41,10 @@ func main() { _ = general.General() // 检测是否安装 - - if s, err := account.CheckSuperAdminCount(); err!= nil { + if s, err := account.CheckSuperAdminCount(); err != nil { log.Panic(err) return - }else if s == 0 { + } else if s == 0 { if UserName == "" { log.Fatal("[ERROR] Fail to create administrator. Please try again or contact technical support of eoLinker GOKU API Gateway.") //fmt.Println("[ERROR] Fail to create administrator. Please try again or contact technical support of eoLinker GOKU API Gateway.") @@ -68,7 +66,6 @@ func main() { } } - console.Router() console.Server() } diff --git a/app/goku-node/main.go b/app/goku-node/main.go index cb1d7b542839f3a44fe8866bcf6399cdc14d2003..4380d8173314bce5affafe9280a13f1167de2b33 100644 --- a/app/goku-node/main.go +++ b/app/goku-node/main.go @@ -40,16 +40,15 @@ func initConfig(resultInfo map[string]interface{}) *entity.ClusterInfo { func main() { - runtime.GOMAXPROCS(runtime.NumCPU()) flag.StringVar(&adminHost, "admin", "127.0.0.1:7005", "Please provide a valid host!") //flag.IntVar(&adminPort, "P", 7005, "Please provide a valid port") flag.IntVar(&listenPort, "port", 6689, "Please provide a valid listen port!") - isDebug := flag.Bool("debug",false,"") + isDebug := flag.Bool("debug", false, "") flag.Parse() - if *isDebug{ + if *isDebug { log.StartDebug() } // @@ -64,9 +63,9 @@ func main() { node_common.SetClusterName(config.Name) - err:=database.InitConnection(&config.DB) - if err!=nil{ - log.Fatal("Fail to Init db:",err) + err := database.InitConnection(&config.DB) + if err != nil { + log.Fatal("Fail to Init db:", err) return } goku_node.InitLog() @@ -76,7 +75,7 @@ func main() { log.Debug("redis_manager.SetDefault") // 其他需要初始化的模块 - _=general.General() + _ = general.General() log.Debug("general.General()") goku_node.InitServer() @@ -89,5 +88,4 @@ func main() { } log.Fatalf("Server on :%d stoped \n", listenPort) - } diff --git a/common/auto-form/auto.go b/common/auto-form/auto.go index 31dd440b0977a51ad8445fdb4e4b7d997b84c7f8..b995796939b70d3f9f972a45c7325a642e713bce 100644 --- a/common/auto-form/auto.go +++ b/common/auto-form/auto.go @@ -1,7 +1,6 @@ package auto import ( - "errors" "fmt" "net" @@ -90,10 +89,10 @@ func setValues(ctx Values, c interface{}) error { if !has { continue } - if tag == "-"{ + if tag == "-" { continue } - name,opts := parseTag(tag) + name, opts := parseTag(tag) if !isValidTag(name) { continue } @@ -104,8 +103,8 @@ func setValues(ctx Values, c interface{}) error { return err } } else { - if opts.Contains("require"){ - return fmt.Errorf("require value of [%s] but has no",name) + if opts.Contains("require") { + return fmt.Errorf("require value of [%s] but has no", name) } defaultVal := field.Tag.Get("default") diff --git a/common/auto-form/tags.go b/common/auto-form/tags.go index 8abb2114f5dcb860e2b24bb9bc5b2e1fd25513fa..a01436c473a71c27c2e1c199aab6880e16316c4a 100644 --- a/common/auto-form/tags.go +++ b/common/auto-form/tags.go @@ -59,4 +59,4 @@ func isValidTag(s string) bool { } } return true -} \ No newline at end of file +} diff --git a/common/endless/endless.go b/common/endless/endless.go index 72b7521572aa56a182c46220b177573c09e1eb1c..e261ea9b20516c7bb496b626e39a79eb96b50f0b 100644 --- a/common/endless/endless.go +++ b/common/endless/endless.go @@ -137,7 +137,7 @@ func NewServer(addr string, handler http.Handler) (srv *endlessServer) { srv.Server.Handler = handler srv.BeforeBegin = func(addr string) { - log.Info("start service:",syscall.Getpid(), addr) + log.Info("start service:", syscall.Getpid(), addr) } runningServersOrder = append(runningServersOrder, addr) diff --git a/common/redis-manager/factory.go b/common/redis-manager/factory.go index 602b86a5097ee58d31b439e64c6dcee84f78f562..a5ac504b328de40d7201d759951494e96959bafe 100644 --- a/common/redis-manager/factory.go +++ b/common/redis-manager/factory.go @@ -26,7 +26,7 @@ func Create(config RedisConfig) Redis { return &redisProxy{ Cmdable: redis.NewClusterClient(option), - config: config, + config: config, } } case RedisModeSentinel: @@ -41,7 +41,7 @@ func Create(config RedisConfig) Redis { } return &redisProxy{ Cmdable: redis.NewSentinelRing(&option), - config: config, + config: config, } } case RedisModeStand: @@ -63,7 +63,7 @@ func Create(config RedisConfig) Redis { return &redisProxy{ Cmdable: redis.NewRing(&option), - config: config, + config: config, } } } diff --git a/common/redis-manager/manager.go b/common/redis-manager/manager.go index 79bb636e4dcee5e19207821bd6dba8c8bc58b10f..3995fa187801bab9ab7dc035a7c2b4c4397978b8 100644 --- a/common/redis-manager/manager.go +++ b/common/redis-manager/manager.go @@ -5,7 +5,7 @@ import ( ) var ( - redisOfCluster = make(map[string]Redis) + redisOfCluster = make(map[string]Redis) redisConfCluster = make(map[string]RedisConfig) locker sync.RWMutex @@ -28,20 +28,20 @@ func get(name string) (Redis, bool) { return r, h } func Get(name string) (Redis, bool) { - r,has:=get(name) + r, has := get(name) - if has{ - return r,r!=nil + if has { + return r, r != nil } locker.Lock() defer locker.Unlock() r, has = redisOfCluster[name] - if has{ - return r,has + if has { + return r, has } - c,h:= redisConfCluster[name] - if h{ + c, h := redisConfCluster[name] + if h { r = Create(c) redisOfCluster[name] = r return r, h @@ -49,5 +49,5 @@ func Get(name string) (Redis, bool) { redisOfCluster[name] = nil - return nil,false + return nil, false } diff --git a/common/redis-manager/proxy.go b/common/redis-manager/proxy.go index e1ee4905ba18e8d3f6802c425762e733f84fac98..31cdc36aa07145b2dc91e756ad7fbbbd70f2401d 100644 --- a/common/redis-manager/proxy.go +++ b/common/redis-manager/proxy.go @@ -9,18 +9,16 @@ type redisProxy struct { config RedisConfig } - func (p *redisProxy) Nodes() []string { - - ch:= make(chan string,1) + ch := make(chan string, 1) switch p.config.GetMode() { case RedisModeCluster: { conn := p.Cmdable.(*redis.ClusterClient) - go func(ch chan string ) { + go func(ch chan string) { conn.ForEachMaster(func(client *redis.Client) error { - ch<-client.Options().Addr + ch <- client.Options().Addr return nil }) close(ch) @@ -31,9 +29,9 @@ func (p *redisProxy) Nodes() []string { { conn := p.Cmdable.(*redis.SentinelRing) - go func(ch chan string ) { + go func(ch chan string) { conn.ForEachAddr(func(addr string) error { - ch<-addr + ch <- addr return nil }) close(ch) @@ -43,9 +41,9 @@ func (p *redisProxy) Nodes() []string { { conn := p.Cmdable.(*redis.Ring) - go func(ch chan string ) { + go func(ch chan string) { conn.ForEachShard(func(client *redis.Client) error { - ch<-client.Options().Addr + ch <- client.Options().Addr return nil }) close(ch) @@ -53,10 +51,9 @@ func (p *redisProxy) Nodes() []string { } } - - nodes:= make([]string,0,10) - for addr:=range ch{ - nodes = append(nodes,addr) + nodes := make([]string, 0, 10) + for addr := range ch { + nodes = append(nodes, addr) } return nodes } diff --git a/common/redis-manager/redis.go b/common/redis-manager/redis.go index 00efcdba46702f32e89dafc8ec7d1f2732f21267..d9f7b76d9e635dbb23e133381d1a9431669e6e4e 100644 --- a/common/redis-manager/redis.go +++ b/common/redis-manager/redis.go @@ -8,12 +8,11 @@ const ( RedisModeStand = "stand" ) - type Redis interface { redis.Cmdable GetConfig() RedisConfig //Foreach(fn func(client *localRedis.Client) error) error - Nodes()[]string + Nodes() []string } type RedisConfig interface { diff --git a/common/redis-manager/redis_conn.go b/common/redis-manager/redis_conn.go index 8469860dce524aac9777d171c28a9015e51bbaeb..b3921ca38ebfc9df32275f9f97a6f07adc13a5b9 100644 --- a/common/redis-manager/redis_conn.go +++ b/common/redis-manager/redis_conn.go @@ -30,4 +30,3 @@ func GetConnection() Redis { def = Create(defaultConfig) return def } - diff --git a/common/redis/sentinel_ring2.go b/common/redis/sentinel_ring2.go index a1734aa4351a2765b1a1f374f893055b5e843ab7..a48afcd76196d0760dcf546b27bf81e7c9a4bb80 100644 --- a/common/redis/sentinel_ring2.go +++ b/common/redis/sentinel_ring2.go @@ -17,13 +17,12 @@ import ( "github.com/eolinker/goku/common/redis/internal" ) - // RingOptions are used to configure a ring client and should be // passed to NewRing. type SentinelRingOptions struct { // Map of name => host:port addresses of ring shards. - Addrs []string - Masters[]string + Addrs []string + Masters []string // Frequency of PING commands sent to check shards availability. // Shard is considered down after 3 subsequent failed checks. HeartbeatFrequency time.Duration @@ -98,10 +97,10 @@ func (opt *SentinelRingOptions) init() { func (opt *SentinelRingOptions) clientOptions(masterName string) *FailoverOptions { return &FailoverOptions{ - MasterName:masterName, - SentinelAddrs:opt.Addrs, - DB: opt.DB, - Password: opt.Password, + MasterName: masterName, + SentinelAddrs: opt.Addrs, + DB: opt.DB, + Password: opt.Password, DialTimeout: opt.DialTimeout, ReadTimeout: opt.ReadTimeout, @@ -322,8 +321,8 @@ func NewSentinelRing(opt *SentinelRingOptions) *SentinelRing { clopt := opt.clientOptions(masterName) ring.shards.Add(masterName, NewFailoverClient(clopt)) } - ring.sentinelClients = make([]*SentinelClient,0,len(opt.Addrs)) - for _, addr:=range opt.Addrs{ + ring.sentinelClients = make([]*SentinelClient, 0, len(opt.Addrs)) + for _, addr := range opt.Addrs { sentinel := NewSentinelClient(&Options{ Addr: addr, @@ -335,11 +334,11 @@ func NewSentinelRing(opt *SentinelRingOptions) *SentinelRing { WriteTimeout: opt.WriteTimeout, PoolSize: 1, - PoolTimeout: opt.PoolTimeout, + PoolTimeout: opt.PoolTimeout, IdleTimeout: opt.IdleTimeout, IdleCheckFrequency: opt.IdleCheckFrequency, }) - ring.sentinelClients = append(ring.sentinelClients,sentinel) + ring.sentinelClients = append(ring.sentinelClients, sentinel) } go ring.shards.Heartbeat(opt.HeartbeatFrequency) @@ -429,24 +428,21 @@ func (c *SentinelRing) PSubscribe(channels ...string) *PubSub { //// It returns the first error if any. func (c *SentinelRing) ForEachAddr(fn func(addr string) error) error { - for _, masterName := range c.opt.Masters { + for _, sentinel := range c.sentinelClients { + masterAddrs, err := sentinel.GetMasterAddrByName(masterName).Result() - for _, sentinel := range c.sentinelClients { - - masterAddrs, err := sentinel.GetMasterAddrByName(masterName).Result() - - if err != nil { - internal.Logf("sentinel: GetMasterAddrByName master=%q failed: %s",masterName, err) - continue - } - - fn(fmt.Sprintf("%s:%s",masterAddrs[0],masterAddrs[1])) - break + if err != nil { + internal.Logf("sentinel: GetMasterAddrByName master=%q failed: %s", masterName, err) + continue } + fn(fmt.Sprintf("%s:%s", masterAddrs[0], masterAddrs[1])) + break + } + } return nil } diff --git a/console/admin/controller.go b/console/admin/controller.go index eef0fe2a2cebdb1ec5a3b976999e606b1406b6cc..ce84b69ddba05ee9374528f3abb55bee716af293 100644 --- a/console/admin/controller.go +++ b/console/admin/controller.go @@ -5,7 +5,8 @@ import ( "strconv" "strings" ) -func GetIpPort(r *http.Request) (string,int,error){ + +func GetIpPort(r *http.Request) (string, int, error) { ip := r.RemoteAddr ip = ip[:strings.Index(ip, ":")] if realIP := strings.TrimSpace(r.Header.Get("X-Real-Ip")); realIP != "" { @@ -15,9 +16,7 @@ func GetIpPort(r *http.Request) (string,int,error){ p := r.FormValue("port") port, err := strconv.Atoi(p) if err != nil { - return ip,port,err + return ip, port, err } - return ip,port,nil + return ip, port, nil } - - diff --git a/console/admin/heartbeat.go b/console/admin/heartbeat.go index 9f1e6ac4a613caedb9dfa5b940beab153711cdac..9c99749fefae17161bef8ede99025503cabc807b 100644 --- a/console/admin/heartbeat.go +++ b/console/admin/heartbeat.go @@ -7,21 +7,19 @@ import ( "strconv" ) -func heartbead(w http.ResponseWriter, r *http.Request) { +func heartbead(w http.ResponseWriter, r *http.Request) { ip, port, err := GetIpPort(r) if err != nil { controller.WriteError(w, "700000", "node", err.Error(), err) - return + return } - node.Refresh(ip,strconv.Itoa(port)) + node.Refresh(ip, strconv.Itoa(port)) controller.WriteResultInfo(w, "node", "node", nil) } - -func stopNode(w http.ResponseWriter, r *http.Request) { - +func stopNode(w http.ResponseWriter, r *http.Request) { ip, port, err := GetIpPort(r) if err != nil { @@ -29,6 +27,6 @@ func stopNode(w http.ResponseWriter, r *http.Request) { controller.WriteError(w, "700000", "node", err.Error(), err) return } - node.NodeStop(ip,strconv.Itoa(port)) + node.NodeStop(ip, strconv.Itoa(port)) controller.WriteResultInfo(w, "node", "node", nil) -} \ No newline at end of file +} diff --git a/console/admin/register.go b/console/admin/register.go index bac3fa264f07b65e75d93ba71fc6cf69aa1182e0..83acc17126c5ff50b1973e8c0eca02edea937bfd 100644 --- a/console/admin/register.go +++ b/console/admin/register.go @@ -22,7 +22,7 @@ func Register(w http.ResponseWriter, r *http.Request) { controller.WriteError(w, "700001", "cluster", err.Error()+ip, err) return } - node.Refresh(ip,strconv.Itoa(port)) + node.Refresh(ip, strconv.Itoa(port)) controller.WriteResultInfo(w, "cluster", "cluster", cluster) } diff --git a/console/admin/router.go b/console/admin/router.go index e7fe5b24053825bee5695615ebdd12d7dbaf7ceb..f33317d3c790aa2e81f30555d21db0926628aa4a 100644 --- a/console/admin/router.go +++ b/console/admin/router.go @@ -7,7 +7,7 @@ func router() http.Handler { serverHandler := http.NewServeMux() serverHandler.HandleFunc("/register", Register) serverHandler.HandleFunc("/node/heartbeat", heartbead) - serverHandler.HandleFunc("/node/stop",stopNode) + serverHandler.HandleFunc("/node/stop", stopNode) serverHandler.HandleFunc("/alert/msg/add", AddAlertMsg) return serverHandler } diff --git a/console/controller/account/guest.go b/console/controller/account/guest.go index 27f8456c1def84f24d2b1a1c304eba95649d32ae..5e08b5b93c7eb50377600641374bbcf859f7b582 100644 --- a/console/controller/account/guest.go +++ b/console/controller/account/guest.go @@ -9,8 +9,6 @@ import ( "strconv" ) - - // 用户登录 func Login(httpResponse http.ResponseWriter, httpRequest *http.Request) { diff --git a/console/controller/node/node.go b/console/controller/node/node.go index 514785ead836cd428d9ffe91599c786fb2f93e9b..2763bcc4b81ce97182decd9c0bc5003ffdc716dc 100644 --- a/console/controller/node/node.go +++ b/console/controller/node/node.go @@ -1,17 +1,14 @@ package node import ( - "encoding/json" "errors" - log "github.com/eolinker/goku/goku-log" "net/http" "strconv" - "github.com/eolinker/goku/console/controller" "github.com/eolinker/goku/console/module/node" cluster2 "github.com/eolinker/goku/server/cluster" @@ -42,7 +39,6 @@ func AddNode(httpResponse http.ResponseWriter, httpRequest *http.Request) { groupID := httpRequest.PostFormValue("groupID") gatewayPath := httpRequest.PostFormValue("gatewayPath") - gID, err := strconv.Atoi(groupID) if err != nil && groupID != "" { controller.WriteError(httpResponse, "230015", "", "[ERROR]Illegal groupID!", err) @@ -72,7 +68,6 @@ func AddNode(httpResponse http.ResponseWriter, httpRequest *http.Request) { } } - exits := node.CheckIsExistRemoteAddr(0, nodeIP, nodePort) if exits { @@ -84,8 +79,6 @@ func AddNode(httpResponse http.ResponseWriter, httpRequest *http.Request) { return } - - flag, result, err := node.AddNode(clusterId, nodeName, nodeIP, nodePort, gatewayPath, gID) if !flag { @@ -168,7 +161,7 @@ func EditNode(httpResponse http.ResponseWriter, httpRequest *http.Request) { } - flag, result, _ := node.EditNode(nodeName, nodeIP, nodePort, gatewayPath, id, gID) + flag, result, _ := node.EditNode(nodeName, nodeIP, nodePort, gatewayPath, id, gID) if !flag { controller.WriteError(httpResponse, "330000", "node", result, nil) @@ -292,7 +285,6 @@ func GetNodeInfo(httpResponse http.ResponseWriter, httpRequest *http.Request) { return } - // 节点IP查重 func CheckIsExistRemoteAddr(httpResponse http.ResponseWriter, httpRequest *http.Request) { @@ -331,7 +323,6 @@ func CheckIsExistRemoteAddr(httpResponse http.ResponseWriter, httpRequest *http. return } - // 批量修改节点分组 func BatchEditNodeGroup(httpResponse http.ResponseWriter, httpRequest *http.Request) { diff --git a/console/controller/node/nodeGroup.go b/console/controller/node/nodeGroup.go index 1b3f1e1e2ab01ee9436e10ac4a4a85f47916285b..1b855194cf19bdb0b101af78d09935289332a205 100644 --- a/console/controller/node/nodeGroup.go +++ b/console/controller/node/nodeGroup.go @@ -188,8 +188,8 @@ func GetNodeGroupList(httpResponse http.ResponseWriter, httpRequest *http.Reques } cluserName := httpRequest.FormValue("cluster") - clusterId,has := cluster2.GetId(cluserName) - if !has{ + clusterId, has := cluster2.GetId(cluserName) + if !has { controller.WriteError(httpResponse, "280001", "nodeGroup", diff --git a/console/log.go b/console/log.go index ff4aed412f38ef5c0b190fd9205c2c282887b347..0e53bbe92793602d0692ca20ef6beb2174bf1c95 100644 --- a/console/log.go +++ b/console/log.go @@ -5,11 +5,11 @@ import ( log "github.com/eolinker/goku/goku-log" ) -func InitLog() { +func InitLog() { c, _ := module.Get(module.ConsoleLog) - period,_:=log.ParsePeriod(c.Period) - log.SetOutPut(c.Enable ,c.Dir,c.File,period,c.Expire) - l,_:= log.ParseLevel(c.Level) + period, _ := log.ParsePeriod(c.Period) + log.SetOutPut(c.Enable, c.Dir, c.File, period, c.Expire) + l, _ := log.ParseLevel(c.Level) log.SetLevel(l) -} \ No newline at end of file +} diff --git a/console/module/account/guest.go b/console/module/account/guest.go index f29be650af5715beb83b3e7af0236b180a6c4414..f68bf20e045039fc5350d28f2e8f9c1c9bd80611 100644 --- a/console/module/account/guest.go +++ b/console/module/account/guest.go @@ -19,7 +19,7 @@ func Register(loginCall, loginPassword string) bool { return console_mysql.Register(loginCall, loginPassword) } -func CheckSuperAdminCount()(int,error){ - b,err:=console_mysql.CheckSuperAdminCount() - return b,err -} \ No newline at end of file +func CheckSuperAdminCount() (int, error) { + b, err := console_mysql.CheckSuperAdminCount() + return b, err +} diff --git a/console/module/account/user.go b/console/module/account/user.go index c16a2f4b535e403a96fc92edc3bbe150ca487f93..3b5a400036dc1042cbac9d4dcd06c236c97e7756 100644 --- a/console/module/account/user.go +++ b/console/module/account/user.go @@ -3,6 +3,7 @@ package account import ( "github.com/eolinker/goku/server/dao/console-mysql" ) + // 获取具有编辑权限的用户列表 func GetUserListWithPermission(operationType, operation string) (bool, []map[string]interface{}, error) { return console_mysql.GetUserListWithPermission(operationType, operation) diff --git a/console/module/api/api.go b/console/module/api/api.go index a9f06392dbc2bbe6d8866edabaab0ec604b784c2..e004e1db093ff936fc419f47f7e6aed5ffd49d27 100644 --- a/console/module/api/api.go +++ b/console/module/api/api.go @@ -1,7 +1,7 @@ package api import ( - dao "github.com/eolinker/goku/server/dao" + "github.com/eolinker/goku/server/dao" console_mysql "github.com/eolinker/goku/server/dao/console-mysql" entity "github.com/eolinker/goku/server/entity/console-entity" ) diff --git a/console/module/api/apiGroup.go b/console/module/api/apiGroup.go index 059ad53cd95affea1ddb337f093426f7559e39c8..99472d95ed6e3a3cd29535547031e8549c5daf4f 100644 --- a/console/module/api/apiGroup.go +++ b/console/module/api/apiGroup.go @@ -1,7 +1,7 @@ package api import ( - dao "github.com/eolinker/goku/server/dao" + "github.com/eolinker/goku/server/dao" console_mysql "github.com/eolinker/goku/server/dao/console-mysql" ) diff --git a/console/module/api/apiPlugin.go b/console/module/api/apiPlugin.go index 6292357d2a3f52a33a69112e9d23362132949e8b..aaeb7e0d17b94bf97dad25f14df3a08f1ff31075 100644 --- a/console/module/api/apiPlugin.go +++ b/console/module/api/apiPlugin.go @@ -4,7 +4,7 @@ import ( "strconv" "strings" - dao "github.com/eolinker/goku/server/dao" + "github.com/eolinker/goku/server/dao" console_mysql "github.com/eolinker/goku/server/dao/console-mysql" ) diff --git a/console/module/api/apiStrategy.go b/console/module/api/apiStrategy.go index c014876a21e90a7bb9d6085344dd07f029f8e49a..8c820dcc430a8084cbc49fe722690a7111ef0679 100644 --- a/console/module/api/apiStrategy.go +++ b/console/module/api/apiStrategy.go @@ -1,7 +1,7 @@ package api import ( - dao "github.com/eolinker/goku/server/dao" + "github.com/eolinker/goku/server/dao" console_mysql "github.com/eolinker/goku/server/dao/console-mysql" ) diff --git a/console/module/balance/balance.go b/console/module/balance/balance.go index c557efef9452bb688e577978e93f48a7c13a24d5..9e075a507d23d6f22dee109a74a809b541a30289 100644 --- a/console/module/balance/balance.go +++ b/console/module/balance/balance.go @@ -14,69 +14,72 @@ import ( func Add(info *Param) (string, error) { const TableName = "goku_balance" - serviceInfo,err:= service.Get(info.ServiceName) - if err!=nil{ - return fmt.Sprintf("serviceName:%s",err.Error()),err + serviceInfo, err := service.Get(info.ServiceName) + if err != nil { + return fmt.Sprintf("serviceName:%s", err.Error()), err } switch serviceInfo.Type { - case driver2.Static:{ - if info.Static == ""&& info.StaticCluster ==""{ - return "param:static 和 staticCluster 不能同时为空",errors.New( "param:static 和 staticCluster 不能同时为空") + case driver2.Static: + { + if info.Static == "" && info.StaticCluster == "" { + return "param:static 和 staticCluster 不能同时为空", errors.New("param:static 和 staticCluster 不能同时为空") + } + now := time.Now().Format("2006-01-02 15:04:05") + result, err := dao_balance.AddStatic(info.Name, info.ServiceName, info.Static, info.StaticCluster, info.Desc, now) + if err == nil { + dao.UpdateTable(TableName) + } + return result, err } - now := time.Now().Format("2006-01-02 15:04:05") - result, err :=dao_balance.AddStatic(info.Name,info.ServiceName,info.Static,info.StaticCluster,info.Desc,now) - if err == nil { - dao.UpdateTable(TableName) + case driver2.Discovery: + { + if info.AppName == "" { + return "param:appName 不能为空", errors.New("param:appName 不能为空") + } + now := time.Now().Format("2006-01-02 15:04:05") + result, err := dao_balance.AddDiscovery(info.Name, info.ServiceName, info.AppName, info.Desc, now) + if err == nil { + dao.UpdateTable(TableName) + } + return result, err } - return result, err - } - case driver2.Discovery:{ - if info.AppName == ""{ - return "param:appName 不能为空",errors.New( "param:appName 不能为空") - } - now := time.Now().Format("2006-01-02 15:04:05") - result, err :=dao_balance.AddDiscovery(info.Name,info.ServiceName,info.AppName,info.Desc,now) - if err == nil { - dao.UpdateTable(TableName) - } - return result, err - } } return "无效serviceName", errors.New("invalid serviceName") } - func Save(info *Param) (string, error) { const TableName = "goku_balance" - serviceInfo,err:= service.Get(info.ServiceName) - if err!=nil{ - return fmt.Sprintf("serviceName:%s",err.Error()),err + serviceInfo, err := service.Get(info.ServiceName) + if err != nil { + return fmt.Sprintf("serviceName:%s", err.Error()), err } switch serviceInfo.Type { - case driver2.Static:{ - if info.Static == ""&& info.StaticCluster ==""{ - return "param:static 和 staticCluster 不能同时为空",errors.New( "param:static 和 staticCluster 不能同时为空") + case driver2.Static: + { + if info.Static == "" && info.StaticCluster == "" { + return "param:static 和 staticCluster 不能同时为空", errors.New("param:static 和 staticCluster 不能同时为空") + } + now := time.Now().Format("2006-01-02 15:04:05") + result, err := dao_balance.SaveStatic(info.Name, info.ServiceName, info.Static, info.StaticCluster, info.Desc, now) + if err == nil { + dao.UpdateTable(TableName) + } + return result, err } - now := time.Now().Format("2006-01-02 15:04:05") - result, err :=dao_balance.SaveStatic(info.Name,info.ServiceName,info.Static,info.StaticCluster,info.Desc,now) - if err == nil { - dao.UpdateTable(TableName) + case driver2.Discovery: + { + if info.AppName == "" { + return "param:appName 不能为空", errors.New("param:appName 不能为空") + } + now := time.Now().Format("2006-01-02 15:04:05") + result, err := dao_balance.SaveDiscover(info.Name, info.ServiceName, info.AppName, info.Desc, now) + if err == nil { + dao.UpdateTable(TableName) + } + return result, err } - return result, err - } - case driver2.Discovery:{ - if info.AppName == ""{ - return "param:appName 不能为空",errors.New( "param:appName 不能为空") - } - now := time.Now().Format("2006-01-02 15:04:05") - result, err :=dao_balance.SaveDiscover(info.Name,info.ServiceName,info.AppName,info.Desc,now) - if err == nil { - dao.UpdateTable(TableName) - } - return result, err - } } @@ -88,18 +91,18 @@ func Get(name string) (*Info, error) { return nil, e } - return ReadInfo(b),nil + return ReadInfo(b), nil } -func Search(keyworkd string)([]*Info, error){ +func Search(keyworkd string) ([]*Info, error) { var entities []*entity.Balance - if keyworkd == ""{ - es, e:= dao_balance.GetAll() + if keyworkd == "" { + es, e := dao_balance.GetAll() if e != nil { return nil, e } entities = es - }else{ - es, e:= dao_balance.Search(keyworkd) + } else { + es, e := dao_balance.Search(keyworkd) if e != nil { return nil, e } diff --git a/console/module/balance/param.go b/console/module/balance/param.go index 85e5889d37f9a3fd1ce1ec5030059b03d29cd780..c81a4811561ad5dcc863db7ea31b18ffe0670501 100644 --- a/console/module/balance/param.go +++ b/console/module/balance/param.go @@ -6,41 +6,40 @@ import ( ) type Param struct { - Name string `opt:"balanceName,require"` - ServiceName string `opt:"serviceName,require"` - AppName string `opt:"appName"` - Static string `opt:"static"` + Name string `opt:"balanceName,require"` + ServiceName string `opt:"serviceName,require"` + AppName string `opt:"appName"` + Static string `opt:"static"` StaticCluster string `opt:"staticCluster"` - Desc string `opt:"balanceDesc"` + Desc string `opt:"balanceDesc"` } - type Info struct { - Name string `json:"balanceName"` - ServiceName string `json:"serviceName"` - ServiceType string `json:"serviceType"` - ServiceDriver string `json:"serviceDriver"` - AppName string `json:"appName"` - Static string `json:"static"` - StaticCluster map[string]string `json:"staticCluster"` - Desc string `json:"balanceDesc"` - CreateTime string `json:"createTime"` - UpdateTime string `json:"updateTime"` + Name string `json:"balanceName"` + ServiceName string `json:"serviceName"` + ServiceType string `json:"serviceType"` + ServiceDriver string `json:"serviceDriver"` + AppName string `json:"appName"` + Static string `json:"static"` + StaticCluster map[string]string `json:"staticCluster"` + Desc string `json:"balanceDesc"` + CreateTime string `json:"createTime"` + UpdateTime string `json:"updateTime"` } func ReadInfo(balance *entity.Balance) *Info { - info:=&Info{ + info := &Info{ Name: balance.Name, ServiceName: balance.ServiceName, ServiceType: balance.ServiceType, ServiceDriver: balance.ServiceDriver, - AppName: balance.AppName, + AppName: balance.AppName, Static: balance.Static, StaticCluster: nil, Desc: balance.Desc, CreateTime: balance.CreateTime, UpdateTime: balance.UpdateTime, } - json.Unmarshal([]byte(balance.StaticCluster),&info.StaticCluster) + json.Unmarshal([]byte(balance.StaticCluster), &info.StaticCluster) return info -} \ No newline at end of file +} diff --git a/console/module/balance/update.go b/console/module/balance/update.go index a89aa5b4758112768efe3e3b6b16a9f88f5b6fc5..434b297a0a0360da94084b225711886bfd2a96ef 100644 --- a/console/module/balance/update.go +++ b/console/module/balance/update.go @@ -10,31 +10,29 @@ import ( func init() { general.RegeditLater(Update) } -func Update()error { +func Update() error { - l,e:= dao_balance_update.GetAllOldVerSion() - if e!=nil{ + l, e := dao_balance_update.GetAllOldVerSion() + if e != nil { return e } - defStaticServiceName :=dao_balance_update.GetDefaultServiceStatic() - for _,e:=range l{ - update(e,defStaticServiceName) + defStaticServiceName := dao_balance_update.GetDefaultServiceStatic() + for _, e := range l { + update(e, defStaticServiceName) } - - return nil } -func update(e *entity.BalanceInfoEntity,serviceName string) { +func update(e *entity.BalanceInfoEntity, serviceName string) { - if e==nil{ + if e == nil { return } - param:=&Param{ + param := &Param{ Name: e.Name, ServiceName: serviceName, AppName: "", @@ -43,27 +41,26 @@ func update(e *entity.BalanceInfoEntity,serviceName string) { Desc: e.Desc, } - info,err:=e.Decode() + info, err := e.Decode() - if err!=nil{ + if err != nil { return } - - if info.Default!= nil{ + if info.Default != nil { param.Static = info.Default.ServersConfigOrg } - if info.Cluster !=nil{ - cluster:=make(map[string]string) - for clusterName,server:=range info.Cluster{ + if info.Cluster != nil { + cluster := make(map[string]string) + for clusterName, server := range info.Cluster { cluster[clusterName] = server.ServersConfigOrg } - data ,err:= json.Marshal(cluster) + data, err := json.Marshal(cluster) - if err==nil{ + if err == nil { param.StaticCluster = string(data) } @@ -71,5 +68,4 @@ func update(e *entity.BalanceInfoEntity,serviceName string) { Save(param) - -} \ No newline at end of file +} diff --git a/console/module/config-log/get.go b/console/module/config-log/get.go index 6732c39110b6cfcb8fc0cbd48471b9ac42f17a0f..597e7e81d536ae3116546b6d9b50246e0067d24d 100644 --- a/console/module/config-log/get.go +++ b/console/module/config-log/get.go @@ -7,25 +7,25 @@ import ( dao "github.com/eolinker/goku/server/dao/config-log" ) -func Get(name string) (*LogConfig,error) { - if _,has:=logNames[name];!has{ - return nil,fmt.Errorf("not has that log config of %s",name) +func Get(name string) (*LogConfig, error) { + if _, has := logNames[name]; !has { + return nil, fmt.Errorf("not has that log config of %s", name) } - c:=&LogConfig{} + c := &LogConfig{} c.Levels = Levels c.Periods = Periods c.Expires = Expires config, e := dao.Get(name) - if e!= nil || config == nil{ + if e != nil || config == nil { auto.SetDefaults(c) c.Name = name c.File = name c.Level = log.ErrorLevel.String() c.Period = log.PeriodHour.String() c.Expire = ExpireDefault - }else{ + } else { c.Read(config) } @@ -34,18 +34,18 @@ func Get(name string) (*LogConfig,error) { func GetAccess() (*AccessConfig, error) { config, e := dao.Get(AccessLog) - c:=new(AccessConfig) + c := new(AccessConfig) c.Periods = Periods c.Expires = Expires - if e!= nil || config == nil{ + if e != nil || config == nil { auto.SetDefaults(c) c.Name = AccessLog c.Period = log.PeriodHour.String() c.Expire = ExpireDefault c.InitFields() - }else{ + } else { c.Read(config) } return c, nil -} \ No newline at end of file +} diff --git a/console/module/config-log/init.go b/console/module/config-log/init.go index aa284088ed29e775eed0a0edcd10858c8bde355c..3569a6eb5033a250a2de74fc8b42f2152cee61b3 100644 --- a/console/module/config-log/init.go +++ b/console/module/config-log/init.go @@ -1,5 +1,5 @@ package config_log -func InitLog() { - -} \ No newline at end of file +func InitLog() { + +} diff --git a/console/module/config-log/log.go b/console/module/config-log/log.go index 891d2eee8f61c5d8cde2708b300fed6b81bc38fb..e4d95498891782cf54282afe01278ea6dc5d2680 100644 --- a/console/module/config-log/log.go +++ b/console/module/config-log/log.go @@ -10,9 +10,9 @@ import ( ) const ( - ConsoleLog = "console" - NodeLog = "node" - AccessLog = "access" + ConsoleLog = "console" + NodeLog = "node" + AccessLog = "access" ExpireDefault = 3 ) @@ -24,24 +24,24 @@ var ( } Expires = []ValueTitle{ { - Value:3, - Title:"3天", + Value: 3, + Title: "3天", }, { - Value:7, - Title:"7天", + Value: 7, + Title: "7天", }, { - Value:30, - Title:"30天", + Value: 30, + Title: "30天", }, { - Value:90, - Title:"90天", + Value: 90, + Title: "90天", }, { - Value:180, - Title:"180天", + Value: 180, + Title: "180天", }, } Periods = []NameTitle{ @@ -98,7 +98,7 @@ type PutParam struct { File string `opt:"file,require"` Level string `opt:"level,require"` Period string `opt:"period,require"` - Expire int `opt:"expire,require"` + Expire int `opt:"expire,require"` } func (p *PutParam) Format() (*Param, error) { @@ -128,7 +128,7 @@ type AccessParam struct { File string `opt:"file,require"` Period string `opt:"period,require"` Fields string `opt:"fields,require"` - Expire int `opt:"expire,require"` + Expire int `opt:"expire,require"` } func (p *AccessParam) Format() (*Param, error) { @@ -169,7 +169,7 @@ func (c *LogConfig) Read(ent *entity.LogConfig) { c.Level = ent.Level c.Period = ent.Period c.Expire = ent.Expire - if c.Expire < ExpireDefault{ + if c.Expire < ExpireDefault { c.Expire = ExpireDefault } } diff --git a/console/module/config-log/set.go b/console/module/config-log/set.go index 7c3379e9b1ae30c02f0590a67d12b6ca57780bab..eb9ade308f590a0d314fdd9cb340a4cb8b612f07 100644 --- a/console/module/config-log/set.go +++ b/console/module/config-log/set.go @@ -8,41 +8,40 @@ import ( entity "github.com/eolinker/goku/server/entity/config-log" ) -func Set(name string,param *Param)error { - if _,has:=logNames[name];!has{ - return fmt.Errorf("not has that log config of %s",name) +func Set(name string, param *Param) error { + if _, has := logNames[name]; !has { + return fmt.Errorf("not has that log config of %s", name) } - c:=new(entity.LogConfig) + c := new(entity.LogConfig) c.Name = name c.Level = param.Level - c.Period = param.Period c.File = param.File c.Dir = param.Dir if param.Enable { c.Enable = 1 - }else{ + } else { c.Enable = 0 } c.Fields = param.Fields c.Expire = param.Expire - err :=dao.Set(c) - if err!=nil{ + err := dao.Set(c) + if err != nil { return err } - _=dao2.UpdateTable("goku_config_log") + _ = dao2.UpdateTable("goku_config_log") - if name == ConsoleLog{ + if name == ConsoleLog { go reset(c) } return nil } -func reset(c *entity.LogConfig) { +func reset(c *entity.LogConfig) { - period,_:=log.ParsePeriod(c.Period) - log.SetOutPut(c.Enable == 1,c.Dir,c.File,period,c.Expire) - l,_:= log.ParseLevel(c.Level) + period, _ := log.ParsePeriod(c.Period) + log.SetOutPut(c.Enable == 1, c.Dir, c.File, period, c.Expire) + l, _ := log.ParseLevel(c.Level) log.SetLevel(l) -} \ No newline at end of file +} diff --git a/console/module/monitor/hour.go b/console/module/monitor/hour.go index e78ba097aa58d049030fed8906faf609653218cb..860beafe0fa0aa5af11c17f59a071470a2e819d6 100644 --- a/console/module/monitor/hour.go +++ b/console/module/monitor/hour.go @@ -5,30 +5,31 @@ import ( "time" ) -func genHour(beginTime, endTime string, period int)( int,int ){ +func genHour(beginTime, endTime string, period int) (int, int) { startHour := 0 - endHour,_ := strconv.Atoi(time.Now().Add(time.Hour).Format("2006010215")) + endHour, _ := strconv.Atoi(time.Now().Add(time.Hour).Format("2006010215")) switch period { - case 3:{ + case 3: + { - bt,e:=time.Parse("2006-01-02", beginTime) - if e==nil{ - startHour,_= strconv.Atoi(bt.Format("2006010215")) + bt, e := time.Parse("2006-01-02", beginTime) + if e == nil { + startHour, _ = strconv.Atoi(bt.Format("2006010215")) + } + et, e := time.Parse("2006-01-02", endTime) + if e == nil { + et.Add(time.Hour*24 - time.Minute) + endHour, _ = strconv.Atoi(et.Format("2006010215")) + } } - et,e:=time.Parse("2006-01-02", endTime) - if e == nil{ - et.Add(time.Hour*24-time.Minute) - endHour,_= strconv.Atoi(et.Format("2006010215")) - } - } case 2: - startHour ,_= strconv.Atoi(time.Now().Add(- time.Hour*24*7).Format("2006010215")) + startHour, _ = strconv.Atoi(time.Now().Add(- time.Hour * 24 * 7).Format("2006010215")) case 1: - startHour ,_= strconv.Atoi(time.Now().Add(- time.Hour*24*3).Format("2006010215")) + startHour, _ = strconv.Atoi(time.Now().Add(- time.Hour * 24 * 3).Format("2006010215")) default: - startHour ,_= strconv.Atoi(time.Now().Format("2006010200")) + startHour, _ = strconv.Atoi(time.Now().Format("2006010200")) } - return startHour,endHour + return startHour, endHour } diff --git a/console/module/node/node.go b/console/module/node/node.go index 6a4b772e65477f10addc43a84a5008e9d37428cd..fe83b8b743d8d04e501af848a9257a04a406fd85 100644 --- a/console/module/node/node.go +++ b/console/module/node/node.go @@ -6,14 +6,14 @@ import ( ) // 新增节点信息 -func AddNode(clusterId int, nodeName, nodeIP, nodePort, gatewayPath string, groupID int) (bool, map[string]interface{}, error) { - return console_mysql.AddNode(clusterId, nodeName, nodeIP, nodePort, gatewayPath, groupID) +func AddNode(clusterId int, nodeName, nodeIP, nodePort, gatewayPath string, groupID int) (bool, map[string]interface{}, error) { + return console_mysql.AddNode(clusterId, nodeName, nodeIP, nodePort, gatewayPath, groupID) } // 修改节点 func EditNode(nodeName, nodeIP, nodePort, gatewayPath string, nodeID, groupID int) (bool, string, error) { - return console_mysql.EditNode(nodeName, nodeIP, nodePort, gatewayPath, nodeID, groupID) + return console_mysql.EditNode(nodeName, nodeIP, nodePort, gatewayPath, nodeID, groupID) } // 删除节点 @@ -23,32 +23,30 @@ func DeleteNode(nodeID int) (bool, string, error) { // 获取节点信息 func GetNodeInfo(nodeID int) (bool, *entity.Node, error) { - b, node, e := console_mysql.GetNodeInfo(nodeID) + b, node, e := console_mysql.GetNodeInfo(nodeID) ResetNodeStatus(node) - return b,node,e + return b, node, e } // 获取节点信息 func GetNodeInfoByIpPort(ip string, port int) (bool, *entity.Node, error) { b, node, e := console_mysql.GetNodeByIpPort(ip, port) ResetNodeStatus(node) - return b,node,e + return b, node, e } // GetNodeList 获取节点列表 func GetNodeList(clusterID, groupID int, keyword string) (bool, []*entity.Node, error) { b, nodes, e := console_mysql.GetNodeList(clusterID, groupID, keyword) ResetNodeStatus(nodes...) - return b,nodes,e + return b, nodes, e } - // 节点IP查重 func CheckIsExistRemoteAddr(nodeID int, nodeIP, nodePort string) bool { return console_mysql.CheckIsExistRemoteAddr(nodeID, nodeIP, nodePort) } - // 批量删除节点 func BatchDeleteNode(nodeIDList string) (bool, string, error) { flag, nodeIDList, err := console_mysql.GetAvaliableNodeListFromNodeList(nodeIDList, 0) @@ -65,9 +63,7 @@ func BatchEditNodeGroup(nodeIDList string, groupID int) (bool, string, error) { return console_mysql.BatchEditNodeGroup(nodeIDList, groupID) } - // 获取节点IP列表 func GetNodeIPList() (bool, []map[string]interface{}, error) { return console_mysql.GetNodeIPList() } - diff --git a/console/module/node/status.go b/console/module/node/status.go index 2dd109616c07dd1448f0454e3d2cfe26d77add07..cf80499de4412fd81b672c798d758c2972e43ec5 100644 --- a/console/module/node/status.go +++ b/console/module/node/status.go @@ -7,71 +7,73 @@ import ( "time" ) -const EXPIRE = time.Second * 10 -var( +const EXPIRE = time.Second * 10 + +var ( manager = _StatusManager{ - locker:sync.RWMutex{}, - lastHeartBeat:make(map[string]time.Time), + locker: sync.RWMutex{}, + lastHeartBeat: make(map[string]time.Time), } ) + type _StatusManager struct { - locker sync.RWMutex + locker sync.RWMutex lastHeartBeat map[string]time.Time } -func (m *_StatusManager)refresh(id string) { - t:=time.Now() +func (m *_StatusManager) refresh(id string) { + t := time.Now() m.locker.Lock() - m.lastHeartBeat[id]=t + m.lastHeartBeat[id] = t m.locker.Unlock() } -func (m *_StatusManager)stop(id string) { +func (m *_StatusManager) stop(id string) { m.locker.Lock() - delete(m.lastHeartBeat,id) + delete(m.lastHeartBeat, id) m.locker.Unlock() } -func (m *_StatusManager)get(id string) (time.Time, bool) { +func (m *_StatusManager) get(id string) (time.Time, bool) { m.locker.RLock() - t,b:=m.lastHeartBeat[id] + t, b := m.lastHeartBeat[id] m.locker.RUnlock() - return t,b + return t, b } -func Refresh(ip string,port string) { - id:=fmt.Sprintf("%s:%d",ip,port) +func Refresh(ip string, port string) { + id := fmt.Sprintf("%s:%d", ip, port) manager.refresh(id) } -func NodeStop(ip,port string) { - id:=fmt.Sprintf("%s:%d",ip,port) +func NodeStop(ip, port string) { + id := fmt.Sprintf("%s:%d", ip, port) manager.stop(id) } -func IsLive(ip string,port string) bool { - id:=fmt.Sprintf("%s:%d",ip,port) - t,has:=manager.get(id) - if !has{ +func IsLive(ip string, port string) bool { + id := fmt.Sprintf("%s:%d", ip, port) + t, has := manager.get(id) + if !has { return false } - if time.Now().Sub(t) > EXPIRE{ + if time.Now().Sub(t) > EXPIRE { return false } return true } -func ResetNodeStatus(nodes... *entity.Node) { - for _, node:=range nodes{ +func ResetNodeStatus(nodes ...*entity.Node) { + for _, node := range nodes { - if IsLive(node.NodeIP,node.NodePort){ + if IsLive(node.NodeIP, node.NodePort) { node.NodeStatus = 1 - }else{ + } else { node.NodeStatus = 0 } } -} \ No newline at end of file +} diff --git a/console/module/plugin/plugin-config/config.go b/console/module/plugin/plugin-config/config.go index f578e16f569ca3dcd9ac12a077995d8dc9ead4b3..21e164b36eee47c04de3392aa55c1c9aaae69832 100644 --- a/console/module/plugin/plugin-config/config.go +++ b/console/module/plugin/plugin-config/config.go @@ -23,17 +23,17 @@ func CheckConfig(pluginName string, config []byte) (bool, error) { switch v := err.(type) { case *json.SyntaxError: { - end := int64(bytes.IndexFunc(config[v.Offset:], isEnd)) - if end == -1{ - end = int64(len(config)-1) - }else{ + end := int64(bytes.IndexFunc(config[v.Offset:], isEnd)) + if end == -1 { + end = int64(len(config) - 1) + } else { end = end + v.Offset } start := 0 if v.Offset > 0 { start = bytes.LastIndexFunc(config[:v.Offset], isEnd) } - if start == -1{ + if start == -1 { start = 0 } @@ -41,7 +41,7 @@ func CheckConfig(pluginName string, config []byte) (bool, error) { } case *json.UnmarshalTypeError: { - return false, fmt.Errorf("数据类型不正确:\"%s\":%s", v.Field,v.Value) + return false, fmt.Errorf("数据类型不正确:\"%s\":%s", v.Field, v.Value) } } diff --git a/console/module/plugin/plugin-config/configs.go b/console/module/plugin/plugin-config/configs.go index 59d1ca468690a4b59d24220bafcabebf91752ed6..39130841f741e2e37af905c3f56b670265df1fc7 100644 --- a/console/module/plugin/plugin-config/configs.go +++ b/console/module/plugin/plugin-config/configs.go @@ -1,28 +1,26 @@ package plugin_config func init() { - allConfigOfPlugin=map[string]interface{}{ - "goku-apikey_auth":new(APIKeyConf), - "goku-basic_auth":new(basicAuthConf), - "goku-circuit_breaker":new(CircuitBreakerConf), - "goku-cors":new(gokuCorsConfig), - "goku-data_format_transformer":new(dataFormatTranformerConf), - "goku-default_response":new(defaultResponseConf), - "goku-extra_params":new(extraParamsConf), - "goku-http_log":new(Log), - "goku-ip_restriction":new(IPList), - "goku-jwt_auth":new(JwtConf), - "goku-oauth2_auth":new(Oauth2Conf), - "goku-params_check":new(paramsCheckConf), - "goku-params_transformer":new(paramsTransformerconf), - "goku-proxy_caching":new(ProxyCachingConf), - "goku-rate_limiting":new(_RateLimitingConf), - "goku-replay_attack_defender":new(ReplayAttackDefenderConf), - "goku-request_size_limiting":new(requestSizeLimit), - "goku-response_headers":new(responseHeader), - "goku-service_downgrade":new(serviceDowngradeConf), - - + allConfigOfPlugin = map[string]interface{}{ + "goku-apikey_auth": new(APIKeyConf), + "goku-basic_auth": new(basicAuthConf), + "goku-circuit_breaker": new(CircuitBreakerConf), + "goku-cors": new(gokuCorsConfig), + "goku-data_format_transformer": new(dataFormatTranformerConf), + "goku-default_response": new(defaultResponseConf), + "goku-extra_params": new(extraParamsConf), + "goku-http_log": new(Log), + "goku-ip_restriction": new(IPList), + "goku-jwt_auth": new(JwtConf), + "goku-oauth2_auth": new(Oauth2Conf), + "goku-params_check": new(paramsCheckConf), + "goku-params_transformer": new(paramsTransformerconf), + "goku-proxy_caching": new(ProxyCachingConf), + "goku-rate_limiting": new(_RateLimitingConf), + "goku-replay_attack_defender": new(ReplayAttackDefenderConf), + "goku-request_size_limiting": new(requestSizeLimit), + "goku-response_headers": new(responseHeader), + "goku-service_downgrade": new(serviceDowngradeConf), } } @@ -170,7 +168,6 @@ type ProxyCachingConf struct { RedisDatabase int `json:"redisDatabase"` } - type _RateLimitingConf struct { Second int64 `json:"second,omitempty"` Minute int64 `json:"minute,omitempty"` @@ -195,4 +192,4 @@ type serviceDowngradeConf struct { StatusCode int `json:"statusCode"` Headers map[string]string `json:"headers"` Body string `json:"body"` -} \ No newline at end of file +} diff --git a/console/module/service/module.go b/console/module/service/module.go index eca31325a44c2b2d59deeb8bf72db077e51b3b3a..d32955d3ca9a10de87b6b3d99b0b7262497589e4 100644 --- a/console/module/service/module.go +++ b/console/module/service/module.go @@ -8,7 +8,8 @@ import ( entity "github.com/eolinker/goku/server/entity/console-entity" ) -const _TableName = "goku_service_config" +const _TableName = "goku_service_config" + func Add(param *AddParam) error { err := dao_service.Add(param.Name, param.Driver, param.Desc, param.Config, param.ClusterConfig, false, param.HealthCheck, param.HealthCheckPath, param.HealthCheckCode, param.HealthCheckPeriod, param.HealthCheckTimeOut) @@ -30,7 +31,7 @@ func Save(param *AddParam) error { return fmt.Errorf("not allowed change dirver from %s to %s for service", v.Driver, param.Driver) } - err:= dao_service.Save(param.Name, param.Desc, param.Config, param.ClusterConfig, param.HealthCheck, param.HealthCheckPath, param.HealthCheckCode, param.HealthCheckPeriod, param.HealthCheckTimeOut) + err := dao_service.Save(param.Name, param.Desc, param.Config, param.ClusterConfig, param.HealthCheck, param.HealthCheckPath, param.HealthCheckCode, param.HealthCheckPeriod, param.HealthCheckTimeOut) if err == nil { dao.UpdateTable(_TableName) } @@ -77,7 +78,7 @@ func tran(v *entity.Service) *Service { IsDefault: v.IsDefault, HealthCheck: v.HealthCheck, UpdateTime: v.UpdateTime, - CreateTime:v.CreateTime, + CreateTime: v.CreateTime, } d, has := driver2.Get(v.Driver) diff --git a/console/module/service/service.go b/console/module/service/service.go index c9b65fa0197e184e929eb56653616111bd8b598a..ad84c6235466468bdd5bda200f10aec3b08b6300 100644 --- a/console/module/service/service.go +++ b/console/module/service/service.go @@ -16,30 +16,30 @@ type Service struct { IsDefault bool `json:"isDefault"` HealthCheck bool `json:"healthCheck"` UpdateTime string `json:"updateTime"` - CreateTime string `json:"createTime"` + CreateTime string `json:"createTime"` } type Info struct { *Service - Config string `json:"config"` - ClusterConfig string `json:"-"` - ClusterConfigObj map[string]string `json:"clusterConfig"` - HealthCheckPath string `json:"healthCheckPath"` - HealthCheckPeriod int `json:"healthCheckPeriod"` - HealthCheckCode string `json:"healthCheckCode"` - HealthCheckTimeOut int `json:"healthCheckTimeOut"` + Config string `json:"config"` + ClusterConfig string `json:"-"` + ClusterConfigObj map[string]string `json:"clusterConfig"` + HealthCheckPath string `json:"healthCheckPath"` + HealthCheckPeriod int `json:"healthCheckPeriod"` + HealthCheckCode string `json:"healthCheckCode"` + HealthCheckTimeOut int `json:"healthCheckTimeOut"` } -func (i *Info) Decode() { - json.Unmarshal([]byte(i.ClusterConfig),&i.ClusterConfigObj) +func (i *Info) Decode() { + json.Unmarshal([]byte(i.ClusterConfig), &i.ClusterConfigObj) } type AddParam struct { - Name string `opt:"name,require"` - Driver string `opt:"driver" default:"static"` - Desc string `opt:"desc"` - Config string `opt:"config"` - ClusterConfig string `opt:"clusterConfig"` + Name string `opt:"name,require"` + Driver string `opt:"driver" default:"static"` + Desc string `opt:"desc"` + Config string `opt:"config"` + ClusterConfig string `opt:"clusterConfig"` //ClusterConfigObj map[string]string `json:"clusterConfig"` HealthCheck bool `opt:"healthCheck" default:"false"` HealthCheckPath string `opt:"healthCheckPath"` diff --git a/console/router.go b/console/router.go index 4cd61d1df6c2475ea534eadf1ebf781bb5cb3ff0..6b45086caee34e5a4b9afddb71057c782b111b10 100644 --- a/console/router.go +++ b/console/router.go @@ -45,9 +45,6 @@ func Router() { http.HandleFunc("/monitor/gateway/getSummaryInfo", monitor.GetGatewayMonitorSummaryByPeriod) - - - // 项目 http.HandleFunc("/project/add", project.AddProject) http.HandleFunc("/project/edit", project.EditProject) @@ -157,11 +154,9 @@ func Router() { http.HandleFunc("/node/getList", node.GetNodeList) http.HandleFunc("/node/checkIsExistRemoteAddr", node.CheckIsExistRemoteAddr) - http.HandleFunc("/node/batchEditGroup", node.BatchEditNodeGroup) http.HandleFunc("/node/batchDelete", node.BatchDeleteNode) - // 节点分组 http.HandleFunc("/node/group/add", node.AddNodeGroup) http.HandleFunc("/node/group/edit", node.EditNodeGroup) diff --git a/go.mod b/go.mod index 533068b3d0e3878df14ae7fd8db6a050efab9f2c..23f6050799d2560a1e0663da96e662ad4617b3b6 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/eolinker/goku go 1.12 require ( - github.com/360EntSecGroup-Skylar/excelize v1.4.1 + github.com/360EntSecGroup-Skylar/excelize v1.4.1 // indirect github.com/eolinker/goku-plugin v0.1.3 github.com/go-redis/redis v6.15.2+incompatible github.com/go-sql-driver/mysql v1.4.1 @@ -11,9 +11,8 @@ require ( github.com/json-iterator/go v1.1.7 github.com/onsi/ginkgo v1.8.0 // indirect github.com/onsi/gomega v1.5.0 // indirect - github.com/pkg/errors v0.8.1 github.com/sirupsen/logrus v1.4.0 - github.com/yuchenfw/gocrypt v0.0.0-20190627061521-ee7b5965ec93 + github.com/yuchenfw/gocrypt v0.0.0-20190627061521-ee7b5965ec93 // indirect golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 google.golang.org/appengine v1.6.0 // indirect gopkg.in/yaml.v2 v2.2.2 diff --git a/goku-log/debug.go b/goku-log/debug.go index 231bc15d7610aad05f6e11031795930b4d6842c6..58ee4fc458b6a4ca80139446caa4044ffb3117f1 100644 --- a/goku-log/debug.go +++ b/goku-log/debug.go @@ -6,13 +6,12 @@ import ( "os" ) -func StartDebug() { +func StartDebug() { logger.AddHook(new(debugHook)) } type debugHook struct { - } func (h *debugHook) Levels() []logrus.Level { @@ -29,7 +28,7 @@ func (h *debugHook) Levels() []logrus.Level { func (h *debugHook) Fire(entry *logrus.Entry) error { s, e := logger.Formatter.Format(entry) - if e!=nil{ + if e != nil { fmt.Println(entry) return nil } diff --git a/goku-log/exported_test.go b/goku-log/exported_test.go index 932074c3c8a3bc969c24d18c4ee7b4c9c582081a..f4808fb298c94b73a59acb7150ecd0fe81875740 100644 --- a/goku-log/exported_test.go +++ b/goku-log/exported_test.go @@ -1,2 +1 @@ package goku_log - diff --git a/goku-log/formatter.go b/goku-log/formatter.go index 3b1a1adc221878a9579c870aa1cf64e179c95c9e..19b3b5ef42512c40a137a9f08a3cdee46df7406d 100644 --- a/goku-log/formatter.go +++ b/goku-log/formatter.go @@ -8,11 +8,13 @@ import ( "strings" "time" ) + const ( defaultTimestampFormat = time.RFC3339 ) + type LineFormatter struct { - TimestampFormat string + TimestampFormat string CallerPrettyfier func(*runtime.Frame) (function string, file string) } @@ -30,7 +32,6 @@ func (f *LineFormatter) Format(entry *logrus.Entry) ([]byte, error) { b = &bytes.Buffer{} } - timestampFormat := f.TimestampFormat if timestampFormat == "" { timestampFormat = defaultTimestampFormat @@ -39,9 +40,8 @@ func (f *LineFormatter) Format(entry *logrus.Entry) ([]byte, error) { levelText := strings.ToUpper(entry.Level.String()) levelText = levelText[0:4] - b.WriteString(fmt.Sprint("[", entry.Time.Format(timestampFormat),"] ")) - b.WriteString(fmt.Sprint("[", levelText,"] ")) - + b.WriteString(fmt.Sprint("[", entry.Time.Format(timestampFormat), "] ")) + b.WriteString(fmt.Sprint("[", levelText, "] ")) if entry.HasCaller() { @@ -61,23 +61,22 @@ func (f *LineFormatter) Format(entry *logrus.Entry) ([]byte, error) { b.WriteString(strings.TrimSuffix(entry.Message, "\n")) + for k, v := range data { - for k ,v:= range data { - - appendKeyValue(b,k,v) + appendKeyValue(b, k, v) } b.WriteByte('\n') return b.Bytes(), nil } -func needsQuoting(text string) bool { +func needsQuoting(text string) bool { - if len(text) == 0 { + if len(text) == 0 { return true } - if text[0] =='"' { + if text[0] == '"' { return false } for _, ch := range text { @@ -91,7 +90,7 @@ func needsQuoting(text string) bool { return false } -func appendKeyValue(b *bytes.Buffer, key string, value interface{}) { +func appendKeyValue(b *bytes.Buffer, key string, value interface{}) { if b.Len() > 0 { b.WriteByte(' ') } @@ -100,7 +99,7 @@ func appendKeyValue(b *bytes.Buffer, key string, value interface{}) { appendValue(b, value) } -func appendValue(b *bytes.Buffer, value interface{}) { +func appendValue(b *bytes.Buffer, value interface{}) { stringVal, ok := value.(string) if !ok { stringVal = fmt.Sprint(value) diff --git a/goku-log/period.go b/goku-log/period.go index 0c0fb823d9eb98051ce509ffc77e111b0b573aeb..702baba01b216fb32aaf3e365918f7f8e590ef4b 100644 --- a/goku-log/period.go +++ b/goku-log/period.go @@ -7,18 +7,18 @@ import ( type LogPeriod interface { String() string - FormatLayout()string + FormatLayout() string } type LogPeriodType int -func ParsePeriod(v string)(LogPeriod,error) { +func ParsePeriod(v string) (LogPeriod, error) { switch strings.ToLower(v) { case "month": - return PeriodMonth,nil + return PeriodMonth, nil case "day": - return PeriodDay,nil + return PeriodDay, nil case "hour": - return PeriodHour,nil + return PeriodHour, nil } return nil, fmt.Errorf("not a valid period: %q", v) @@ -42,12 +42,11 @@ const ( PeriodHour ) - func (period LogPeriodType) FormatLayout() string { switch period { case PeriodHour: { - return "2006-01-02-15" + return "2006-01-02-15" } case PeriodDay: { diff --git a/goku-log/writer.go b/goku-log/writer.go index 08955b469376856be138e16f1a2401c860ff4d2f..ce4994ee7ef65a6eff5d012029924167dfd2d22d 100644 --- a/goku-log/writer.go +++ b/goku-log/writer.go @@ -11,44 +11,46 @@ import ( "sync" "time" ) -const MaxBufferd = 1024*500 -var( + +const MaxBufferd = 1024 * 500 + +var ( bufferPool = &sync.Pool{ New: func() interface{} { return new(bytes.Buffer) }, } ) + type FileWriterByPeriod struct { - wC chan *bytes.Buffer - dir string - file string - period LogPeriod - enable bool - cancelFunc context.CancelFunc - locker sync.Mutex - wg sync.WaitGroup - expire time.Duration + wC chan *bytes.Buffer + dir string + file string + period LogPeriod + enable bool + cancelFunc context.CancelFunc + locker sync.Mutex + wg sync.WaitGroup + expire time.Duration } func NewFileWriteBytePeriod() *FileWriterByPeriod { - w:=&FileWriterByPeriod{ - locker:sync.Mutex{}, - wg:sync.WaitGroup{}, - enable:false, + w := &FileWriterByPeriod{ + locker: sync.Mutex{}, + wg: sync.WaitGroup{}, + enable: false, } - return w } -func (w *FileWriterByPeriod)getExpire()time.Duration{ +func (w *FileWriterByPeriod) getExpire() time.Duration { w.locker.Lock() - expire:= w.expire + expire := w.expire w.locker.Unlock() return expire } -func (w *FileWriterByPeriod)Set(dir,file string,period LogPeriod,expire time.Duration){ - fileName:=strings.TrimSuffix(file,".log") +func (w *FileWriterByPeriod) Set(dir, file string, period LogPeriod, expire time.Duration) { + fileName := strings.TrimSuffix(file, ".log") w.locker.Lock() w.file = fileName @@ -57,76 +59,75 @@ func (w *FileWriterByPeriod)Set(dir,file string,period LogPeriod,expire time.Dur w.expire = expire w.locker.Unlock() } -func (w *FileWriterByPeriod) Open() { +func (w *FileWriterByPeriod) Open() { w.locker.Lock() - defer w.locker.Unlock() + defer w.locker.Unlock() - if w.enable{ + if w.enable { return } ctx, cancel := context.WithCancel(context.Background()) w.cancelFunc = cancel - w.wC = make(chan *bytes.Buffer,100) + w.wC = make(chan *bytes.Buffer, 100) w.wg.Add(1) w.enable = true go w.do(ctx) } -func (w *FileWriterByPeriod) Close() { +func (w *FileWriterByPeriod) Close() { isClose := false w.locker.Lock() - if !w.enable{ + if !w.enable { w.locker.Unlock() return } - if w.cancelFunc != nil{ + if w.cancelFunc != nil { isClose = true w.cancelFunc() w.cancelFunc = nil } w.enable = false w.locker.Unlock() - if isClose{ + if isClose { w.wg.Wait() } } func (w *FileWriterByPeriod) Write(p []byte) (n int, err error) { - - l:=len(p) + l := len(p) if !w.enable { - return l,nil + return l, nil } buffer := bufferPool.Get().(*bytes.Buffer) buffer.Reset() buffer.Write(p) - w.wC<-buffer - return l,nil + w.wC <- buffer + return l, nil } -func (w *FileWriterByPeriod) do(ctx context.Context) { +func (w *FileWriterByPeriod) do(ctx context.Context) { w.initFile() - f,lastTag,e:=w.openFile() - if e!=nil{ - fmt.Printf("open log file:%s\n",e.Error()) + f, lastTag, e := w.openFile() + if e != nil { + fmt.Printf("open log file:%s\n", e.Error()) return } - buf:=bufio.NewWriter(f) - t:=time.NewTicker(time.Second*5) + buf := bufio.NewWriter(f) + t := time.NewTicker(time.Second * 5) defer t.Stop() - tflusth:=time.NewTimer(time.Second) + tflusth := time.NewTimer(time.Second) - for{ + for { select { case <-ctx.Done(): { - for len(w.wC)>0{ - p:=<-w.wC + for len(w.wC) > 0 { + p := <-w.wC buf.Write(p.Bytes()) bufferPool.Put(p) } @@ -139,20 +140,20 @@ func (w *FileWriterByPeriod) do(ctx context.Context) { case <-t.C: { - if buf.Buffered() >0{ + if buf.Buffered() > 0 { buf.Flush() tflusth.Reset(time.Second) } - if lastTag != w.timeTag(time.Now()){ + if lastTag != w.timeTag(time.Now()) { f.Close() w.history(lastTag) - fnew,tag,err:=w.openFile() - if err!=nil{ + fnew, tag, err := w.openFile() + if err != nil { return } lastTag = tag - f=fnew + f = fnew buf.Reset(f) go w.dropHistory() @@ -161,60 +162,61 @@ func (w *FileWriterByPeriod) do(ctx context.Context) { } case <-tflusth.C: { - if buf.Buffered()> 0{ + if buf.Buffered() > 0 { buf.Flush() } tflusth.Reset(time.Second) } - case p:=<-w.wC:{ - buf.Write(p.Bytes()) - bufferPool.Put(p) - if buf.Buffered()>MaxBufferd{ - buf.Flush() + case p := <-w.wC: + { + buf.Write(p.Bytes()) + bufferPool.Put(p) + if buf.Buffered() > MaxBufferd { + buf.Flush() + } + tflusth.Reset(time.Second) } - tflusth.Reset(time.Second) - } } } } func (w *FileWriterByPeriod) timeTag(t time.Time) string { w.locker.Lock() - tag:= t.Format(w.period.FormatLayout()) + tag := t.Format(w.period.FormatLayout()) w.locker.Unlock() return tag } func (w *FileWriterByPeriod) history(tag string) { - path := filepath.Join(w.dir,fmt.Sprintf("%s.log",w.file)) - histroy:= filepath.Join(w.dir,fmt.Sprintf("%s-%s.log",w.file,tag)) - _=os.Rename(path,histroy) + path := filepath.Join(w.dir, fmt.Sprintf("%s.log", w.file)) + histroy := filepath.Join(w.dir, fmt.Sprintf("%s-%s.log", w.file, tag)) + _ = os.Rename(path, histroy) } -func (w *FileWriterByPeriod) dropHistory(){ - expire:=w.getExpire() +func (w *FileWriterByPeriod) dropHistory() { + expire := w.getExpire() expireTime := time.Now().Add(- expire) - pathPatten := filepath.Join(w.dir,fmt.Sprintf("%s-*",w.file)) + pathPatten := filepath.Join(w.dir, fmt.Sprintf("%s-*", w.file)) files, err := filepath.Glob(pathPatten) - if err==nil{ - for _,f:=range files{ - if info, e := os.Stat(f);e==nil{ + if err == nil { + for _, f := range files { + if info, e := os.Stat(f); e == nil { - if expireTime.After(info.ModTime()){ - _=os.Remove(f) + if expireTime.After(info.ModTime()) { + _ = os.Remove(f) } } } } } -func (w *FileWriterByPeriod) initFile() { - _=os.MkdirAll(w.dir,os.ModePerm) - path := filepath.Join(w.dir,fmt.Sprintf("%s.log",w.file)) - nowTag:= w.timeTag(time.Now()) - if info, e := os.Stat(path);e==nil{ - - timeTag:=w.timeTag(info.ModTime()) - if timeTag !=nowTag{ +func (w *FileWriterByPeriod) initFile() { + _ = os.MkdirAll(w.dir, os.ModePerm) + path := filepath.Join(w.dir, fmt.Sprintf("%s.log", w.file)) + nowTag := w.timeTag(time.Now()) + if info, e := os.Stat(path); e == nil { + + timeTag := w.timeTag(info.ModTime()) + if timeTag != nowTag { w.history(timeTag) } } @@ -223,14 +225,14 @@ func (w *FileWriterByPeriod) initFile() { } -func (w *FileWriterByPeriod)openFile()(*os.File,string,error) { - path := filepath.Join(w.dir,fmt.Sprintf("%s.log",w.file)) - nowTag:= w.timeTag(time.Now()) - f,err:=os.OpenFile(path,os.O_WRONLY|os.O_CREATE|os.O_APPEND,0666) +func (w *FileWriterByPeriod) openFile() (*os.File, string, error) { + path := filepath.Join(w.dir, fmt.Sprintf("%s.log", w.file)) + nowTag := w.timeTag(time.Now()) + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) - if err!= nil{ - return nil,"",err + if err != nil { + return nil, "", err } - return f,nowTag,err + return f, nowTag, err -} \ No newline at end of file +} diff --git a/goku-log/writer_test.go b/goku-log/writer_test.go index 188a3104df77676d74842c30459175658801cb05..8b6fb703ddbb91b08912f4f68c4c602e48b84654 100644 --- a/goku-log/writer_test.go +++ b/goku-log/writer_test.go @@ -8,7 +8,6 @@ import ( ) type MinPeriod struct { - } func (p *MinPeriod) String() string { @@ -20,17 +19,17 @@ func (p *MinPeriod) FormatLayout() string { } func TestFileWriterByPeriod(t *testing.T) { - w:=NewFileWriteBytePeriod("/Users/huangmengzhu/test/log","app.log",new(MinPeriod)) + w := NewFileWriteBytePeriod("/Users/huangmengzhu/test/log", "app.log", new(MinPeriod)) defer w.Close() - ctx,_:=context.WithTimeout(context.Background(),time.Minute*3) + ctx, _ := context.WithTimeout(context.Background(), time.Minute*3) - tick:=time.NewTicker(time.Millisecond) + tick := time.NewTicker(time.Millisecond) defer tick.Stop() - index:= 0 + index := 0 for { select { - case <-ctx.Done(): + case <-ctx.Done(): { w.Close() return @@ -39,8 +38,8 @@ func TestFileWriterByPeriod(t *testing.T) { case <-tick.C: { index++ - fmt.Fprintf(w,"line:%d\n",index) + fmt.Fprintf(w, "line:%d\n", index) } } } -} \ No newline at end of file +} diff --git a/goku-node/access-log/fields.go b/goku-node/access-log/fields.go index d139a86398f44e6ba4950205e9b76c79336bec08..a611da4e250fe910004d240987d9c5d3b365fd4e 100644 --- a/goku-node/access-log/fields.go +++ b/goku-node/access-log/fields.go @@ -3,6 +3,6 @@ package access_log import "time" const ( - DefaultTimeStampFormatter ="[2006-01-02 15:04:05]" - TimeIso8601Formatter = "["+time.RFC3339+"]" + DefaultTimeStampFormatter = "[2006-01-02 15:04:05]" + TimeIso8601Formatter = "[" + time.RFC3339 + "]" ) diff --git a/goku-node/access-log/formatter.go b/goku-node/access-log/formatter.go index d6543c270b64f31480c000dcc036962acde33fd2..c93edb10767c99974cbfa7d5767af0d9cc0949ca 100644 --- a/goku-node/access-log/formatter.go +++ b/goku-node/access-log/formatter.go @@ -10,10 +10,11 @@ import ( ) type AccessLogFormatter struct { - fields []access_field.AccessFieldKey - locker sync.RWMutex + fields []access_field.AccessFieldKey + locker sync.RWMutex TimestampFormat string } + func (f *AccessLogFormatter) SetFields(fields []access_field.AccessFieldKey) { f.locker.Lock() f.fields = fields @@ -32,27 +33,27 @@ func (f *AccessLogFormatter) Format(entry *logrus.Entry) ([]byte, error) { timestampFormat = DefaultTimeStampFormatter } - data:= entry.Data + data := entry.Data data[access_field.TimeLocal] = entry.Time.Format(timestampFormat) - data[access_field.TimeIso8601] = entry.Time.Format(TimeIso8601Formatter) + data[access_field.TimeIso8601] = entry.Time.Format(TimeIso8601Formatter) - msec := entry.Time.UnixNano()/int64(time.Millisecond) - data[access_field.Msec] = fmt.Sprintf("%d.%d",msec/1000,msec%1000) + msec := entry.Time.UnixNano() / int64(time.Millisecond) + data[access_field.Msec] = fmt.Sprintf("%d.%d", msec/1000, msec%1000) - requestTIme:= data[access_field.RequestTime].(time.Duration) - data[access_field.RequestTime] = fmt.Sprintf("%dms",requestTIme/time.Millisecond) + requestTIme := data[access_field.RequestTime].(time.Duration) + data[access_field.RequestTime] = fmt.Sprintf("%dms", requestTIme/time.Millisecond) - for _,key:=range f.fields{ + for _, key := range f.fields { b.WriteByte('\t') - if v,has := data[key.Key()];has{ - f.appendValue(b,v) - }else{ - f.appendValue(b,"-") + if v, has := data[key.Key()]; has { + f.appendValue(b, v) + } else { + f.appendValue(b, "-") } } b.WriteByte('\n') - p:=b.Bytes() - return p[1:],nil + p := b.Bytes() + return p[1:], nil } // @@ -75,11 +76,11 @@ func (f *AccessLogFormatter) appendValue(b *bytes.Buffer, value interface{}) { } //if !f.needsQuoting(stringVal) { - b.WriteString(stringVal) + b.WriteString(stringVal) //} else { // b.WriteString(fmt.Sprintf("%q", stringVal)) //} } -func NewAccessLogFormatter(fields []access_field.AccessFieldKey)*AccessLogFormatter { - return &AccessLogFormatter{fields:fields} -} \ No newline at end of file +func NewAccessLogFormatter(fields []access_field.AccessFieldKey) *AccessLogFormatter { + return &AccessLogFormatter{fields: fields} +} diff --git a/goku-node/access-log/log.go b/goku-node/access-log/log.go index f2dccebe731153d0dafc48316baff33f7b63d1a4..e92c84511b4039ca49a98fc4ca027a6ab8228784 100644 --- a/goku-node/access-log/log.go +++ b/goku-node/access-log/log.go @@ -6,10 +6,11 @@ import ( "github.com/sirupsen/logrus" "time" ) + var ( - logger *logrus.Logger - formatter *AccessLogFormatter - writer *log.FileWriterByPeriod + logger *logrus.Logger + formatter *AccessLogFormatter + writer *log.FileWriterByPeriod ) //func InitLogger(enable bool,fields []string,dir,file string,period log.LogPeriod) { @@ -19,41 +20,42 @@ var ( // //} type Fields = logrus.Fields -func Log(fields Fields) { - if logger ==nil{ + +func Log(fields Fields) { + if logger == nil { return } logger.WithFields(fields).Info() } -func SetFields(fields []access_field.AccessFieldKey){ - if formatter == nil{ - formatter = NewAccessLogFormatter(fields) - }else{ +func SetFields(fields []access_field.AccessFieldKey) { + if formatter == nil { + formatter = NewAccessLogFormatter(fields) + } else { formatter.SetFields(fields) } } -func SetOutput(enable bool,dir, file string, period log.LogPeriod,expire int) { +func SetOutput(enable bool, dir, file string, period log.LogPeriod, expire int) { - if enable{ - if writer == nil{ + if enable { + if writer == nil { writer = log.NewFileWriteBytePeriod() } - writer.Set(dir,file,period,time.Duration(expire)*time.Hour*24) + writer.Set(dir, file, period, time.Duration(expire)*time.Hour*24) writer.Open() - if logger == nil{ + if logger == nil { logger = logrus.New() logger.SetFormatter(formatter) logger.SetOutput(writer) logger.SetLevel(logrus.InfoLevel) } - }else{ - if writer!=nil{ + } else { + if writer != nil { writer.Close() } } -} \ No newline at end of file +} diff --git a/goku-node/access-log/log_test.go b/goku-node/access-log/log_test.go index b12cba0d0666d14ab2b976330f5419b2740acc14..b6b9072536e1d18f0a10157874aea8f0d50b4d59 100644 --- a/goku-node/access-log/log_test.go +++ b/goku-node/access-log/log_test.go @@ -8,41 +8,40 @@ import ( func Test(t *testing.T) { - dir:="/Users/huangmengzhu/test/log" - file:="access.log" - period:=log.PeriodDay + dir := "/Users/huangmengzhu/test/log" + file := "access.log" + period := log.PeriodDay SetFields(access_field.All()) - log.SetOutPut(true,dir,file,period) - demoCtx:=Fields{ - "$remote_addr":"192.168.0.1", - "$http_x_forwarded_for":"192.168.0.99", + log.SetOutPut(true, dir, file, period) + demoCtx := Fields{ + "$remote_addr": "192.168.0.1", + "$http_x_forwarded_for": "192.168.0.99", //"$remote_user":"", - "$request":"\"GET /kingsword\"", - "$status":200, - "$body_bytes_sent":300, - "$bytes_sent":500, + "$request": "\"GET /kingsword\"", + "$status": 200, + "$body_bytes_sent": 300, + "$bytes_sent": 500, //"$msec":"日志写入时间。单位为秒,精度是毫秒。", //"$http_referer":"", - "$http_user_agent":"\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36\"", - "$request_length":100, - "$request_time":100, + "$http_user_agent": "\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36\"", + "$request_length": 100, + "$request_time": 100, //"$time_iso8601":"ISO8601标准格式下的本地时间。", //"$time_local":"通用日志格式下的本地时间。", - "$requestId":"xxffsdffadf", - "$finally_server":"127.0.0.1:8080", - "$balance":"Static_Load", - "$strategy":"FKdCm2", - "$api":"\"1657 kingsword\"", - "$retry":"10.1.0.1:80,10.1.0.2:800", - "$proxy":"\"POST /proxy HTTPS\"", - "$proxy_status":200, + "$requestId": "xxffsdffadf", + "$finally_server": "127.0.0.1:8080", + "$balance": "Static_Load", + "$strategy": "FKdCm2", + "$api": "\"1657 kingsword\"", + "$retry": "10.1.0.1:80,10.1.0.2:800", + "$proxy": "\"POST /proxy HTTPS\"", + "$proxy_status": 200, } Log(demoCtx) writer.Close() - t.Log("xx") -} \ No newline at end of file +} diff --git a/goku-node/cmd/cluster.go b/goku-node/cmd/cluster.go index 63b8f2075c19312658c4c48ade5cdd089f870a2c..5add3ca7d68e6899c1745c0438636f20374f8012 100644 --- a/goku-node/cmd/cluster.go +++ b/goku-node/cmd/cluster.go @@ -9,4 +9,4 @@ type CMD struct { type ClusterConfig struct { CMD Cluster *entity.ClusterInfo `json:"cluster"` -} \ No newline at end of file +} diff --git a/goku-node/cmd/request.go b/goku-node/cmd/request.go index 193e03398dd73dc15c016282bec755df7bfca6b6..06802fe95338aedd06197eae3d1aa72ad0b05f9b 100644 --- a/goku-node/cmd/request.go +++ b/goku-node/cmd/request.go @@ -11,6 +11,7 @@ import ( node_common "github.com/eolinker/goku/goku-node/node-common" ) + // 新增报警信息 func AddAlertMessage(apiID int, apiName, requestURL, targetServer, targetURL, requestMethod, proxyMethod, headerList, queryParamList, formParamList, responseHeaderList string, alertPeriodType, alertCount, responseStatus int, isAlert string, strategyID string, strategyName, requestID string) (bool, string, error) { client := &http.Client{ diff --git a/goku-node/common/context.go b/goku-node/common/context.go index 3fb8e76bd04f5909f92a238ab40ca8fb1d2d9dba..0e73a653341c975d4ab2798e2f9274955fdcb848 100644 --- a/goku-node/common/context.go +++ b/goku-node/common/context.go @@ -40,7 +40,7 @@ func (ctx *Context) SetRetryTargetServers(retryTargetServers string) { ctx.retryTargetServers = retryTargetServers } -func (ctx *Context) Finish() (n int,statusCode int){ +func (ctx *Context) Finish() (n int, statusCode int) { header := ctx.PriorityHeader.header @@ -91,10 +91,10 @@ func (ctx *Context) Finish() (n int,statusCode int){ ctx.w.WriteHeader(statusCode) if !bodyAllowed { - return 0,statusCode + return 0, statusCode } n, _ = ctx.w.Write(ctx.Body) - return n,statusCode + return n, statusCode } func (ctx *Context) RequestId() string { return ctx.requestId diff --git a/goku-node/common/header.go b/goku-node/common/header.go index 3a02e1ca114f507b4913c5313c57729e2e744a33..8ff74bc6d3fdb089cd8417604e0e5837ed0d6766 100644 --- a/goku-node/common/header.go +++ b/goku-node/common/header.go @@ -1,11 +1,9 @@ package common import ( - goku_plugin "github.com/eolinker/goku-plugin" "net/http" "net/url" - ) type Header struct { @@ -20,7 +18,7 @@ func (h *Header) Headers() http.Header { } return n } -func (h *Header) String()string { +func (h *Header) String() string { return url.Values(h.header).Encode() //buf:=bytes.NewBuffer(nil) diff --git a/goku-node/driver.go b/goku-node/driver.go index ea112cea1717fe158a47c95132f0e1bfe82e2383..c0978f1ac1c488268448a5d63a5f164e0156c598 100644 --- a/goku-node/driver.go +++ b/goku-node/driver.go @@ -1,7 +1,6 @@ package goku_node import ( - _ "github.com/eolinker/goku/goku-node/manager/service-manager" _ "github.com/eolinker/goku/goku-service/driver/consul" _ "github.com/eolinker/goku/goku-service/driver/eureka" diff --git a/goku-node/handler/handler.go b/goku-node/handler/handler.go index 940dbde2417c01084fe2b49bd7c9fb6b51ac3aee..9091b6d7a264025a87576231aabed6f5705938dc 100644 --- a/goku-node/handler/handler.go +++ b/goku-node/handler/handler.go @@ -5,24 +5,24 @@ import ( ) type Entry struct { - Pattern string + Pattern string HandlerFunc func(w http.ResponseWriter, r *http.Request) } + func init() { } func Handler() []Entry { - return []Entry{ { - Pattern:"/goku-update", HandlerFunc:gokuUpdate, + Pattern: "/goku-update", HandlerFunc: gokuUpdate, }, { - Pattern:"/goku-check_update",HandlerFunc: gokuCheckUpdate}, + Pattern: "/goku-check_update", HandlerFunc: gokuCheckUpdate}, { - Pattern:"/goku-check_plugin" , HandlerFunc:gokuCheckPlugin}, + Pattern: "/goku-check_plugin", HandlerFunc: gokuCheckPlugin}, { - Pattern:"/goku-monitor",HandlerFunc:gokuMonitor}, + Pattern: "/goku-monitor", HandlerFunc: gokuMonitor}, } } diff --git a/goku-node/handler/plugin.go b/goku-node/handler/plugin.go index c73c361021fecae2fe1d42fe28acffa61ecb4253..e709b92f92c64181490090b935efd81add62e242 100644 --- a/goku-node/handler/plugin.go +++ b/goku-node/handler/plugin.go @@ -8,7 +8,7 @@ import ( "net/http" ) -func gokuCheckPlugin( w http.ResponseWriter,req *http.Request) { +func gokuCheckPlugin(w http.ResponseWriter, req *http.Request) { req.ParseForm() pluginName := req.PostFormValue("pluginName") diff --git a/goku-node/handler/update.go b/goku-node/handler/update.go index 8dbbaa4f5eba042e8e0f49fc60b61d5add26a269..b4efd1ba282a2939abe5767c8ae0c84b9bebe40f 100644 --- a/goku-node/handler/update.go +++ b/goku-node/handler/update.go @@ -2,12 +2,11 @@ package handler import ( "encoding/json" - . "github.com/eolinker/goku/common/version" "github.com/eolinker/goku/goku-node/manager/updater" "net/http" ) -func gokuUpdate(w http.ResponseWriter, r *http.Request) { +func gokuUpdate(w http.ResponseWriter, r *http.Request) { updater.Update() } func gokuCheckUpdate(w http.ResponseWriter, r *http.Request) { @@ -21,4 +20,4 @@ func gokuCheckUpdate(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) _, _ = w.Write(resultStr) return -} \ No newline at end of file +} diff --git a/goku-node/manager/balance-manager/balance.go b/goku-node/manager/balance-manager/balance.go index 3e4cd15d944f5a3e66039142a4c1187aaa2c5e82..e6c411e318ba04e7133f220dedc08ee22e14c3da 100644 --- a/goku-node/manager/balance-manager/balance.go +++ b/goku-node/manager/balance-manager/balance.go @@ -47,7 +47,7 @@ func genBalance(e *entity.Balance) *balance.Balance { b.AppConfig = e.Static if err := json.Unmarshal([]byte(e.StaticCluster), &m); err == nil { if v, has := m[node_common.ClusterName()]; has { - if len(strings.Trim(v, " "))>0{ + if len(strings.Trim(v, " ")) > 0 { b.AppConfig = v } } diff --git a/goku-node/manager/config-manager/field.go b/goku-node/manager/config-manager/field.go index cd55239003dbf16b3405033876b250d2d608ce72..b02543213a006b47de95888cda701a30fcd02584 100644 --- a/goku-node/manager/config-manager/field.go +++ b/goku-node/manager/config-manager/field.go @@ -1,7 +1,6 @@ package config_manager - type AccessField struct { - Name string `json:"name"` - Select bool `json:"select"` -} \ No newline at end of file + Name string `json:"name"` + Select bool `json:"select"` +} diff --git a/goku-node/manager/config-manager/log.go b/goku-node/manager/config-manager/log.go index 1074741279c65a5214f4f6f0006d60d5e33a4f4a..918bba07effcc2761876fcb2f11c4b56ff7bfca7 100644 --- a/goku-node/manager/config-manager/log.go +++ b/goku-node/manager/config-manager/log.go @@ -11,14 +11,14 @@ import ( ) const ( - AccessLog = "access" - NodeLog = "node" + AccessLog = "access" + NodeLog = "node" ) func init() { - updater.Add(reloadLogConfig,1, "goku_config_log") + updater.Add(reloadLogConfig, 1, "goku_config_log") } -func defaultAccessLogConfig()*entity.LogConfig { +func defaultAccessLogConfig() *entity.LogConfig { return &entity.LogConfig{ Name: AccessLog, Enable: 1, @@ -29,7 +29,7 @@ func defaultAccessLogConfig()*entity.LogConfig { Fields: "", } } -func defaultNodeAppLogConfig()*entity.LogConfig { +func defaultNodeAppLogConfig() *entity.LogConfig { return &entity.LogConfig{ Name: AccessLog, Enable: 1, @@ -37,74 +37,72 @@ func defaultNodeAppLogConfig()*entity.LogConfig { File: "node.log", Level: "error", Period: "hour", - } } -func InitLog() { +func InitLog() { reloadLogConfig() } -func reloadLogConfig() { +func reloadLogConfig() { reloadAppLog() reloadAccessLog() } -func reloadAppLog() { - c,e:= dao.Get(NodeLog) - if e!=nil{ - log.Warn("manager/config load goku_config_log fro node error:",e) +func reloadAppLog() { + c, e := dao.Get(NodeLog) + if e != nil { + log.Warn("manager/config load goku_config_log fro node error:", e) c = defaultNodeAppLogConfig() } - period,err:=log.ParsePeriod(c.Period) - if err!=nil{ + period, err := log.ParsePeriod(c.Period) + if err != nil { period = log.PeriodDay - log.Warn("manager/config unmarshal access log period failed for nod , use the default config:%s",e) + log.Warn("manager/config unmarshal access log period failed for nod , use the default config:%s", e) } - level,err:= log.ParseLevel(c.Level) - if err!=nil{ + level, err := log.ParseLevel(c.Level) + if err != nil { level = log.WarnLevel - log.Warn("manager/config unmarshal access log level failed for nod , use the default config:%s",e) + log.Warn("manager/config unmarshal access log level failed for nod , use the default config:%s", e) } - enable:= c.Enable == 1 - log.SetOutPut(enable,c.Dir,c.File,period,c.Expire) + enable := c.Enable == 1 + log.SetOutPut(enable, c.Dir, c.File, period, c.Expire) log.SetLevel(level) } -func reloadAccessLog() { +func reloadAccessLog() { c, e := dao.Get(AccessLog) - if e!=nil{ - log.Warn("manager/config load goku_config_log for access log error:",e) - c= defaultAccessLogConfig() + if e != nil { + log.Warn("manager/config load goku_config_log for access log error:", e) + c = defaultAccessLogConfig() } - period,err:=log.ParsePeriod(c.Period) - if err!=nil{ + period, err := log.ParsePeriod(c.Period) + if err != nil { period = log.PeriodDay - log.Warn("manager/config unmarshal period failed for , use the default config:%s",e) + log.Warn("manager/config unmarshal period failed for , use the default config:%s", e) } - enable:= c.Enable == 1 - + enable := c.Enable == 1 - fieldsConfig:= make([]AccessField ,0,access_field.Size()) - err =json.Unmarshal([]byte(c.Fields),&fieldsConfig) + fieldsConfig := make([]AccessField, 0, access_field.Size()) + err = json.Unmarshal([]byte(c.Fields), &fieldsConfig) - if err!= nil || len(fieldsConfig) == 0{ - log.Warn("manager/config unmarshal access log fields error:",err) + if err != nil || len(fieldsConfig) == 0 { + log.Warn("manager/config unmarshal access log fields error:", err) access_log.SetFields(access_field.Default()) - }else{ - fields:=make([]access_field.AccessFieldKey,0,access_field.Size()) - for _,f:=range fieldsConfig{ - if f.Select{ - if access_field.Has(f.Name){ - fields = append(fields,access_field.Parse(f.Name)) + } else { + fields := make([]access_field.AccessFieldKey, 0, access_field.Size()) + for _, f := range fieldsConfig { + if f.Select { + if access_field.Has(f.Name) { + fields = append(fields, access_field.Parse(f.Name)) } } } access_log.SetFields(fields) } - access_log.SetOutput( enable,c.Dir,c.File,period,c.Expire) + access_log.SetOutput(enable, c.Dir, c.File, period, c.Expire) -} \ No newline at end of file +} diff --git a/goku-node/manager/plugin-manager/pluginload.go b/goku-node/manager/plugin-manager/pluginload.go index 037451b8d7f873dd458fbd1126a8c75a551be452..18f892518fdafe4e4a4f82b3bc7ea3cf4a8ffbf1 100644 --- a/goku-node/manager/plugin-manager/pluginload.go +++ b/goku-node/manager/plugin-manager/pluginload.go @@ -68,7 +68,7 @@ func LoadPlugin(pis map[string]*entity.PluginInfo) (allFactory map[string]*entit for key, value := range pis { handle, err, _ := globalPluginManager.loadPlugin(key) if err != nil { - goku_plugin.Warn("LoadPlugin:",err.Error()) + goku_plugin.Warn("LoadPlugin:", err.Error()) continue } factory := &entity.PluginFactoryHandler{ @@ -144,14 +144,14 @@ func (m *_GlodPluginManager) loadPlugin(name string) (goku_plugin.PluginFactory, vp, ok := v.(func() goku_plugin.PluginFactory) if !ok { - e := fmt.Errorf("The builder func can not implemented interface named goku_plugin.PluginFactory:%s ",name) + e := fmt.Errorf("The builder func can not implemented interface named goku_plugin.PluginFactory:%s ", name) m.errors[name] = e m.errorCodes[name] = LoadInterFaceError return nil, e, LoadInterFaceError } factory := vp() if factory == nil || reflect.ValueOf(factory).IsNil() { - e := fmt.Errorf("The builder result is nil:%s ",name) + e := fmt.Errorf("The builder result is nil:%s ", name) m.errors[name] = e m.errorCodes[name] = LoadInterFaceError return nil, e, LoadInterFaceError diff --git a/goku-node/manager/service-manager/service.go b/goku-node/manager/service-manager/service.go index 75ce18aadee7245c33f0c139e37ce81d929b1314..5b01d541e4735fc47d3400a80fb757958d02aca8 100644 --- a/goku-node/manager/service-manager/service.go +++ b/goku-node/manager/service-manager/service.go @@ -51,7 +51,7 @@ func toDiscoverConfig(e *entity.Service) *discovery.Config { clusterName := node_common.ClusterName() if v, has := clusterConfigObj[clusterName]; has { - if len(strings.Trim(v, " "))>0{ + if len(strings.Trim(v, " ")) > 0 { c.Config = v } } diff --git a/goku-node/manager/strategy-api-manager/match.go b/goku-node/manager/strategy-api-manager/match.go index 9bc8bffae44d82e0fd2fc3e166490e2ea2c4d0ef..08213c41feb793198f8d7935c2125c125c1e3fdf 100644 --- a/goku-node/manager/strategy-api-manager/match.go +++ b/goku-node/manager/strategy-api-manager/match.go @@ -36,7 +36,7 @@ func CheckApiFromStrategy(strategyId, requestPath string, requestMethod string) apiextend.Target = apiInfo.BalanceName } - apiextend.Target = utils.TrimSuffixAll(apiextend.Target,"/") + apiextend.Target = utils.TrimSuffixAll(apiextend.Target, "/") //apiextend.TargetServer = balance_manager.ParseTargetServer(apiextend.Target) return apiextend, splitURL, param, true diff --git a/goku-node/node-common/constant.go b/goku-node/node-common/constant.go index e132d35da4a9b91e629852337e491b46c3a9dcdd..144260c526b258d806d66f6c42e9f883d4d85b9f 100644 --- a/goku-node/node-common/constant.go +++ b/goku-node/node-common/constant.go @@ -19,11 +19,11 @@ func ClusterName() string { } func SetAdmin(host string) { - h:= strings.TrimPrefix(host,"http://") - h = strings.TrimSuffix(h,"/") + h := strings.TrimPrefix(host, "http://") + h = strings.TrimSuffix(h, "/") adminUrl = fmt.Sprintf("http://%s", h) } func GetAdminUrl(path string) string { - p:=strings.TrimPrefix(path,"/") + p := strings.TrimPrefix(path, "/") return fmt.Sprintf("%s/%s", adminUrl, p) } diff --git a/goku-node/plugin-flow/access.go b/goku-node/plugin-flow/access.go index b9cfc6f93fd78357dd1e8f05b898220fb20b0cd7..16fec284e0c48fad6342a29ecff24d26d07c8540 100644 --- a/goku-node/plugin-flow/access.go +++ b/goku-node/plugin-flow/access.go @@ -8,6 +8,7 @@ import ( "reflect" "time" ) + var ( authNames = map[string]string{ "Oauth2": "goku-oauth2_auth", @@ -23,40 +24,37 @@ var ( } ) - - func getPluginNameByType(authType string) (string, bool) { name, has := authNames[authType] return name, has } - // 执行插件的Access函数 func AccessFunc(ctx *common.Context, handleFunc []*entity.PluginHandlerExce) (bool, int) { requestId := ctx.RequestId() authType := ctx.Request().GetHeader("Authorization-Type") authName, _ := getPluginNameByType(authType) defer func(ctx *common.Context) { - log.Debug(requestId," access plugin default: begin") + log.Debug(requestId, " access plugin default: begin") for _, handler := range plugin_manager.GetDefaultPlugins() { - if handler.PluginObj.Access==nil || reflect.ValueOf(handler.PluginObj.Access).IsNil() { + if handler.PluginObj.Access == nil || reflect.ValueOf(handler.PluginObj.Access).IsNil() { continue } ctx.SetPlugin(handler.Name) - log.Info(requestId," access plugin:",handler.Name) - now:=time.Now() - _, err:=handler.PluginObj.Access.Access(ctx) - log.Debug(requestId," access plugin:",handler.Name," Duration",time.Since(now)) - if err!=nil{ - log.Warn(requestId," access plugin:",handler.Name," error:",err.Error()) + log.Info(requestId, " access plugin:", handler.Name) + now := time.Now() + _, err := handler.PluginObj.Access.Access(ctx) + log.Debug(requestId, " access plugin:", handler.Name, " Duration", time.Since(now)) + if err != nil { + log.Warn(requestId, " access plugin:", handler.Name, " error:", err.Error()) } } - log.Debug(requestId," access plugin default: end") + log.Debug(requestId, " access plugin default: end") }(ctx) isAuthSucess := false isNeedAuth := false - log.Debug(requestId," access plugin auth check: begin") + log.Debug(requestId, " access plugin auth check: begin") for _, handler := range handleFunc { if _, has := authPluginNames[handler.Name]; has { isNeedAuth = true @@ -67,33 +65,33 @@ func AccessFunc(ctx *common.Context, handleFunc []*entity.PluginHandlerExce) (bo continue } ctx.SetPlugin(handler.Name) - log.Debug(requestId," access plugin:",handler.Name," begin") - now:=time.Now() + log.Debug(requestId, " access plugin:", handler.Name, " begin") + now := time.Now() flag, err := handler.PluginObj.Access.Access(ctx) - log.Debug(requestId," access plugin:",handler.Name," Duration",time.Since(now)) + log.Debug(requestId, " access plugin:", handler.Name, " Duration", time.Since(now)) if flag == false { // 校验失败 if err != nil { - log.Warn(requestId," access auth:[",handler.Name,"] error:",err.Error()) + log.Warn(requestId, " access auth:[", handler.Name, "] error:", err.Error()) } - log.Info(requestId," auth [",authName,"] refuse") + log.Info(requestId, " auth [", authName, "] refuse") return false, 0 } - log.Debug(requestId," auth [",authName,"] pass") + log.Debug(requestId, " auth [", authName, "] pass") isAuthSucess = true } } - log.Debug(requestId," access plugin auth check: end") + log.Debug(requestId, " access plugin auth check: end") // 需要校验但是没有执行校验 if isNeedAuth && !isAuthSucess { - log.Warn(requestId," Illegal authorization type:",authType) + log.Warn(requestId, " Illegal authorization type:", authType) ctx.SetStatus(403, "403") ctx.SetBody([]byte("[ERROR]Illegal authorization type!")) return false, 0 } lastIndex := 0 - log.Debug(requestId," access plugin : begin") + log.Debug(requestId, " access plugin : begin") // 执行校验以外的插件 for index, handler := range handleFunc { lastIndex = index @@ -106,19 +104,19 @@ func AccessFunc(ctx *common.Context, handleFunc []*entity.PluginHandlerExce) (bo } ctx.SetPlugin(handler.Name) - log.Debug(requestId," access plugin:",handler.Name) - now:=time.Now() + log.Debug(requestId, " access plugin:", handler.Name) + now := time.Now() flag, err := handler.PluginObj.Access.Access(ctx) - log.Debug(requestId," access plugin:",handler.Name," Duration:",time.Since(now)) + log.Debug(requestId, " access plugin:", handler.Name, " Duration:", time.Since(now)) if err != nil { - log.Warn(requestId," access plugin:",handler.Name," error:",err.Error()) + log.Warn(requestId, " access plugin:", handler.Name, " error:", err.Error()) } if flag == false && handler.IsStop { - log.Info(requestId," access plugin:",handler.Name," stop") + log.Info(requestId, " access plugin:", handler.Name, " stop") return false, index } - log.Debug(requestId," access plugin:",handler.Name," continue") + log.Debug(requestId, " access plugin:", handler.Name, " continue") } - log.Debug(requestId," access plugin : end") + log.Debug(requestId, " access plugin : end") return true, lastIndex -} \ No newline at end of file +} diff --git a/goku-node/plugin-flow/before.go b/goku-node/plugin-flow/before.go index 8b73bfe9aae775d6c614a58a17874edc624fad78..440f8e22e074622318c90e6883afa56edea67c61 100644 --- a/goku-node/plugin-flow/before.go +++ b/goku-node/plugin-flow/before.go @@ -12,24 +12,24 @@ import ( func BeforeMatch(ctx *common.Context) bool { requestId := ctx.RequestId() defer func(ctx *common.Context) { - log.Debug(requestId," before plugin default: begin") + log.Debug(requestId, " before plugin default: begin") for _, handler := range plugin_manager.GetDefaultPlugins() { if handler.PluginObj.BeforeMatch == nil || reflect.ValueOf(handler.PluginObj.BeforeMatch).IsNil() { continue } ctx.SetPlugin(handler.Name) - log.Debug(requestId," before plugin :",handler.Name," start") - now:=time.Now() - _,err:=handler.PluginObj.BeforeMatch.BeforeMatch(ctx) - log.Debug(requestId," before plugin :",handler.Name," Duration:",time.Since(now)) - log.Debug(requestId," before plugin :",handler.Name," end") + log.Debug(requestId, " before plugin :", handler.Name, " start") + now := time.Now() + _, err := handler.PluginObj.BeforeMatch.BeforeMatch(ctx) + log.Debug(requestId, " before plugin :", handler.Name, " Duration:", time.Since(now)) + log.Debug(requestId, " before plugin :", handler.Name, " end") if err != nil { - log.Warn(requestId," before plugin:",handler.Name," error:",err.Error()) + log.Warn(requestId, " before plugin:", handler.Name, " error:", err.Error()) } } - log.Debug(requestId," before plugin default: end") + log.Debug(requestId, " before plugin default: end") }(ctx) - log.Debug(requestId," before plugin : begin") + log.Debug(requestId, " before plugin : begin") for _, handler := range plugin_manager.GetBeforPlugins() { if handler.PluginObj.BeforeMatch == nil || reflect.ValueOf(handler.PluginObj.BeforeMatch).IsNil() { @@ -37,14 +37,14 @@ func BeforeMatch(ctx *common.Context) bool { } ctx.SetPlugin(handler.Name) - log.Debug(requestId," before plugin :",handler.Name," start") - now:=time.Now() + log.Debug(requestId, " before plugin :", handler.Name, " start") + now := time.Now() flag, err := handler.PluginObj.BeforeMatch.BeforeMatch(ctx) - log.Debug(requestId," before plugin :",handler.Name," Duration:",time.Since(now)) - log.Debug(requestId," before plugin :",handler.Name," end") + log.Debug(requestId, " before plugin :", handler.Name, " Duration:", time.Since(now)) + log.Debug(requestId, " before plugin :", handler.Name, " end") if err != nil { - log.Warn(requestId," before plugin:",handler.Name," error:",err.Error()) + log.Warn(requestId, " before plugin:", handler.Name, " error:", err.Error()) } if flag == false { if handler.IsStop == true { @@ -52,6 +52,6 @@ func BeforeMatch(ctx *common.Context) bool { } } } - log.Debug(requestId," before plugin : end") + log.Debug(requestId, " before plugin : end") return true -} \ No newline at end of file +} diff --git a/goku-node/plugin-flow/proxy.go b/goku-node/plugin-flow/proxy.go index 8ea6892b24dbe53c6cb46cd2a1c94e101f3d1433..ddc9b7f32bfd7f3914c56360de3c2fec54ab0852 100644 --- a/goku-node/plugin-flow/proxy.go +++ b/goku-node/plugin-flow/proxy.go @@ -14,26 +14,26 @@ import ( func ProxyFunc(ctx *common.Context, handleFunc []*entity.PluginHandlerExce) (bool, int) { requestId := ctx.RequestId() defer func(ctx *common.Context) { - log.Debug(requestId," Proxy plugin default: begin") + log.Debug(requestId, " Proxy plugin default: begin") for _, handler := range plugin_manager.GetDefaultPlugins() { if handler.PluginObj.Proxy == nil || reflect.ValueOf(handler.PluginObj.Proxy).IsNil() { continue } ctx.SetPlugin(handler.Name) - log.Debug(requestId," Proxy plugin :",handler.Name," start") - now:=time.Now() - _, err:= handler.PluginObj.Proxy.Proxy(ctx) - log.Debug(requestId," Proxy plugin :",handler.Name," Duration:",time.Since(now)) - log.Debug(requestId," Proxy plugin :",handler.Name," end") + log.Debug(requestId, " Proxy plugin :", handler.Name, " start") + now := time.Now() + _, err := handler.PluginObj.Proxy.Proxy(ctx) + log.Debug(requestId, " Proxy plugin :", handler.Name, " Duration:", time.Since(now)) + log.Debug(requestId, " Proxy plugin :", handler.Name, " end") if err != nil { - log.Warn(requestId," Proxy plugin:",handler.Name," error:",err.Error()) + log.Warn(requestId, " Proxy plugin:", handler.Name, " error:", err.Error()) } } - log.Debug(requestId," Proxy plugin default: begin") + log.Debug(requestId, " Proxy plugin default: begin") }(ctx) lastIndex := 0 - log.Debug(requestId," Proxy plugin : begin") + log.Debug(requestId, " Proxy plugin : begin") for index, handler := range handleFunc { lastIndex = index if handler.PluginObj.Proxy == nil || reflect.ValueOf(handler.PluginObj.Proxy).IsNil() { @@ -41,21 +41,20 @@ func ProxyFunc(ctx *common.Context, handleFunc []*entity.PluginHandlerExce) (boo } ctx.SetPlugin(handler.Name) - log.Debug(requestId," Proxy plugin :",handler.Name," start") - now:=time.Now() + log.Debug(requestId, " Proxy plugin :", handler.Name, " start") + now := time.Now() flag, err := handler.PluginObj.Proxy.Proxy(ctx) - log.Debug(requestId," Proxy plugin :",handler.Name," Duration:",time.Since(now)) - log.Debug(requestId," Proxy plugin :",handler.Name," end") + log.Debug(requestId, " Proxy plugin :", handler.Name, " Duration:", time.Since(now)) + log.Debug(requestId, " Proxy plugin :", handler.Name, " end") if err != nil { - log.Warn(requestId," Proxy plugin :",handler.Name," error: ",err.Error()) + log.Warn(requestId, " Proxy plugin :", handler.Name, " error: ", err.Error()) } if flag == false && handler.IsStop == true { return false, lastIndex } } - log.Debug(requestId," Proxy plugin : end") + log.Debug(requestId, " Proxy plugin : end") return true, lastIndex } - diff --git a/goku-node/request_mapping.go b/goku-node/request_mapping.go index a627012b92ff0265f10d35c90e58de79d8f8d743..a15717a1438c900aa97d3d85f273942b4f4aa7df 100644 --- a/goku-node/request_mapping.go +++ b/goku-node/request_mapping.go @@ -14,23 +14,23 @@ import ( ) // 创建转发请求 -func CreateRequest(ctx *common.Context, apiInfo *entity.ApiExtend, timeout, retry int) ( error, *http.Response) { +func CreateRequest(ctx *common.Context, apiInfo *entity.ApiExtend, timeout, retry int) (error, *http.Response) { - app,has:=balance_manager.Get(apiInfo.Target) - if !has{ - err:= fmt.Errorf("get balance error:%s",apiInfo.Target) - return err,nil + app, has := balance_manager.Get(apiInfo.Target) + if !has { + err := fmt.Errorf("get balance error:%s", apiInfo.Target) + return err, nil } rawbody, _ := ctx.ProxyRequest.RawBody() - response,finalTargetServer,retryTargetServers,err:=app.Send(apiInfo.Protocol,ctx.ProxyRequest.Method,ctx.ProxyRequest.TargetURL(),ctx.ProxyRequest.Querys(),ctx.ProxyRequest.Headers() ,rawbody,time.Duration(timeout)*time.Millisecond,retry) + response, finalTargetServer, retryTargetServers, err := app.Send(apiInfo.Protocol, ctx.ProxyRequest.Method, ctx.ProxyRequest.TargetURL(), ctx.ProxyRequest.Querys(), ctx.ProxyRequest.Headers(), rawbody, time.Duration(timeout)*time.Millisecond, retry) ctx.SetRetryTargetServers(strings.Join(retryTargetServers, ",")) ctx.SetFinalTargetServer(finalTargetServer) - if err!= nil{ - return err,nil + if err != nil { + return err, nil } - return nil,response + return nil, response } diff --git a/goku-node/router.go b/goku-node/router.go index 147325df6c2af86ae2e9f483ab166aff4b981a0e..6b1dc485259425fded3e088fb2f7087ff34d54bf 100644 --- a/goku-node/router.go +++ b/goku-node/router.go @@ -7,7 +7,6 @@ import ( access_log "github.com/eolinker/goku/goku-node/access-log" "github.com/eolinker/goku/goku-node/handler" "github.com/eolinker/goku/goku-node/plugin-flow" - . "github.com/eolinker/goku/server/access-field" "net/http" "strconv" "strings" @@ -30,7 +29,7 @@ type Router struct { mu map[string]http.HandlerFunc } -func (mux*Router) ServeHTTP(w http.ResponseWriter, r*http.Request) { +func (mux *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.RequestURI == "*" { if r.ProtoAtLeast(1, 1) { w.Header().Set("Connection", "close") @@ -38,72 +37,69 @@ func (mux*Router) ServeHTTP(w http.ResponseWriter, r*http.Request) { w.WriteHeader(http.StatusBadRequest) return } - path:=r.URL.Path - h, has:= mux.mu[path] - if has{ + path := r.URL.Path + h, has := mux.mu[path] + if has { h.ServeHTTP(w, r) return } - ServeHTTP(w,r) + ServeHTTP(w, r) } func NewRouter() http.Handler { - r:=&Router{ - mu :make(map[string]http.HandlerFunc), + r := &Router{ + mu: make(map[string]http.HandlerFunc), } + hs := handler.Handler() - hs:= handler.Handler() - - for _,h:=range hs{ + for _, h := range hs { r.mu[h.Pattern] = h.HandlerFunc } - return r + return r } var systemRequestPath = []string{"/oauth2/token", "/oauth2/authorize", "/oauth2/verify"} -func ServeHTTP(w http.ResponseWriter, req *http.Request) { +func ServeHTTP(w http.ResponseWriter, req *http.Request) { defer func() { if err := recover(); err != nil { log.Warn(err) } }() + timeStart := time.Now() - timeStart:=time.Now() - - logFields:=make(log.Fields) + logFields := make(log.Fields) // 记录访问次数 requestID := GetRandomString(16) - ctx := common.NewContext(req, requestID, w) proxyStatusCode := 0 - log.Debug(requestID," url: ",req.URL.String()) - log.Debug(requestID," header: ",ctx.RequestOrg.Header.String()) - rawBody ,err:=ctx.RequestOrg.RawBody() - if err==nil{ - log.Debug(requestID," body: ",string(rawBody)) - } + log.Debug(requestID, " url: ", req.URL.String()) + log.Debug(requestID, " header: ", ctx.RequestOrg.Header.String()) + rawBody, err := ctx.RequestOrg.RawBody() + if err == nil { + log.Debug(requestID, " body: ", string(rawBody)) + } defer func() { - n,status:=ctx.Finish() + n, status := ctx.Finish() if ctx.ProxyResponseHandler != nil { proxyStatusCode = ctx.ProxyResponseHandler.StatusCode() } - logFields[RequestId]= requestID + logFields[RequestId] = requestID logFields[StatusCode] = status - logFields[HttpUserAgent] = fmt.Sprint("\"",req.UserAgent(),"\"") + logFields[HttpUserAgent] = fmt.Sprint("\"", req.UserAgent(), "\"") logFields[HttpReferer] = req.Referer() logFields[RequestTime] = time.Since(timeStart) - logFields[Request] = fmt.Sprint("\"",req.Method," ",req.URL.Path," ",req.Proto,"\"") + logFields[Request] = fmt.Sprint("\"", req.Method, " ", req.URL.Path, " ", req.Proto, "\"") logFields[BodyBytesSent] = n logFields[Host] = req.Host access_log.Log(logFields) @@ -120,12 +116,12 @@ func ServeHTTP(w http.ResponseWriter, req *http.Request) { }() remoteAddr := Intercept(req.RemoteAddr, ":") - logFields[RemoteAddr]= remoteAddr + logFields[RemoteAddr] = remoteAddr - if realIp := ctx.GetHeader("X-Real-Ip") ;realIp == ""{ + if realIp := ctx.GetHeader("X-Real-Ip"); realIp == "" { ctx.ProxyRequest.SetHeader("X-Real-Ip", remoteAddr) logFields[HttpXForwardedFor] = remoteAddr - }else{ + } else { logFields[HttpXForwardedFor] = realIp } @@ -133,21 +129,20 @@ func ServeHTTP(w http.ResponseWriter, req *http.Request) { var isBefor bool start := time.Now() isBefor = plugin_flow.BeforeMatch(ctx) - log.Info(requestID," BeforeMatch plugin duration:",time.Since(start)) + log.Info(requestID, " BeforeMatch plugin duration:", time.Since(start)) if !isBefor { - log.Info(requestID," stop by BeforeMatch plugin") + log.Info(requestID, " stop by BeforeMatch plugin") return } var timeout, retryCount int - strategyID, ok := retrieveStrategyID(ctx) if !ok { return } - logFields[Strategy] = fmt.Sprintf("\"%s %s\"", strategyID,ctx.StrategyName()) + logFields[Strategy] = fmt.Sprintf("\"%s %s\"", strategyID, ctx.StrategyName()) requestPath := req.URL.Path requestMenthod := ctx.Request().Method() @@ -160,7 +155,6 @@ func ServeHTTP(w http.ResponseWriter, req *http.Request) { //ctx.IsMatch = true timeout = apiInfo.Timeout - ctx.ProxyRequest.SetTargetServer(fmt.Sprintf("%s://%s", apiInfo.Protocol, apiInfo.Target)) targetUrl := apiInfo.TargetURL + requestPath @@ -185,7 +179,7 @@ func ServeHTTP(w http.ResponseWriter, req *http.Request) { } start = time.Now() isAccess, _ := plugin_flow.AccessFunc(ctx, handleFunc) - log.Info(requestID," Access plugin duration:",time.Since(start)) + log.Info(requestID, " Access plugin duration:", time.Since(start)) if !isAccess { // todo @@ -193,20 +187,20 @@ func ServeHTTP(w http.ResponseWriter, req *http.Request) { } if apiInfo == nil { - log.Info(requestID," URL dose not exist!") + log.Info(requestID, " URL dose not exist!") ctx.SetStatus(404, "404") ctx.SetBody([]byte("[ERROR]URL dose not exist!")) - + return } - logFields[Api] = fmt.Sprintf("\"%d %s\"",apiInfo.ApiID,apiInfo.ApiName) - logFields[Proxy] = fmt.Sprintf("\"%s %s %s\"",ctx.ProxyRequest.Method,ctx.ProxyRequest.TargetURL(),apiInfo.Protocol) + logFields[Api] = fmt.Sprintf("\"%d %s\"", apiInfo.ApiID, apiInfo.ApiName) + logFields[Proxy] = fmt.Sprintf("\"%s %s %s\"", ctx.ProxyRequest.Method, ctx.ProxyRequest.TargetURL(), apiInfo.Protocol) logFields[Balance] = apiInfo.Target start = time.Now() err, response := CreateRequest(ctx, apiInfo, timeout, retryCount) - log.Info(requestID," Proxy request duration:",time.Since(start)) + log.Info(requestID, " Proxy request duration:", time.Since(start)) if err != nil { - log.Warn(err.Error()) + log.Warn(err.Error()) } logFields[FinallyServer] = ctx.FinalTargetServer() logFields[Retry] = ctx.RetryTargetServers() @@ -243,7 +237,7 @@ func ServeHTTP(w http.ResponseWriter, req *http.Request) { start = time.Now() isProxy, _ := plugin_flow.ProxyFunc(ctx, handleFunc) - log.Info(requestID," Proxy plugin Duration:",time.Since(start)) + log.Info(requestID, " Proxy plugin Duration:", time.Since(start)) if !isProxy { return } diff --git a/goku-node/server.go b/goku-node/server.go index 90f0fde327c16af7311cf33b74190dbf75d2a1e0..ca188eeaaa7e16c9131cb23ab5159391c5caf3d1 100644 --- a/goku-node/server.go +++ b/goku-node/server.go @@ -14,8 +14,6 @@ import ( "strings" ) - - func InitPluginUtils() { goku_plugin.SetRedisManager(redis_plugin_proxy.Create()) goku_plugin.InitLog(log.GetLogger()) @@ -26,10 +24,10 @@ func InitDiscovery() { all := discovery.AllDrivers() log.Infof("install service discovery driver:[%s]\n", strings.Join(all, ",")) } -func InitLog() { +func InitLog() { config_manager.InitLog() } -func InitServer(){ +func InitServer() { log.Debug("init InitServer start") InitPluginUtils() diff --git a/goku-node/utils.go b/goku-node/utils.go index ff086009cf6d8ae5ba9e456646471edb9091f1de..c94353a2a9736dce67d41384600a07caefe20f4f 100644 --- a/goku-node/utils.go +++ b/goku-node/utils.go @@ -51,4 +51,3 @@ func PanicTrace(kb int) []byte { stack = bytes.TrimRight(stack, "\n") return stack } - diff --git a/goku-node/visit/visit.go b/goku-node/visit/visit.go index 56646a21d6b6ffc5b2886b1594b34cb6b1813778..a95011f3de7cd7459bf0d090977a350f52940604 100644 --- a/goku-node/visit/visit.go +++ b/goku-node/visit/visit.go @@ -225,23 +225,23 @@ func UpdateProxyFailureCount(apiInfo *entity.ApiExtend, // 记录告警日志 func AlertLog(requestURL, targetServer, targetURL, requestMethod, proxyMethod, headerList, queryParamList, formParamList, responseHeaderList string, responseStatus int, strategyID string, strategyName, requestID string) { - log.WithFields(log.Fields{ - "request_id":requestID, - "strategy_name":strategyName, - "strategy_id":strategyID, - "request_method":requestMethod, - "request_url":requestURL, - "target_method":proxyMethod, - "target_server":targetServer, - "target_url":targetURL, - "request_query":queryParamList, - "request_header":headerList, - "request_form_param":formParamList, - "response_statusCode":strconv.Itoa(responseStatus), - "response_header":responseHeaderList, + log.WithFields(log.Fields{ + "request_id": requestID, + "strategy_name": strategyName, + "strategy_id": strategyID, + "request_method": requestMethod, + "request_url": requestURL, + "target_method": proxyMethod, + "target_server": targetServer, + "target_url": targetURL, + "request_query": queryParamList, + "request_header": headerList, + "request_form_param": formParamList, + "response_statusCode": strconv.Itoa(responseStatus), + "response_header": responseHeaderList, }).Warning("alert") - //_= logutils.Log("log/alertLog", "alert", log.PeriodDay, logInfo) + //_= logutils.Log("log/alertLog", "alert", log.PeriodDay, logInfo) return } diff --git a/goku-service/application/application.go b/goku-service/application/application.go index 7c8167a32fb1148657793a53ac65d8b259c9c0b4..d169a52b426ac2df968b79d63aa29ed10b9a7f46 100644 --- a/goku-service/application/application.go +++ b/goku-service/application/application.go @@ -7,5 +7,5 @@ import ( ) type IHttpApplication interface { - Send(Proto string, method string,path string,querys url.Values,header http.Header,body []byte,timeout time.Duration,retry int)(*http.Response,string,[]string,error) + Send(Proto string, method string, path string, querys url.Values, header http.Header, body []byte, timeout time.Duration, retry int) (*http.Response, string, []string, error) } diff --git a/goku-service/application/org.go b/goku-service/application/org.go index a80c5cc09eccd7ccb8b3bb90c4c87ca9b2046a77..77c8ddec2fd972b5f22ad12fa06b262771d4ac57 100644 --- a/goku-service/application/org.go +++ b/goku-service/application/org.go @@ -11,36 +11,36 @@ import ( type Org struct { server string } -// 忽略重试 -func (app *Org) Send(proto string,method string, path string,querys url.Values, header http.Header, body []byte,timeout time.Duration, retry int) (*http.Response,string,[]string,error) { +// 忽略重试 +func (app *Org) Send(proto string, method string, path string, querys url.Values, header http.Header, body []byte, timeout time.Duration, retry int) (*http.Response, string, []string, error) { var response *http.Response = nil var err error = nil FinalTargetServer := "" - RetryTargetServers :=make([]string,0,retry+1) + RetryTargetServers := make([]string, 0, retry+1) - path = utils.TrimPrefixAll(path,"/") + path = utils.TrimPrefixAll(path, "/") - for doTrice := retry +1;doTrice>0;doTrice--{ + for doTrice := retry + 1; doTrice > 0; doTrice-- { - u:= fmt.Sprintf("%s://%s/%s",proto,app.server,path) + u := fmt.Sprintf("%s://%s/%s", proto, app.server, path) FinalTargetServer = app.server - RetryTargetServers = append(RetryTargetServers,FinalTargetServer) - response,err =request(method,u,querys,header,body,timeout) - if err != nil{ - continue - }else{ - return response,FinalTargetServer,RetryTargetServers,err + RetryTargetServers = append(RetryTargetServers, FinalTargetServer) + response, err = request(method, u, querys, header, body, timeout) + if err != nil { + continue + } else { + return response, FinalTargetServer, RetryTargetServers, err } } - return response,FinalTargetServer,RetryTargetServers,err + return response, FinalTargetServer, RetryTargetServers, err } -func NewOrg(server string)IHttpApplication { +func NewOrg(server string) IHttpApplication { return &Org{ - server:server, + server: server, } -} \ No newline at end of file +} diff --git a/goku-service/application/r.go b/goku-service/application/r.go index 088910a9d28b0eaaf69516503c024824925ea525..902ca73c6f65f581f674ef4401b1430d41282aec 100644 --- a/goku-service/application/r.go +++ b/goku-service/application/r.go @@ -7,36 +7,30 @@ import ( "time" ) -func request(method string, backendDomain string,query url.Values, header http.Header, body []byte,timeout time.Duration) (*http.Response,error) { - - +func request(method string, backendDomain string, query url.Values, header http.Header, body []byte, timeout time.Duration) (*http.Response, error) { if backendDomain == "" { - return nil,fmt.Errorf("invaild url") + return nil, fmt.Errorf("invaild url") } u, err := url.ParseRequestURI(backendDomain) if err != nil { - return nil, err } req, err := NewRequest(method, u) if err != nil { - return nil,err + return nil, err } - req.headers = header - - - req.queryParams = query - + req.headers = header + req.queryParams = query req.SetRawBody(body) if timeout != 0 { req.SetTimeout(timeout) } - return req.Send() -} \ No newline at end of file + return req.Send() +} diff --git a/goku-service/application/service.go b/goku-service/application/service.go index 788b6d7e946fc529ef87693346df4df664e5dd72..7cbafc386cd718840dc9bb4f44d1713cf9778417 100644 --- a/goku-service/application/service.go +++ b/goku-service/application/service.go @@ -11,50 +11,48 @@ import ( ) type Application struct { - service *common.Service + service *common.Service healthCheckHandler health.CheckHandler } -func NewApplication(service *common.Service,healthCheckHandler health.CheckHandler) *Application { +func NewApplication(service *common.Service, healthCheckHandler health.CheckHandler) *Application { return &Application{ service: service, healthCheckHandler: healthCheckHandler, } } -func (app *Application) Send(proto string,method string, path string,querys url.Values, header http.Header, body []byte,timeout time.Duration, retry int)( *http.Response,string,[]string,error) { - +func (app *Application) Send(proto string, method string, path string, querys url.Values, header http.Header, body []byte, timeout time.Duration, retry int) (*http.Response, string, []string, error) { var response *http.Response = nil var err error = nil FinalTargetServer := "" - RetryTargetServers :=make([]string,0,retry+1) + RetryTargetServers := make([]string, 0, retry+1) lastIndex := -1 - path = utils.TrimPrefixAll(path,"/") - for doTrice := retry +1;doTrice>0;doTrice--{ - instance,index,has:=app.service.Next(lastIndex) + path = utils.TrimPrefixAll(path, "/") + for doTrice := retry + 1; doTrice > 0; doTrice-- { + instance, index, has := app.service.Next(lastIndex) lastIndex = index - if !has{ - return nil,FinalTargetServer,RetryTargetServers,fmt.Errorf("not found instance for app:%s",app.service.Name) + if !has { + return nil, FinalTargetServer, RetryTargetServers, fmt.Errorf("not found instance for app:%s", app.service.Name) } - FinalTargetServer = fmt.Sprintf("%s:%d",instance.IP,instance.Port) - RetryTargetServers = append(RetryTargetServers,FinalTargetServer) - u:= fmt.Sprintf("%s://%s:%d/%s",proto,instance.IP,instance.Port,path) - response,err =request(method,u,querys,header,body,timeout) + FinalTargetServer = fmt.Sprintf("%s:%d", instance.IP, instance.Port) + RetryTargetServers = append(RetryTargetServers, FinalTargetServer) + u := fmt.Sprintf("%s://%s:%d/%s", proto, instance.IP, instance.Port, path) + response, err = request(method, u, querys, header, body, timeout) - if err != nil{ - if app.healthCheckHandler.IsNeedCheck(){ + if err != nil { + if app.healthCheckHandler.IsNeedCheck() { app.healthCheckHandler.Check(instance) } - }else{ - return response,FinalTargetServer,RetryTargetServers,err + } else { + return response, FinalTargetServer, RetryTargetServers, err } } - return response,FinalTargetServer,RetryTargetServers,err + return response, FinalTargetServer, RetryTargetServers, err } - diff --git a/goku-service/balance/balance.go b/goku-service/balance/balance.go index 1afb8c4acc963df0fd59358daac041d781531c7d..15fcfd68f4fad8ebf2378bf00d5a1fb17ffb82c8 100644 --- a/goku-service/balance/balance.go +++ b/goku-service/balance/balance.go @@ -5,5 +5,3 @@ type Balance struct { Discovery string AppConfig string } - - diff --git a/goku-service/balance/discovery.go b/goku-service/balance/discovery.go index 50193f08256c68feea4a88788d45d1266306b364..228cdaa031d511c3270119842cffbe25441e010f 100644 --- a/goku-service/balance/discovery.go +++ b/goku-service/balance/discovery.go @@ -5,11 +5,11 @@ import ( "github.com/eolinker/goku/goku-service/discovery" ) -func ResetBalances(balances []*Balance) { +func ResetBalances(balances []*Balance) { - bmap:=make(map[string]*Balance) + bmap := make(map[string]*Balance) - for _,b:=range balances{ + for _, b := range balances { bmap[b.Name] = b } @@ -18,20 +18,20 @@ func ResetBalances(balances []*Balance) { } -func GetByName(name string)(application.IHttpApplication,bool) { - b,has:=manager.get(name) - if !has{ - return application.NewOrg(name),true +func GetByName(name string) (application.IHttpApplication, bool) { + b, has := manager.get(name) + if !has { + return application.NewOrg(name), true } - sources,has:=discovery.GetDiscoverer(b.Discovery) - if has{ + sources, has := discovery.GetDiscoverer(b.Discovery) + if has { - service, handler, yes:= sources.GetApp(b.AppConfig) - if yes{ - return application.NewApplication(service,handler),true + service, handler, yes := sources.GetApp(b.AppConfig) + if yes { + return application.NewApplication(service, handler), true } } - return nil,false -} \ No newline at end of file + return nil, false +} diff --git a/goku-service/balance/manager.go b/goku-service/balance/manager.go index aacf4f555a6562e53c687c98691eb6a62f8b03a5..48d003d273a2b91b65595ea5e9c8a1d8e6d40604 100644 --- a/goku-service/balance/manager.go +++ b/goku-service/balance/manager.go @@ -5,30 +5,26 @@ import ( ) var manager = &Manager{ - locker:sync.RWMutex{}, - balances:make(map[string]*Balance), + locker: sync.RWMutex{}, + balances: make(map[string]*Balance), } - - type Manager struct { - locker sync.RWMutex + locker sync.RWMutex balances map[string]*Balance } -func (m *Manager)set(balances map[string]*Balance) { +func (m *Manager) set(balances map[string]*Balance) { m.locker.Lock() m.balances = balances m.locker.Unlock() } -func (m *Manager)get(name string)( *Balance,bool) { +func (m *Manager) get(name string) (*Balance, bool) { m.locker.RLock() - b,has:=m.balances[name] + b, has := m.balances[name] m.locker.RUnlock() - return b,has + return b, has } - - diff --git a/goku-service/common/factory.go b/goku-service/common/factory.go index 08a873d09cbb6e0df170b60753f54dff6eb1fac0..01c92dc346e98bc7d2ba472067299c3e67be9a2d 100644 --- a/goku-service/common/factory.go +++ b/goku-service/common/factory.go @@ -6,7 +6,7 @@ import ( ) type InstanceFactory struct { - locker sync.RWMutex + locker sync.RWMutex instances map[string]*Instance } @@ -17,28 +17,28 @@ func NewInstanceFactory() *InstanceFactory { } } -func (m *InstanceFactory) General(ip string,port int,weight int)*Instance { - if weight<1{ +func (m *InstanceFactory) General(ip string, port int, weight int) *Instance { + if weight < 1 { weight = 1 } - key:=fmt.Sprintf("%s:%d-%d",ip,port,weight) + key := fmt.Sprintf("%s:%d-%d", ip, port, weight) m.locker.RLock() - i,h:=m.instances[key] + i, h := m.instances[key] m.locker.RUnlock() - if h{ + if h { i.Weight = weight return i } m.locker.Lock() - i,h =m.instances[key] - if h{ + i, h = m.instances[key] + if h { m.locker.Unlock() i.Weight = weight return i } - i =&Instance{ - InstanceId: fmt.Sprintf("%s:%d",ip,port), + i = &Instance{ + InstanceId: fmt.Sprintf("%s:%d", ip, port), IP: ip, Port: port, Weight: weight, diff --git a/goku-service/common/instance.go b/goku-service/common/instance.go index f68c7de2fb248497cb385ed0eb0eeeafbc6250bb..9abbbf382f03bd85109dbb24c858694823d106af 100644 --- a/goku-service/common/instance.go +++ b/goku-service/common/instance.go @@ -4,11 +4,11 @@ import "sync" type Instance struct { InstanceId string - IP string - Port int - Weight int - Status InstanceStatus - locker sync.RWMutex + IP string + Port int + Weight int + Status InstanceStatus + locker sync.RWMutex } type PInstances []*Instance @@ -17,32 +17,31 @@ func (p PInstances) Len() int { } func (p PInstances) Less(i, j int) bool { - return p[i].Weight
1{ - weightKey=tags[1] + if len(tags) > 1 { + weightKey = tags[1] } - urls:=strings.Split(tags[0],",") + urls := strings.Split(tags[0], ",") - d.setConfig(urls,weightKey) + d.setConfig(urls, weightKey) return nil } -func (d *Eureka)setConfig(eurekaUrl []string,weightKey string) { +func (d *Eureka) setConfig(eurekaUrl []string, weightKey string) { d.eurekaUrl = eurekaUrl d.weightKey = weightKey } @@ -54,11 +52,11 @@ func (d *Eureka) SetCallback(callback func(services []*common.Service)) { } func (d *Eureka) GetServers() ([]*common.Service, error) { - return d.services,nil + return d.services, nil } func (d *Eureka) Close() error { - if d.cancelFunc !=nil{ + if d.cancelFunc != nil { d.cancelFunc() d.cancelFunc = nil } @@ -66,12 +64,12 @@ func (d *Eureka) Close() error { } func (d *Eureka) Open() error { - d.ScheduleAtFixedRate(time.Second*5) + d.ScheduleAtFixedRate(time.Second * 5) return nil } func NewEurekaDiscovery(config string) *Eureka { - e:= &Eureka{ + e := &Eureka{ services: nil, callback: nil, ct: 0, @@ -82,45 +80,44 @@ func NewEurekaDiscovery(config string) *Eureka { return e } - func (d *Eureka) execCallbacks(apps *Applications) { - if d.callback == nil{ + if d.callback == nil { return } - if apps ==nil{ + if apps == nil { d.callback(nil) return } - if len(apps.Applications) == 0{ + if len(apps.Applications) == 0 { d.callback(nil) return } - services:=make([]*common.Service,0,len(apps.Applications)) - for _,app:=range apps.Applications{ - inses:= make([]*common.Instance,0,len(app.Instances)) - for _,ins:=range app.Instances{ - if ins.Status != EurekaStatusUp{ + services := make([]*common.Service, 0, len(apps.Applications)) + for _, app := range apps.Applications { + inses := make([]*common.Instance, 0, len(app.Instances)) + for _, ins := range app.Instances { + if ins.Status != EurekaStatusUp { continue } - weight:= 0 - if w,has:=ins.Metadata.Map[d.weightKey];has{ - weight,_ = strconv.Atoi(w) + weight := 0 + if w, has := ins.Metadata.Map[d.weightKey]; has { + weight, _ = strconv.Atoi(w) } - if weight == 0{ + if weight == 0 { weight = 1 } - port:= 0 - if ins.Port.Enabled{ + port := 0 + if ins.Port.Enabled { port = ins.Port.Port - } else if ins.SecurePort.Enabled{ + } else if ins.SecurePort.Enabled { port = ins.SecurePort.Port } - inses = append(inses, d.instanceFactory.General(ins.IpAddr, port,weight)) + inses = append(inses, d.instanceFactory.General(ins.IpAddr, port, weight)) } - server:=common.NewService(app.Name,inses) - services = append(services,server) + server := common.NewService(app.Name, inses) + services = append(services, server) } d.callback(services) @@ -129,17 +126,17 @@ func (d *Eureka) execCallbacks(apps *Applications) { func (d *Eureka) ScheduleAtFixedRate(second time.Duration) { d.run() - if d.cancelFunc !=nil{ + if d.cancelFunc != nil { d.cancelFunc() d.cancelFunc = nil } - ctx,cancel:=context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(context.Background()) d.cancelFunc = cancel - go d.runTask(second,ctx) + go d.runTask(second, ctx) } -func (d *Eureka) runTask(second time.Duration,ctx context.Context) { +func (d *Eureka) runTask(second time.Duration, ctx context.Context) { timer := time.NewTicker(second) for { select { @@ -164,11 +161,11 @@ func (d *Eureka) run() { func (d *Eureka) GetApplications() (*Applications, error) { //url := c.eurekaUrl + "/apps" - url, err:= d.getEurekaServerUrl() - if err!= nil{ - return nil,err + url, err := d.getEurekaServerUrl() + if err != nil { + return nil, err } - url = fmt.Sprintf("%s/apps",url) + url = fmt.Sprintf("%s/apps", url) res, err := http.Get(url) if err != nil { @@ -190,20 +187,20 @@ func (d *Eureka) GetApplications() (*Applications, error) { return applications, err } -func (d *Eureka) getEurekaServerUrl()( string ,error){ +func (d *Eureka) getEurekaServerUrl() (string, error) { ct := atomic.AddUint64(&d.ct, 1) size := len(d.eurekaUrl) if size == 0 { - e:= NilPointError("eureka url is empty") + e := NilPointError("eureka url is empty") - return "",e + return "", e } index := int(ct) % size url := d.eurekaUrl[index] //if strings.LastIndex(url,"/")>-1{ url = strings.TrimSuffix(url, "/") //} - return url,nil + return url, nil } func (d *Eureka) Health() (bool, string) { diff --git a/goku-service/driver/eureka/init.go b/goku-service/driver/eureka/init.go index 92f19c10aeb7d39c54a15ed4f2e062af9df3bd37..f15f0091840779d0a10c85cac4262f1dc20e2956 100644 --- a/goku-service/driver/eureka/init.go +++ b/goku-service/driver/eureka/init.go @@ -3,13 +3,15 @@ package eureka import ( "github.com/eolinker/goku/goku-service/discovery" ) + const DriverName = "eureka" -const EurekaStatusUp ="UP" +const EurekaStatusUp = "UP" + func init() { - discovery.RegisteredDiscovery(DriverName,discovery.NewDriver(Create)) + discovery.RegisteredDiscovery(DriverName, discovery.NewDriver(Create)) } func Create(config string) discovery.Discovery { return NewEurekaDiscovery(config) -} \ No newline at end of file +} diff --git a/goku-service/driver/kubernetes/init.go b/goku-service/driver/kubernetes/init.go index 27f7d8be3d78c6c707b2d0a7398df3e4d42f6548..5f4ca5b3953dceb3754c98508b96f48e270f4d8d 100644 --- a/goku-service/driver/kubernetes/init.go +++ b/goku-service/driver/kubernetes/init.go @@ -3,8 +3,10 @@ package kubernetes import ( discoveryManager "github.com/eolinker/goku/goku-service/discovery" ) + const DriverName = "kubernetes" + func init() { - discoveryManager.RegisteredDiscovery(DriverName,new(Driver)) + discoveryManager.RegisteredDiscovery(DriverName, new(Driver)) } diff --git a/goku-service/driver/kubernetes/k8s.go b/goku-service/driver/kubernetes/k8s.go index 53bd8a47c755efd6b45a9ec24f0b85b3f234a4d1..7ce9a8b03496a0cdc49d621268155013dbbc76da 100644 --- a/goku-service/driver/kubernetes/k8s.go +++ b/goku-service/driver/kubernetes/k8s.go @@ -5,14 +5,11 @@ import ( ) type Driver struct { - } -func (d *Driver) Open(name string,config string)(discovery.ISource,error) { +func (d *Driver) Open(name string, config string) (discovery.ISource, error) { panic("implement me") } - type KubernetesDiscovery struct { - -} \ No newline at end of file +} diff --git a/goku-service/driver/static/init.go b/goku-service/driver/static/init.go index 0c6526cf7d497cbe61f30153dc56aae95a2a35ec..f268ebbce076e1a99e04b557d8debdbf075108b2 100644 --- a/goku-service/driver/static/init.go +++ b/goku-service/driver/static/init.go @@ -1,11 +1,11 @@ package static import ( - "github.com/eolinker/goku/goku-service/discovery" ) + const DriverName = "static" func init() { - discovery.RegisteredDiscovery(DriverName,new(Driver)) + discovery.RegisteredDiscovery(DriverName, new(Driver)) } diff --git a/goku-service/driver/static/node.go b/goku-service/driver/static/node.go index 745db3f1bca44fd24a814bc41a1f043792a3e672..c95b78cf3a1cbe83213f1dacb702235748dcc29c 100644 --- a/goku-service/driver/static/node.go +++ b/goku-service/driver/static/node.go @@ -1,8 +1,7 @@ package static type Node struct { -IP string -Port int -Weight int - + IP string + Port int + Weight int } diff --git a/goku-service/driver/static/static-node.go b/goku-service/driver/static/static-node.go index cc8e806ad7a4df18512e0f13087e0534c15e14f8..5eb60bb72e76fc652d1a38ee8ad2beccbbf85aea 100644 --- a/goku-service/driver/static/static-node.go +++ b/goku-service/driver/static/static-node.go @@ -6,16 +6,14 @@ import ( ) type Driver struct { - } -func (d *Driver) Open(name string,config string)(discovery.ISource,error) { +func (d *Driver) Open(name string, config string) (discovery.ISource, error) { - return NewStaticSources(name),nil + return NewStaticSources(name), nil } type StaticDiscovery struct { - } func (d *StaticDiscovery) SetConfig(config string) error { @@ -31,13 +29,13 @@ func (d *StaticDiscovery) SetCallback(callback func(services []*common.Service)) } func (d *StaticDiscovery) GetServers() ([]*common.Service, error) { - return nil,nil + return nil, nil } func (d *StaticDiscovery) Close() error { -return nil + return nil } func (d *StaticDiscovery) Open() error { -return nil + return nil } diff --git a/goku-service/driver/static/staticSources.go b/goku-service/driver/static/staticSources.go index bf47e675d7ccbfb86b9efb55784cf5d6d48a8d02..bbeabd4ecbe17369783769d43f1909172112117a 100644 --- a/goku-service/driver/static/staticSources.go +++ b/goku-service/driver/static/staticSources.go @@ -12,17 +12,19 @@ import ( "strings" "unicode" ) + var ErrorNoInstance = errors.New("no instance") + type Sources struct { name string - discovery *StaticDiscovery + discovery *StaticDiscovery healthCheckHandler health.CheckHandler - instanceFactory *common.InstanceFactory + instanceFactory *common.InstanceFactory } func (s *Sources) SetHealthConfig(conf *discovery.HealthCheckConfig) { - if conf==nil || !conf.IsHealthCheck { + if conf == nil || !conf.IsHealthCheck { s.Close() return } @@ -36,37 +38,35 @@ func (s *Sources) SetHealthConfig(conf *discovery.HealthCheckConfig) { func (s *Sources) Close() { instances := s.healthCheckHandler.Close() - for _,instance:=range instances{ - instance.ChangeStatus(common.InstanceChecking,common.InstanceRun) + for _, instance := range instances { + instance.ChangeStatus(common.InstanceChecking, common.InstanceRun) } } func (s *Sources) CheckDriver(driverName string) bool { - return driverName == DriverName } -func (s*Sources)SetDriverConfig(config string) error { +func (s *Sources) SetDriverConfig(config string) error { return nil } -func (s *Sources) GetApp(app string) (*common.Service,health.CheckHandler, bool) { - service,e:=s.decode(app) - if e!=nil{ - return nil,nil,false +func (s *Sources) GetApp(app string) (*common.Service, health.CheckHandler, bool) { + service, e := s.decode(app) + if e != nil { + return nil, nil, false } - return service, s.healthCheckHandler,true + return service, s.healthCheckHandler, true } func NewStaticSources(name string) *Sources { return &Sources{ - name: name, - discovery: new(StaticDiscovery), - healthCheckHandler: &health.CheckBox{}, - instanceFactory: common.NewInstanceFactory(), - + name: name, + discovery: new(StaticDiscovery), + healthCheckHandler: &health.CheckBox{}, + instanceFactory: common.NewInstanceFactory(), } } @@ -82,13 +82,12 @@ func fields(str string) []string { return words } -func (s*Sources) decode(config string)(*common.Service,error ){ +func (s *Sources) decode(config string) (*common.Service, error) { words := fields(config) - - instances:=make([]*common.Instance,0,5) - nodes:= make([]*Node,0,5) + instances := make([]*common.Instance, 0, 5) + nodes := make([]*Node, 0, 5) var node *Node = nil index := 0 for _, word := range words { @@ -106,26 +105,26 @@ func (s*Sources) decode(config string)(*common.Service,error ){ case 0: { node = new(Node) - vs:=strings.Split(value,":") - if len(vs)>2{ - return nil,fmt.Errorf("decode ip:port failt for[%s]",value) + vs := strings.Split(value, ":") + if len(vs) > 2 { + return nil, fmt.Errorf("decode ip:port failt for[%s]", value) } - node.IP=vs[0] - if len(vs) == 2{ - node.Port,_= strconv.Atoi(vs[1]) + node.IP = vs[0] + if len(vs) == 2 { + node.Port, _ = strconv.Atoi(vs[1]) } - if node.Port == 0{ + if node.Port == 0 { node.Port = 80 } - //node.InstanceId = fmt.Sprintf("%s:%d",node.IP,node.Port) - nodes = append(nodes,node) + //node.InstanceId = fmt.Sprintf("%s:%d",node.IP,node.Port) + nodes = append(nodes, node) } case 1: { weight, err := strconv.Atoi(value) if err != nil { - return nil,err + return nil, err } node.Weight = weight } @@ -146,13 +145,13 @@ func (s*Sources) decode(config string)(*common.Service,error ){ } if len(nodes) > 0 { - for _,n:=range nodes{ - instance:= s.instanceFactory.General(n.IP,n.Port,n.Weight) + for _, n := range nodes { + instance := s.instanceFactory.General(n.IP, n.Port, n.Weight) instances = append(instances, instance) } - s:=common.NewService("static_upstream",instances) - return s,nil + s := common.NewService("static_upstream", instances) + return s, nil } - return nil,ErrorNoInstance + return nil, ErrorNoInstance } diff --git a/goku-service/health/checker.go b/goku-service/health/checker.go index 7f20b765951ffbe695b85e27924280b5bcafecd6..6dd635c947a2699ef5d1b277cec491bc3904c61e 100644 --- a/goku-service/health/checker.go +++ b/goku-service/health/checker.go @@ -8,61 +8,59 @@ import ( "time" ) - type Checker struct { - path string - second int + path string + second int timeout time.Duration - instances map[string][]*common.Instance - sum int + instances map[string][]*common.Instance + sum int cancelFunc context.CancelFunc statusCodes map[int]bool - closeDone chan int - checkChan chan *common.Instance - + closeDone chan int + checkChan chan *common.Instance } -func (c *Checker) Open() { - if c.cancelFunc != nil{ +func (c *Checker) Open() { + if c.cancelFunc != nil { return } - if c.checkChan == nil{ - c.checkChan = make(chan *common.Instance,2) + if c.checkChan == nil { + c.checkChan = make(chan *common.Instance, 2) } ctx, cancel := context.WithCancel(context.Background()) c.cancelFunc = cancel c.closeDone = make(chan int) - go c.doloop(ctx,c.closeDone) + go c.doloop(ctx, c.closeDone) } -func (c*Checker)check(instance *common.Instance) bool { - url:=fmt.Sprintf("http://%s:%d/%s",instance.IP,instance.Port,c.path) - respone,err:=http.Get(url) - if err!=nil{ +func (c *Checker) check(instance *common.Instance) bool { + url := fmt.Sprintf("http://%s:%d/%s", instance.IP, instance.Port, c.path) + respone, err := http.Get(url) + if err != nil { return false } - if c.statusCodes[ respone.StatusCode]{ + if c.statusCodes[ respone.StatusCode] { return true } return false } -func (c *Checker) doloop(ctx context.Context,closeDone chan int) { +func (c *Checker) doloop(ctx context.Context, closeDone chan int) { defer close(closeDone) - t:=time.NewTicker(time.Duration(c.second)*time.Second) + t := time.NewTicker(time.Duration(c.second) * time.Second) defer t.Stop() - instances:= c.instances + instances := c.instances if instances == nil { instances = make(map[string][]*common.Instance) } - for{ + for { select { case <-ctx.Done(): c.instances = instances @@ -70,64 +68,63 @@ func (c *Checker) doloop(ctx context.Context,closeDone chan int) { return case <-t.C: { - count:= 0 - for instanceId,ins:=range instances { + count := 0 + for instanceId, ins := range instances { // 处理空列表 - if len(ins)==0 { - delete(instances,instanceId) + if len(ins) == 0 { + delete(instances, instanceId) continue } // 筛选需要检查的实例 - insNew:= make([]*common.Instance,0,len(ins)) - for _,instance:=range ins{ - if instance.CheckStatus(common.InstanceChecking){ - insNew = append(insNew,instance) + insNew := make([]*common.Instance, 0, len(ins)) + for _, instance := range ins { + if instance.CheckStatus(common.InstanceChecking) { + insNew = append(insNew, instance) } } // 移除没有需要待检查的实例id if len(insNew) == 0 { - delete(instances,instanceId) + delete(instances, instanceId) continue } instance := insNew[0] - if c.check(instance){ - delete(instances,instanceId) - for _,in:=range insNew{ - in.ChangeStatus(common.InstanceChecking,common.InstanceRun) + if c.check(instance) { + delete(instances, instanceId) + for _, in := range insNew { + in.ChangeStatus(common.InstanceChecking, common.InstanceRun) } - }else{ - count+=len(insNew) + } else { + count += len(insNew) instances[instanceId] = insNew } } c.sum = count } case instance := <-c.checkChan: - if instance!=nil{ - instances[instance.InstanceId] = append(instances[instance.InstanceId],instance) + if instance != nil { + instances[instance.InstanceId] = append(instances[instance.InstanceId], instance) c.sum++ } } } } -func (c *Checker) Check( instance *common.Instance) { - instance.ChangeStatus(common.InstanceRun,common.InstanceChecking) - c.checkChan<-instance +func (c *Checker) Check(instance *common.Instance) { + instance.ChangeStatus(common.InstanceRun, common.InstanceChecking) + c.checkChan <- instance } - -func (c *Checker) Close() (map[string][]*common.Instance,int){ - if c.cancelFunc!= nil{ +func (c *Checker) Close() (map[string][]*common.Instance, int) { + if c.cancelFunc != nil { c.cancelFunc() c.cancelFunc = nil } <-c.closeDone c.closeDone = nil - return c.instances,c.sum -} \ No newline at end of file + return c.instances, c.sum +} diff --git a/goku-service/health/health.go b/goku-service/health/health.go index 260ae0f64907b87e36cc8ab0e7918e528a88dadd..679516245c2b42fbc8b8a264599a0e42c511d4f6 100644 --- a/goku-service/health/health.go +++ b/goku-service/health/health.go @@ -8,10 +8,10 @@ import ( ) type CheckHandler interface { - Open(path string,statusCodes string,second int,timeout time.Duration) + Open(path string, statusCodes string, second int, timeout time.Duration) Check(instance *common.Instance) IsNeedCheck() bool - Close()[]*common.Instance + Close() []*common.Instance } type CheckBox struct { isNeedCheck bool @@ -19,41 +19,40 @@ type CheckBox struct { checker *Checker } -func (c *CheckBox) Open(path string, statusCodes string,second int, timeout time.Duration) { +func (c *CheckBox) Open(path string, statusCodes string, second int, timeout time.Duration) { - old:= c.checker + old := c.checker - checker:=new(Checker) + checker := new(Checker) - checker.path = strings.TrimPrefix(path,"/") - status:=make(map[int]bool) - for _,s:=range strings.Split(statusCodes,","){ - code,e:=strconv.Atoi(s) - if e!=nil{ + checker.path = strings.TrimPrefix(path, "/") + status := make(map[int]bool) + for _, s := range strings.Split(statusCodes, ",") { + code, e := strconv.Atoi(s) + if e != nil { status[code] = true } } - if len(status) == 0{ + if len(status) == 0 { status[200] = true } checker.statusCodes = status - checker.second=second - if checker.second < 5{ + checker.second = second + if checker.second < 5 { checker.second = 5 } checker.timeout = timeout - if checker.timeout < time.Millisecond*100{ - checker.timeout = time.Millisecond*100 + if checker.timeout < time.Millisecond*100 { + checker.timeout = time.Millisecond * 100 } - if old!=nil{ - sources,_:= old.Close() - checker.instances=sources + if old != nil { + sources, _ := old.Close() + checker.instances = sources } - checker.Open() c.checker = checker c.isNeedCheck = true @@ -70,30 +69,28 @@ func (c *CheckBox) Check(instance *common.Instance) { func (c *CheckBox) IsNeedCheck() bool { - return c.isNeedCheck && c.checker!=nil + return c.isNeedCheck && c.checker != nil } -func (c *CheckBox) Close() []*common.Instance{ - if c.checker == nil{ +func (c *CheckBox) Close() []*common.Instance { + if c.checker == nil { return nil } c.isNeedCheck = false - oldInstances,count:=c.checker.Close() + oldInstances, count := c.checker.Close() c.checker = nil - if count>0{ - instances:=make([]*common.Instance,0,count) + if count > 0 { + instances := make([]*common.Instance, 0, count) - for _,ins:=range oldInstances{ + for _, ins := range oldInstances { - if len(ins)>0{ - instances = append(instances,ins...) + if len(ins) > 0 { + instances = append(instances, ins...) } } return instances } - return nil } - diff --git a/server/access-field/def.go b/server/access-field/def.go index c94485f020446e76b5505e19d0c51da8b1d22997..39f1fd13085cec7566afdeb4f9bd437dbb74b2ac 100644 --- a/server/access-field/def.go +++ b/server/access-field/def.go @@ -10,21 +10,21 @@ const ( Request = "$request" StatusCode = "$status_code" BodyBytesSent = "$body_bytes_sent" - Msec = "$msec" - HttpReferer = "$http_referer" - HttpUserAgent = "$http_user_agent" - RequestTime = "$request_time" - TimeIso8601 = "$time_iso8601" - TimeLocal = "$time_local" - RequestId = "$request_id" - FinallyServer = "$finally_server" - Balance = "$balance" - Strategy = "$strategy" - Api = "$api" - Retry = "$retry" - Proxy = "$proxy" - ProxyStatusCode = "$proxy_status_code" - Host = "$host" + Msec = "$msec" + HttpReferer = "$http_referer" + HttpUserAgent = "$http_user_agent" + RequestTime = "$request_time" + TimeIso8601 = "$time_iso8601" + TimeLocal = "$time_local" + RequestId = "$request_id" + FinallyServer = "$finally_server" + Balance = "$balance" + Strategy = "$strategy" + Api = "$api" + Retry = "$retry" + Proxy = "$proxy" + ProxyStatusCode = "$proxy_status_code" + Host = "$host" ) func (k AccessFieldKey) Info() string { @@ -40,18 +40,17 @@ func (k AccessFieldKey) Key() string { return strings.ToLower(string(k)) } - func Parse(key string) AccessFieldKey { return AccessFieldKey(strings.ToLower(key)) } -func CopyKey()map[string]string{ - v:=make(map[string]string) - for key,value:=range infos{ - v[key]=value +func CopyKey() map[string]string { + v := make(map[string]string) + for key, value := range infos { + v[key] = value } return v } -func Has(key string) bool { - _,has:=infos[AccessFieldKey(key).Key()] +func Has(key string) bool { + _, has := infos[AccessFieldKey(key).Key()] return has } diff --git a/server/access-field/info.go b/server/access-field/info.go index 0841ce40d558c008316d6f4796f4085a46eab4a2..9608d33b528a9327f04f1de9caae3831eb2a85d4 100644 --- a/server/access-field/info.go +++ b/server/access-field/info.go @@ -4,24 +4,23 @@ var ( infos = map[string]string{ RemoteAddr: "记录客户端IP地址", HttpXForwardedFor: "记录客户端IP地址(反向)", - Request: "记录请求的方法、URL和协议(例如 POST /proxy HTTPS)", + Request: "记录请求的方法、URL和协议(例如 POST /proxy HTTPS)", StatusCode: "记录请求状态", BodyBytesSent: "发送给客户端的字节数,不包括响应头的大小; 该变量与Apache模块mod_log_config里的“%B”参数兼容。", - Msec: "日志写入时间。单位为秒,精度是毫秒。", + Msec: "日志写入时间。单位为秒,精度是毫秒。", HttpReferer: "记录从哪个页面链接访问过来的", - HttpUserAgent: "记录客户端浏览器相关信息", - RequestTime: "请求处理时间,单位为秒,精度毫秒; 从读入客户端的第一个字节开始,直到把最后一个字符发送给客户端后进行日志写入为止。", - TimeIso8601: "ISO8601标准格式下的本地时间。", - TimeLocal: "通用日志格式下的本地时间。", - RequestId: "请求id", - FinallyServer: "最后一次转发的主机信息(IP端口或域名端口)", - Balance: "负载信息", - Strategy: "策略信息,包括策略名称和ID", - Api: "API信息,包括 API名称和ID", - Retry: "重试信息", - Proxy: "记录转发的方法、URL和协议(例如 POST /proxy HTTPS)", - ProxyStatusCode: "转发状态码", - Host: "主机信息", + HttpUserAgent: "记录客户端浏览器相关信息", + RequestTime: "请求处理时间,单位为秒,精度毫秒; 从读入客户端的第一个字节开始,直到把最后一个字符发送给客户端后进行日志写入为止。", + TimeIso8601: "ISO8601标准格式下的本地时间。", + TimeLocal: "通用日志格式下的本地时间。", + RequestId: "请求id", + FinallyServer: "最后一次转发的主机信息(IP端口或域名端口)", + Balance: "负载信息", + Strategy: "策略信息,包括策略名称和ID", + Api: "API信息,包括 API名称和ID", + Retry: "重试信息", + Proxy: "记录转发的方法、URL和协议(例如 POST /proxy HTTPS)", + ProxyStatusCode: "转发状态码", + Host: "主机信息", } - ) diff --git a/server/access-field/select.go b/server/access-field/select.go index 2b5bea25b08795a63c417560b5ab388e8f492a5c..db8bfd7cee3f6222097342dcbd91ab7a2cc44e8f 100644 --- a/server/access-field/select.go +++ b/server/access-field/select.go @@ -1,7 +1,7 @@ package access_field -var( - defaultFields =[]AccessFieldKey{ +var ( + defaultFields = []AccessFieldKey{ RequestId, TimeIso8601, @@ -20,21 +20,20 @@ var( Retry, } - defaultSet =make(map[AccessFieldKey]bool) - + defaultSet = make(map[AccessFieldKey]bool) ) func init() { - for _,k:=range defaultFields{ + for _, k := range defaultFields { defaultSet[k] = true } } func IsDefault(k AccessFieldKey) bool { - _,has:= defaultSet[k] + _, has := defaultSet[k] return has } func Default() []AccessFieldKey { return defaultFields -} \ No newline at end of file +} diff --git a/server/access-field/sort.go b/server/access-field/sort.go index 6fc9c681b2c7bc853a0a8402656af21b504d14e7..9fa3fda5b76b664b9015541121ab3dcd4ab54ced 100644 --- a/server/access-field/sort.go +++ b/server/access-field/sort.go @@ -1,7 +1,6 @@ -package access_field +package access_field var ( - all = []AccessFieldKey{ RequestId, Msec, @@ -18,12 +17,11 @@ var ( ProxyStatusCode, RequestTime, RemoteAddr, - HttpXForwardedFor, - Retry, - BodyBytesSent, - HttpReferer, - HttpUserAgent, - + HttpXForwardedFor, + Retry, + BodyBytesSent, + HttpReferer, + HttpUserAgent, } size = len(all) ) @@ -31,6 +29,6 @@ var ( func Size() int { return size } -func All()[]AccessFieldKey { +func All() []AccessFieldKey { return all -} \ No newline at end of file +} diff --git a/server/dao/config-log/log.go b/server/dao/config-log/log.go index bd9c5f5049f8584ef5f20853bcc17f87b1244563..60f072984754f38a130e186e9ad03c5ce511823f 100644 --- a/server/dao/config-log/log.go +++ b/server/dao/config-log/log.go @@ -5,15 +5,16 @@ import ( entity "github.com/eolinker/goku/server/entity/config-log" ) -const sqlSelect = "SELECT `name`,`enable`,`dir`,`file`,`level`,`period`,`expire`,`fields` FROM `goku_config_log` WHERE `name` = ? LIMIT 1;" -const sqlInsert = "INSERT INTO `goku_config_log`(`name`,`enable`,`dir`,`file`,`level`,`period`,`expire`,`fields`)VALUES(?,?,?,?,?,?,?,?)ON DUPLICATE KEY UPDATE `enable`=VALUES(`enable`),`dir`=VALUES(`dir`),`file`=VALUES(`file`),`level`=VALUES(`level`),`period`=VALUES(`period`),`expire`=VALUES(`expire`),`fields`=VALUES(`fields`);" -func Get(name string) (*entity.LogConfig ,error){ +const sqlSelect = "SELECT `name`,`enable`,`dir`,`file`,`level`,`period`,`expire`,`fields` FROM `goku_config_log` WHERE `name` = ? LIMIT 1;" +const sqlInsert = "INSERT INTO `goku_config_log`(`name`,`enable`,`dir`,`file`,`level`,`period`,`expire`,`fields`)VALUES(?,?,?,?,?,?,?,?)ON DUPLICATE KEY UPDATE `enable`=VALUES(`enable`),`dir`=VALUES(`dir`),`file`=VALUES(`file`),`level`=VALUES(`level`),`period`=VALUES(`period`),`expire`=VALUES(`expire`),`fields`=VALUES(`fields`);" + +func Get(name string) (*entity.LogConfig, error) { stmt, e := database.GetConnection().Prepare(sqlSelect) - if e!=nil{ - return nil,e + if e != nil { + return nil, e } - ent:=&entity.LogConfig{} - err:=stmt.QueryRow(name).Scan( + ent := &entity.LogConfig{} + err := stmt.QueryRow(name).Scan( &ent.Name, &ent.Enable, &ent.Dir, @@ -22,16 +23,16 @@ func Get(name string) (*entity.LogConfig ,error){ &ent.Period, &ent.Expire, &ent.Fields, - ) - if err!=nil{ - return nil,err + ) + if err != nil { + return nil, err } - return ent,nil + return ent, nil } -func Set(ent *entity.LogConfig)error{ +func Set(ent *entity.LogConfig) error { stmt, e := database.GetConnection().Prepare(sqlInsert) - if e!=nil{ + if e != nil { return e } _, err := stmt.Exec( diff --git a/server/dao/console-mysql/cluster.go b/server/dao/console-mysql/cluster.go index 56c5e34ca3bd339f1dff061922663b0b3c972b8c..f698cf7f448454b96737ec0950f923329a5a4ecf 100644 --- a/server/dao/console-mysql/cluster.go +++ b/server/dao/console-mysql/cluster.go @@ -3,57 +3,56 @@ package console_mysql import ( "github.com/eolinker/goku/common/database" "github.com/eolinker/goku/server/entity" - "github.com/json-iterator/go" + jsoniter "github.com/json-iterator/go" ) -func InsertClusters(cs []*entity.ClusterInfo) error { - db:= database.GetConnection() - stmt,e:=db.Prepare("INSERT INTO `goku_cluster`(`name`,`title`,`note`,`db`,`redis`) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE `title`=VALUES(`title`),`note`=VALUES(`note`),`db`=VALUES(`db`),`redis`=VALUES(`redis`)") - if e!= nil{ +func InsertClusters(cs []*entity.ClusterInfo) error { + db := database.GetConnection() + stmt, e := db.Prepare("INSERT INTO `goku_cluster`(`name`,`title`,`note`,`db`,`redis`) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE `title`=VALUES(`title`),`note`=VALUES(`note`),`db`=VALUES(`db`),`redis`=VALUES(`redis`)") + if e != nil { return e } - for _,c:=range cs{ - db,_:=jsoniter.MarshalToString(c.DB) - redis,_:=jsoniter.MarshalToString(c.Redis) - stmt.Exec(c.Name,c.Title,c.Note,db,redis) + for _, c := range cs { + db, _ := jsoniter.MarshalToString(c.DB) + redis, _ := jsoniter.MarshalToString(c.Redis) + stmt.Exec(c.Name, c.Title, c.Note, db, redis) } - return nil + return nil } -func LoadClusters()(map[string]*entity.ClusterInfo,error) { - db:=database.GetConnection() - sql:="select `id`, `name`,`title`,`note`,`db`,`redis` from `goku_cluster`;" +func LoadClusters() (map[string]*entity.ClusterInfo, error) { + db := database.GetConnection() + sql := "select `id`, `name`,`title`,`note`,`db`,`redis` from `goku_cluster`;" stmt, e := db.Prepare(sql) - if e!=nil{ - return nil,e + if e != nil { + return nil, e } rows, e := stmt.Query() - if e!= nil{ - return nil,e + if e != nil { + return nil, e } vs := make(map[string]*entity.ClusterInfo) - for rows.Next(){ + for rows.Next() { v := new(entity.ClusterInfo) - db:= "" - redis:= "" - err:=rows.Scan(&v.Id,&v.Name,&v.Title,&v.Note,&db,&redis) - if err!=nil{ + db := "" + redis := "" + err := rows.Scan(&v.Id, &v.Name, &v.Title, &v.Note, &db, &redis) + if err != nil { return nil, nil } - err = jsoniter.UnmarshalFromString(db,&v.DB) - if err!=nil{ + err = jsoniter.UnmarshalFromString(db, &v.DB) + if err != nil { return nil, nil } - err = jsoniter.UnmarshalFromString(redis,&v.Redis) - if err!=nil{ + err = jsoniter.UnmarshalFromString(redis, &v.Redis) + if err != nil { return nil, nil } vs[v.Name] = v } return vs, nil } - diff --git a/server/dao/console-mysql/dao-balance-update/update.go b/server/dao/console-mysql/dao-balance-update/update.go index 6975aad399d70426ce0066bc7b2ef757822f43fa..b384d02ba5539561959508038f0aae3ccea0007b 100644 --- a/server/dao/console-mysql/dao-balance-update/update.go +++ b/server/dao/console-mysql/dao-balance-update/update.go @@ -6,37 +6,37 @@ import ( entity "github.com/eolinker/goku/server/entity/balance-entity" ) -func GetAllOldVerSion() ([]*entity.BalanceInfoEntity ,error){ +func GetAllOldVerSion() ([]*entity.BalanceInfoEntity, error) { const sql = "SELECT `balanceName`,IFNULL(`balanceDesc`, ''),IFNULL(`balanceConfig`, ''),IFNULL(`defaultConfig`, ''),IFNULL(`clusterConfig`, ''),`updateTime`,`createTime` FROM `goku_balance` WHERE `serviceName` = '';" - db:=database.GetConnection() - rows,err:= db.Query(sql) - if err!= nil{ - return nil,err + db := database.GetConnection() + rows, err := db.Query(sql) + if err != nil { + return nil, err } defer rows.Close() - r:=make([]*entity.BalanceInfoEntity,0,20) - for rows.Next(){ - v:=new(entity.BalanceInfoEntity) - err:=rows.Scan( &v.Name,&v.Desc,&v.OldVersionConfig, &v.DefaultConfig, &v.ClusterConfig, &v.UpdateTime, &v.CreateTime) - if err!= nil{ - return nil,err + r := make([]*entity.BalanceInfoEntity, 0, 20) + for rows.Next() { + v := new(entity.BalanceInfoEntity) + err := rows.Scan(&v.Name, &v.Desc, &v.OldVersionConfig, &v.DefaultConfig, &v.ClusterConfig, &v.UpdateTime, &v.CreateTime) + if err != nil { + return nil, err } - r= append(r,v) + r = append(r, v) } - return r,nil + return r, nil } -func GetDefaultServiceStatic()string { +func GetDefaultServiceStatic() string { tx := database.GetConnection() - name:="" - err:=tx.QueryRow("SELECT `name` FROM `goku_service_config` WHERE `driver`='static' ORDER BY `default` DESC LIMIT 1; ").Scan(&name) - if err!=nil{ - name ="static" - dao_service.Add(name,"static","默认静态服务","","",false,false,"","",5,300) + name := "" + err := tx.QueryRow("SELECT `name` FROM `goku_service_config` WHERE `driver`='static' ORDER BY `default` DESC LIMIT 1; ").Scan(&name) + if err != nil { + name = "static" + dao_service.Add(name, "static", "默认静态服务", "", "", false, false, "", "", 5, 300) } return name -} \ No newline at end of file +} diff --git a/server/dao/console-mysql/dao-monitor/download.go b/server/dao/console-mysql/dao-monitor/download.go index 1788e7135d1344671d2e95cea604fac3385059a2..e7915fd1987af32cb56725240d8af8520bb437ef 100644 --- a/server/dao/console-mysql/dao-monitor/download.go +++ b/server/dao/console-mysql/dao-monitor/download.go @@ -7,121 +7,121 @@ import ( func GetStrategyByHour(clusterId int, hours []int) ([]*MonitorValueWidthStrategy, error) { stmt, e := database.GetConnection().Prepare(sqlSelectStrategyByHour.Build(hours)) - if e!=nil{ - return nil,e + if e != nil { + return nil, e } defer stmt.Close() - rows,err:= stmt.Query( clusterId) - if err!=nil{ - return nil,err + rows, err := stmt.Query(clusterId) + if err != nil { + return nil, err } defer rows.Close() - all:=make([]*MonitorValueWidthStrategy,0,1000) + all := make([]*MonitorValueWidthStrategy, 0, 1000) - for rows.Next(){ - v:= new(MonitorValueWidthStrategy) + for rows.Next() { + v := new(MonitorValueWidthStrategy) - values,err:=read(rows,&v.Hour,&v.Id,&v.Name,&v.Status) - if err!=nil{ - return nil,err + values, err := read(rows, &v.Hour, &v.Id, &v.Name, &v.Status) + if err != nil { + return nil, err } v.Value = values - all = append( all,v) + all = append(all, v) } - return all,nil + return all, nil } func GetAPIByHour(clusterId int, hours []int) ([]*MonitorValueWidthAPI, error) { stmt, e := database.GetConnection().Prepare(sqlSelectApiByHour.Build(hours)) - if e!=nil{ - return nil,e + if e != nil { + return nil, e } defer stmt.Close() - rows,err:= stmt.Query( clusterId) - if err!=nil{ - return nil,err + rows, err := stmt.Query(clusterId) + if err != nil { + return nil, err } defer rows.Close() - all:=make([]*MonitorValueWidthAPI,0,1000) + all := make([]*MonitorValueWidthAPI, 0, 1000) - for rows.Next(){ - v:= new(MonitorValueWidthAPI) + for rows.Next() { + v := new(MonitorValueWidthAPI) - values,err:=read(rows,&v.Hour,&v.Id,&v.Name,&v.RequestURL) - if err!=nil{ - return nil,err + values, err := read(rows, &v.Hour, &v.Id, &v.Name, &v.RequestURL) + if err != nil { + return nil, err } v.Value = values - all = append( all,v) + all = append(all, v) } - return all,nil + return all, nil } -func GetAPIOfStrategyByHour(clusterId int,strategyID string, hours []int) ([]*MonitorValueWidthAPI, error) { +func GetAPIOfStrategyByHour(clusterId int, strategyID string, hours []int) ([]*MonitorValueWidthAPI, error) { stmt, e := database.GetConnection().Prepare(sqlSelectApiOfStrategyByHour.Build(hours)) - if e!=nil{ - return nil,e + if e != nil { + return nil, e } defer stmt.Close() - rows,err:= stmt.Query( strategyID,clusterId) - if err!=nil{ - return nil,err + rows, err := stmt.Query(strategyID, clusterId) + if err != nil { + return nil, err } defer rows.Close() - all:=make([]*MonitorValueWidthAPI,0,1000) + all := make([]*MonitorValueWidthAPI, 0, 1000) - for rows.Next(){ - v:= new(MonitorValueWidthAPI) + for rows.Next() { + v := new(MonitorValueWidthAPI) - values,err:=read(rows,&v.Hour,&v.Id,&v.Name,&v.RequestURL) - if err!=nil{ - return nil,err + values, err := read(rows, &v.Hour, &v.Id, &v.Name, &v.RequestURL) + if err != nil { + return nil, err } v.Value = values - all = append( all,v) + all = append(all, v) } - return all,nil + return all, nil } -func GetStrategyOfAPIHour(clusterId int,apiId int, hours []int) ([]*MonitorValueWidthStrategy, error) { +func GetStrategyOfAPIHour(clusterId int, apiId int, hours []int) ([]*MonitorValueWidthStrategy, error) { stmt, e := database.GetConnection().Prepare(sqlSelectStrategyOfAPIByHour.Build(hours)) - if e!=nil{ - return nil,e + if e != nil { + return nil, e } defer stmt.Close() - rows,err:= stmt.Query( apiId,clusterId,) - if err!=nil{ - return nil,err + rows, err := stmt.Query(apiId, clusterId, ) + if err != nil { + return nil, err } defer rows.Close() - all:=make([]*MonitorValueWidthStrategy,0,1000) + all := make([]*MonitorValueWidthStrategy, 0, 1000) - for rows.Next(){ - strategy:= new(MonitorValueWidthStrategy) + for rows.Next() { + strategy := new(MonitorValueWidthStrategy) - values,err:=read(rows,&strategy.Hour,&strategy.Id,&strategy.Name,&strategy.Status) - if err!=nil{ - return nil,err + values, err := read(rows, &strategy.Hour, &strategy.Id, &strategy.Name, &strategy.Status) + if err != nil { + return nil, err } strategy.Value = values - all = append( all,strategy) + all = append(all, strategy) } - return all,nil -} \ No newline at end of file + return all, nil +} diff --git a/server/dao/console-mysql/dao-monitor/read.go b/server/dao/console-mysql/dao-monitor/read.go index 51ad4b56ae6891a5dd00a0cdfeef70eafe46a081..3784a0cbb6e63293111a7865662e7100c0ccf9f5 100644 --- a/server/dao/console-mysql/dao-monitor/read.go +++ b/server/dao/console-mysql/dao-monitor/read.go @@ -2,18 +2,18 @@ package dao_monitor import monitor_key "github.com/eolinker/goku/server/monitor/monitor-key" -func read(s SCAN,args ...interface{}) (monitor_key.MonitorValues,error) { - v:=monitor_key.MakeValue() - vp:=make([]interface{},0,monitor_key.MonitorKeyTypeSize+len(args)) +func read(s SCAN, args ...interface{}) (monitor_key.MonitorValues, error) { + v := monitor_key.MakeValue() + vp := make([]interface{}, 0, monitor_key.MonitorKeyTypeSize+len(args)) - vp = append(vp,args...) + vp = append(vp, args...) - for i:=range v{ - vp = append(vp,&v[i]) + for i := range v { + vp = append(vp, &v[i]) } - err:=s.Scan(vp...) - if err!= nil{ - return v,err + err := s.Scan(vp...) + if err != nil { + return v, err } - return v,nil -} \ No newline at end of file + return v, nil +} diff --git a/server/dao/console-mysql/dao-monitor/sql_test.go b/server/dao/console-mysql/dao-monitor/sql_test.go index 3118deecda9e93a33bdc457f36bd0be24cf68253..efc1fb8fc5c488dbdddc66de0054c14448654c38 100644 --- a/server/dao/console-mysql/dao-monitor/sql_test.go +++ b/server/dao/console-mysql/dao-monitor/sql_test.go @@ -6,12 +6,12 @@ import ( "testing" ) -func TestGenSql(t *testing.T) { +func TestGenSql(t *testing.T) { keys := monitor_key.Keys() - fields := make([]string,len(keys)) + fields := make([]string, len(keys)) - for i:=range keys{ - fields[i] = fmt.Sprintf("`%s`",keys[i].String()) + for i := range keys { + fields[i] = fmt.Sprintf("`%s`", keys[i].String()) } fmt.Println("# save ") fmt.Println(genSqlSave(fields)) @@ -33,4 +33,4 @@ func TestGenSql(t *testing.T) { fmt.Println("#策略内API") fmt.Println(genSqlSelectApiOfStrategy(fields)) -} \ No newline at end of file +} diff --git a/server/dao/console-mysql/dao-service/add.go b/server/dao/console-mysql/dao-service/add.go index 336505ff06945e2dfea52cb2e7925c250f108c6e..654bd7e611ef17b64a1e119ca733b84cac57200f 100644 --- a/server/dao/console-mysql/dao-service/add.go +++ b/server/dao/console-mysql/dao-service/add.go @@ -5,17 +5,17 @@ import ( "time" ) -const sqlAdd="INSERT INTO `goku_service_config`(`name`,`driver`,`default`,`desc`,`config`,`clusterConfig`,`healthCheck`,`healthCheckPath`,`healthCheckPeriod`,`healthCheckCode`,`healthCheckTimeOut`,`createTime`,`updateTime`)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?);" -func Add(name, driver, desc, config, clusterConfig string,isDefault,healthCheck bool,healthCheckPath string,healthCheckCode string,healthCheckPeriod ,healthCheckTimeOut int) error { +const sqlAdd = "INSERT INTO `goku_service_config`(`name`,`driver`,`default`,`desc`,`config`,`clusterConfig`,`healthCheck`,`healthCheckPath`,`healthCheckPeriod`,`healthCheckCode`,`healthCheckTimeOut`,`createTime`,`updateTime`)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?);" - now:=time.Now() +func Add(name, driver, desc, config, clusterConfig string, isDefault, healthCheck bool, healthCheckPath string, healthCheckCode string, healthCheckPeriod, healthCheckTimeOut int) error { + + now := time.Now() stmt, e := database.GetConnection().Prepare(sqlAdd) - if e!=nil{ + if e != nil { return e } - _,err:=stmt.Exec(name,driver,isDefault,desc,config,clusterConfig,healthCheck,healthCheckPath,healthCheckPeriod,healthCheckCode,healthCheckTimeOut,now,now) + _, err := stmt.Exec(name, driver, isDefault, desc, config, clusterConfig, healthCheck, healthCheckPath, healthCheckPeriod, healthCheckCode, healthCheckTimeOut, now, now) return err } - diff --git a/server/dao/console-mysql/dao-service/default.go b/server/dao/console-mysql/dao-service/default.go index 572bc2a041d94011ad11807eed5b0c6e38f86087..8044b7f2bc8ada5da91e37c6c1e64866490c378f 100644 --- a/server/dao/console-mysql/dao-service/default.go +++ b/server/dao/console-mysql/dao-service/default.go @@ -5,30 +5,30 @@ import ( "github.com/eolinker/goku/common/database" ) -func SetDefault(name string)error { - count:=0 - err:=database.GetConnection().QueryRow("SELECT count(1) FROM `goku_service_config` WHERE `name` = ?;",name).Scan(&count) - if err!=nil{ +func SetDefault(name string) error { + count := 0 + err := database.GetConnection().QueryRow("SELECT count(1) FROM `goku_service_config` WHERE `name` = ?;", name).Scan(&count) + if err != nil { return err } - if count !=1{ - return fmt.Errorf("has no name=%s",name) + if count != 1 { + return fmt.Errorf("has no name=%s", name) } tx, e := database.GetConnection().Begin() - if e!=nil{ + if e != nil { return e } - if _,e:=tx.Exec("UPDATE `goku_service_config` SET `default` = 0 ;");e!=nil{ + if _, e := tx.Exec("UPDATE `goku_service_config` SET `default` = 0 ;"); e != nil { tx.Rollback() return e } - if _,e:=tx.Exec("UPDATE `goku_service_config` SET `default` = 1 WHERE `name`=? ;",name);e!=nil{ + if _, e := tx.Exec("UPDATE `goku_service_config` SET `default` = 1 WHERE `name`=? ;", name); e != nil { tx.Rollback() return e } return tx.Commit() -} \ No newline at end of file +} diff --git a/server/dao/console-mysql/dao-service/delete.go b/server/dao/console-mysql/dao-service/delete.go index 8ebd9b6d772c6baf0b7c9d265831ed4a0e1c77d4..a3cca8ce49cb9994260a4bb806d9b61a3a847de9 100644 --- a/server/dao/console-mysql/dao-service/delete.go +++ b/server/dao/console-mysql/dao-service/delete.go @@ -9,39 +9,37 @@ const sqlDelete = "DELETE FROM `goku_service_config` WHERE `name` = ? AND NOT type DeleteError string -func (e DeleteError) Error()string { - return fmt.Sprintf("can not delete :%s",string(e)) +func (e DeleteError) Error() string { + return fmt.Sprintf("can not delete :%s", string(e)) } -func Delete(names []string)error { +func Delete(names []string) error { - tx, err:= database.GetConnection().Begin() - if err!=nil{ + tx, err := database.GetConnection().Begin() + if err != nil { return err } stmt, e := tx.Prepare(sqlDelete) - if e!=nil{ + if e != nil { return e } - defer stmt.Close() - - for _,name:=range names{ - r,e:=stmt.Exec(name) - if e!=nil{ + for _, name := range names { + r, e := stmt.Exec(name) + if e != nil { tx.Rollback() return e } - rowCount,err:=r.RowsAffected() - if err!=nil{ + rowCount, err := r.RowsAffected() + if err != nil { tx.Rollback() return e } - if rowCount == 0{ + if rowCount == 0 { tx.Rollback() return DeleteError(name) } @@ -49,4 +47,4 @@ func Delete(names []string)error { return tx.Commit() -} \ No newline at end of file +} diff --git a/server/dao/console-mysql/dao-service/get.go b/server/dao/console-mysql/dao-service/get.go index f8516c310183f9ffbe9df283753d41a058fc759a..c7bfea6c6c671e9f8622ac534c41917ba221b795 100644 --- a/server/dao/console-mysql/dao-service/get.go +++ b/server/dao/console-mysql/dao-service/get.go @@ -6,24 +6,25 @@ import ( entity "github.com/eolinker/goku/server/entity/console-entity" ) -const sqlGet = "SELECT `name`,`driver`,`default`,`desc`,`config`,`clusterConfig`,`healthCheck`,`healthCheckPath`,`healthCheckPeriod`,`healthCheckCode`,`healthCheckTimeOut`,`createTime`,`updateTime` FROM `goku_service_config` WHERE `name`=?; " -func Get(name string)(*entity.Service, error) { +const sqlGet = "SELECT `name`,`driver`,`default`,`desc`,`config`,`clusterConfig`,`healthCheck`,`healthCheckPath`,`healthCheckPeriod`,`healthCheckCode`,`healthCheckTimeOut`,`createTime`,`updateTime` FROM `goku_service_config` WHERE `name`=?; " + +func Get(name string) (*entity.Service, error) { stmt, e := database.GetConnection().Prepare(sqlGet) - if e!=nil{ - return nil,e + if e != nil { + return nil, e } defer stmt.Close() - rows,err:=stmt.Query(name) + rows, err := stmt.Query(name) - if err!=nil{ - return nil,err + if err != nil { + return nil, err } defer rows.Close() - if rows.Next(){ + if rows.Next() { - v:=new(entity.Service) - er:=rows.Scan(&v.Name, + v := new(entity.Service) + er := rows.Scan(&v.Name, &v.Driver, &v.IsDefault, &v.Desc, @@ -36,15 +37,14 @@ func Get(name string)(*entity.Service, error) { &v.HealthCheckTimeOut, &v.CreateTime, &v.UpdateTime, - ) - if er!=nil{ - return nil,er + ) + if er != nil { + return nil, er } - - return v,nil + return v, nil } - return nil,fmt.Errorf("no that service:%s",name) + return nil, fmt.Errorf("no that service:%s", name) -} \ No newline at end of file +} diff --git a/server/dao/console-mysql/dao-service/save.go b/server/dao/console-mysql/dao-service/save.go index e82b2ecc2491cc808236ee43724b6e5d5cbf0223..da0ff71f46d6c5b5a42a08e5e78c7e0222e7adb1 100644 --- a/server/dao/console-mysql/dao-service/save.go +++ b/server/dao/console-mysql/dao-service/save.go @@ -5,15 +5,16 @@ import ( "time" ) -const sqlSave = "UPDATE `goku_service_config` SET `desc`=?,`config`=?,`clusterConfig`=?,`healthCheck`=?,`healthCheckPath`=?,`healthCheckPeriod`=?,`healthCheckCode`=?,`healthCheckTimeOut`=?,`updateTime`=? WHERE `name`=?;" -func Save(name, desc, config, clusterConfig string,healthCheck bool,healthCheckPath string,healthCheckCode string,healthCheckPeriod ,healthCheckTimeOut int) error { - now:=time.Now() +const sqlSave = "UPDATE `goku_service_config` SET `desc`=?,`config`=?,`clusterConfig`=?,`healthCheck`=?,`healthCheckPath`=?,`healthCheckPeriod`=?,`healthCheckCode`=?,`healthCheckTimeOut`=?,`updateTime`=? WHERE `name`=?;" + +func Save(name, desc, config, clusterConfig string, healthCheck bool, healthCheckPath string, healthCheckCode string, healthCheckPeriod, healthCheckTimeOut int) error { + now := time.Now() stmt, e := database.GetConnection().Prepare(sqlSave) - if e!=nil{ + if e != nil { return e } - _,err:=stmt.Exec(desc,config,clusterConfig,healthCheck,healthCheckPath,healthCheckPeriod,healthCheckCode,healthCheckTimeOut,now,name) + _, err := stmt.Exec(desc, config, clusterConfig, healthCheck, healthCheckPath, healthCheckPeriod, healthCheckCode, healthCheckTimeOut, now, name) return err -} \ No newline at end of file +} diff --git a/server/dao/console-mysql/guest.go b/server/dao/console-mysql/guest.go index 6cd483341663f487d70f3de01e4f04f74d50605d..7022c86dc858485055ee44a77c03159ec2084a6d 100644 --- a/server/dao/console-mysql/guest.go +++ b/server/dao/console-mysql/guest.go @@ -4,7 +4,6 @@ import ( SQL "database/sql" "github.com/eolinker/goku/common/database" "github.com/eolinker/goku/utils" - ) func Login(loginCall, loginPassword string) (bool, int) { diff --git a/server/dao/console-mysql/node.go b/server/dao/console-mysql/node.go index 967f3276561faccfcd4780c2536d8ce30a0058f7..71e5b3181f0ae168b6bbce29cba37c09669dd944 100644 --- a/server/dao/console-mysql/node.go +++ b/server/dao/console-mysql/node.go @@ -2,13 +2,12 @@ package console_mysql import ( "fmt" - "strconv" - "strings" - "time" - "github.com/eolinker/goku/common/database" . "github.com/eolinker/goku/common/version" entity "github.com/eolinker/goku/server/entity/console-entity" + "strconv" + "strings" + "time" ) // 新增节点信息 diff --git a/server/dao/console-mysql/redis_test.go b/server/dao/console-mysql/redis_test.go index 6f6b56a45827f14e331ced72f26b8236578a77ff..4511ac926a42597584132a9a1ff598d74aa31f96 100644 --- a/server/dao/console-mysql/redis_test.go +++ b/server/dao/console-mysql/redis_test.go @@ -1,4 +1 @@ package console_mysql - - - diff --git a/server/dao/console-mysql/script.go b/server/dao/console-mysql/script.go index 3e0173195f34632f4857884be7fcac4e11cf845c..4767f72e1b216004b0c8045a1739ffd20f1df683 100644 --- a/server/dao/console-mysql/script.go +++ b/server/dao/console-mysql/script.go @@ -136,7 +136,7 @@ func RefreshGatewayAlertConfig() bool { dropColomn := []string{"alertPeriodType", "alertAddress", "alertLogPath", "receiverList"} for _, colomn := range dropColomn { sql := "ALTER TABLE goku_gateway DROP COLUMN " + colomn + ";" - log.Debug("RefreshGatewayAlertConfig-sql:",sql) + log.Debug("RefreshGatewayAlertConfig-sql:", sql) _, err = Tx.Exec(sql) if err != nil { Tx.Rollback() diff --git a/server/dao/console-mysql/user.go b/server/dao/console-mysql/user.go index 331ec97e2b3f25276c2331fcd642e1b97c5c5bec..ade601c4a49947d7ea550c891f5cb4f65ee0b0d4 100644 --- a/server/dao/console-mysql/user.go +++ b/server/dao/console-mysql/user.go @@ -6,8 +6,8 @@ import ( database2 "github.com/eolinker/goku/common/database" "github.com/eolinker/goku/utils" ) -type permissionsJson map[string]bool +type permissionsJson map[string]bool // 修改账户信息 func EditPassword(oldPassword, newPassword string, userID int) (bool, string, error) { @@ -103,7 +103,7 @@ func CheckUserIsSuperAdmin(userID int) (bool, string, error) { return true, "", nil } -func CheckSuperAdminCount() (int,error){ +func CheckSuperAdminCount() (int, error) { db := database2.GetConnection() sql := "SELECT count(*) FROM goku_admin WHERE userType = 0;" count := 0 @@ -112,8 +112,9 @@ func CheckSuperAdminCount() (int,error){ return 0, err } - return count , nil + return count, nil } + // 检查用户权限 func CheckUserPermission(operationType, operation string, userID int) (bool, string, error) { db := database2.GetConnection() @@ -150,7 +151,6 @@ func CheckUserPermission(operationType, operation string, userID int) (bool, str } } - // 获取具有编辑权限的用户列表 func GetUserListWithPermission(operationType, operation string) (bool, []map[string]interface{}, error) { db := database2.GetConnection() diff --git a/server/dao/dao-balance/balance.go b/server/dao/dao-balance/balance.go index e5d54a1662ddbcc16eb0305aac471db8a24c299d..77c5221aae91c6ce6b41f926c56a96e6d04af387 100644 --- a/server/dao/dao-balance/balance.go +++ b/server/dao/dao-balance/balance.go @@ -1,7 +1,7 @@ package dao_balance import ( - "github.com/eolinker/goku/common/database" + "github.com/eolinker/goku/common/database" ) func GetBalanceNames() (bool, []string, error) { diff --git a/server/dao/dao-balance/get.go b/server/dao/dao-balance/get.go index 691159bf5ac33e8d258e532f82463fe237ea5d75..bbacc3e9f9c26eddd539d8ba324ecd304d3b2eeb 100644 --- a/server/dao/dao-balance/get.go +++ b/server/dao/dao-balance/get.go @@ -9,64 +9,64 @@ import ( func Get(name string) (*entity.Balance, error) { const sql = "SELECT A.`balanceName`,A.`serviceName`,IFNULL(B.`driver`,''),A.`appName`,IFNULL(A.`static`,''),IFNULL(A.`staticCluster`,''),A.`balanceDesc`,A.`updateTime`,A.`createTime` FROM `goku_balance` A LEFT JOIN `goku_service_config` B ON A.`serviceName` = B.`NAME` WHERE A.`balanceName`= ?;" - db:=database.GetConnection() - v:= new(entity.Balance) - err := db.QueryRow(sql, name).Scan( &v.Name,&v.ServiceName,&v.ServiceDriver,&v.AppName,&v.Static,&v.StaticCluster,&v.Desc, &v.UpdateTime, &v.CreateTime) - if err!= nil{ - return nil,err + db := database.GetConnection() + v := new(entity.Balance) + err := db.QueryRow(sql, name).Scan(&v.Name, &v.ServiceName, &v.ServiceDriver, &v.AppName, &v.Static, &v.StaticCluster, &v.Desc, &v.UpdateTime, &v.CreateTime) + if err != nil { + return nil, err } - return v.Type(),nil + return v.Type(), nil } -func GetAll() ([]*entity.Balance ,error){ +func GetAll() ([]*entity.Balance, error) { const sql = "SELECT A.`balanceName`,A.`serviceName`,IFNULL(B.`driver`,''),A.`appName`,IFNULL(A.`static`,''),IFNULL(A.`staticCluster`,''),A.`balanceDesc`,A.`updateTime`,A.`createTime` FROM `goku_balance` A LEFT JOIN `goku_service_config` B ON A.`serviceName` = B.`name` ORDER BY `updateTime` DESC;" - db:=database.GetConnection() - rows,err:= db.Query(sql) - if err!= nil{ - return nil,err + db := database.GetConnection() + rows, err := db.Query(sql) + if err != nil { + return nil, err } defer rows.Close() - r:=make([]*entity.Balance,0,20) - for rows.Next(){ - v:=new(entity.Balance) - err:=rows.Scan( &v.Name,&v.ServiceName,&v.ServiceDriver,&v.AppName,&v.Static,&v.StaticCluster,&v.Desc, &v.UpdateTime, &v.CreateTime) - if err!= nil{ - return nil,err + r := make([]*entity.Balance, 0, 20) + for rows.Next() { + v := new(entity.Balance) + err := rows.Scan(&v.Name, &v.ServiceName, &v.ServiceDriver, &v.AppName, &v.Static, &v.StaticCluster, &v.Desc, &v.UpdateTime, &v.CreateTime) + if err != nil { + return nil, err } - r= append(r,v.Type()) + r = append(r, v.Type()) } - return r,nil + return r, nil } -func Search(keyword string) ([]*entity.Balance ,error) { +func Search(keyword string) ([]*entity.Balance, error) { const sqlTpl = "SELECT A.`balanceName`,A.`serviceName`,IFNULL(B.`driver`,''),A.`appName`,IFNULL(A.`static`,''),IFNULL(A.`staticCluster`,''),A.`balanceDesc`,A.`updateTime`,A.`createTime` FROM `goku_balance` A LEFT JOIN `goku_service_config` B ON A.`serviceName` = B.`name` %s ORDER BY `updateTime` DESC;" - where:="" - args:=make([]interface{},0,3) - keywordvalue:= strings.Trim(keyword,"%") - if keywordvalue!= ""{ - where = "WHERE A.`balanceName` LIKE ? OR A.`serviceName` LIKE ? OR B.`driver` LIKE ?" - kp:= fmt.Sprint("%",keywordvalue,"%") - args=append(args,kp,kp,kp) + where := "" + args := make([]interface{}, 0, 3) + keywordvalue := strings.Trim(keyword, "%") + if keywordvalue != "" { + where = "WHERE A.`balanceName` LIKE ? OR A.`serviceName` LIKE ? OR B.`driver` LIKE ?" + kp := fmt.Sprint("%", keywordvalue, "%") + args = append(args, kp, kp, kp) } - sql := fmt.Sprintf(sqlTpl,where) - db:=database.GetConnection() - rows,err:= db.Query(sql,args...) - if err!= nil{ - return nil,err + sql := fmt.Sprintf(sqlTpl, where) + db := database.GetConnection() + rows, err := db.Query(sql, args...) + if err != nil { + return nil, err } defer rows.Close() - r:=make([]*entity.Balance,0,20) - for rows.Next(){ - v:=new(entity.Balance) - err:=rows.Scan( &v.Name,&v.ServiceName,&v.ServiceDriver,&v.AppName,&v.Static,&v.StaticCluster,&v.Desc, &v.UpdateTime, &v.CreateTime) - if err!= nil{ - return nil,err + r := make([]*entity.Balance, 0, 20) + for rows.Next() { + v := new(entity.Balance) + err := rows.Scan(&v.Name, &v.ServiceName, &v.ServiceDriver, &v.AppName, &v.Static, &v.StaticCluster, &v.Desc, &v.UpdateTime, &v.CreateTime) + if err != nil { + return nil, err } - r= append(r,v.Type()) + r = append(r, v.Type()) } - return r,nil -} \ No newline at end of file + return r, nil +} diff --git a/server/dao/node-mysql/dao-api/api.go b/server/dao/node-mysql/dao-api/api.go index 82f9df1df55236dfdd02568d514a6a90d46bb324..c23da0c0f647f2d4cd3422f403446640b8e878d9 100644 --- a/server/dao/node-mysql/dao-api/api.go +++ b/server/dao/node-mysql/dao-api/api.go @@ -31,11 +31,11 @@ func GetAllApi() (map[int]*entity.Api, error) { if err != nil { continue } - if len(api.RequestURL)==0 || api.RequestURL[0]!= '/'{ - api.RequestURL = fmt.Sprint("/",api.RequestURL) + if len(api.RequestURL) == 0 || api.RequestURL[0] != '/' { + api.RequestURL = fmt.Sprint("/", api.RequestURL) } - if len(api.TargetURL)==0 ||api.TargetURL[0]!= '/'{ - api.TargetURL = fmt.Sprint("/",api.TargetURL) + if len(api.TargetURL) == 0 || api.TargetURL[0] != '/' { + api.TargetURL = fmt.Sprint("/", api.TargetURL) } apiList[api.ApiID] = api diff --git a/server/dao/node-mysql/dao-balance/balance.go b/server/dao/node-mysql/dao-balance/balance.go index 920d1177aeeaebb71f35a530bcefae64f0056da2..87b070896c167a17249d695fd6485ee792667bd5 100644 --- a/server/dao/node-mysql/dao-balance/balance.go +++ b/server/dao/node-mysql/dao-balance/balance.go @@ -5,23 +5,23 @@ import ( entity "github.com/eolinker/goku/server/entity/node-entity" ) -func GetAllBalance() ([]*entity.Balance ,error){ +func GetAllBalance() ([]*entity.Balance, error) { const sql = "SELECT A.`balanceName`,A.`serviceName`,IFNULL(B.`driver`,''),A.`appName`,IFNULL(A.`static`,''),IFNULL(A.`staticCluster`,'') FROM `goku_balance` A LEFT JOIN `goku_service_config` B ON A.`serviceName` = B.`name`;" - db:=database.GetConnection() - rows,err:= db.Query(sql) - if err!= nil{ - return nil,err + db := database.GetConnection() + rows, err := db.Query(sql) + if err != nil { + return nil, err } defer rows.Close() - r:=make([]*entity.Balance,0,20) - for rows.Next(){ - v:=new(entity.Balance) - err:=rows.Scan( &v.Name,&v.ServiceName,&v.ServiceDriver,&v.AppName,&v.Static,&v.StaticCluster) - if err!= nil{ - return nil,err + r := make([]*entity.Balance, 0, 20) + for rows.Next() { + v := new(entity.Balance) + err := rows.Scan(&v.Name, &v.ServiceName, &v.ServiceDriver, &v.AppName, &v.Static, &v.StaticCluster) + if err != nil { + return nil, err } - r= append(r,v.Type()) + r = append(r, v.Type()) } - return r,nil -} \ No newline at end of file + return r, nil +} diff --git a/server/dao/node-mysql/dao-service/service.go b/server/dao/node-mysql/dao-service/service.go index bcd3ea1a491282822fa692e003c33504fcd77627..c87cba192228e87d62efa2ebadccaf60089db486 100644 --- a/server/dao/node-mysql/dao-service/service.go +++ b/server/dao/node-mysql/dao-service/service.go @@ -5,27 +5,28 @@ import ( entity "github.com/eolinker/goku/server/entity/node-entity" ) -const sqlList="SELECT `name`,`driver`,`default`,`desc`,`config`,`clusterConfig`,`healthCheck`,`healthCheckPath`,`healthCheckPeriod`,`healthCheckCode`,`healthCheckTimeOut` FROM `goku_service_config`" -func GetAll() ([]*entity.Service,error) { +const sqlList = "SELECT `name`,`driver`,`default`,`desc`,`config`,`clusterConfig`,`healthCheck`,`healthCheckPath`,`healthCheckPeriod`,`healthCheckCode`,`healthCheckTimeOut` FROM `goku_service_config`" + +func GetAll() ([]*entity.Service, error) { stmt, e := database.GetConnection().Prepare(sqlList) - if e!=nil{ - return nil,e + if e != nil { + return nil, e } defer stmt.Close() - rows,err:=stmt.Query() + rows, err := stmt.Query() - if err!=nil{ - return nil,err + if err != nil { + return nil, err } defer rows.Close() - vs:=make([]*entity.Service,0,10) + vs := make([]*entity.Service, 0, 10) - for rows.Next(){ + for rows.Next() { - v:=new(entity.Service) - er:=rows.Scan(&v.Name, + v := new(entity.Service) + er := rows.Scan(&v.Name, &v.Driver, &v.IsDefault, &v.Desc, @@ -38,12 +39,12 @@ func GetAll() ([]*entity.Service,error) { &v.HealthCheckTimeOut, ) - if er!=nil{ - return nil,er + if er != nil { + return nil, er } - vs = append(vs,v) + vs = append(vs, v) } - return vs,nil + return vs, nil -} \ No newline at end of file +} diff --git a/server/dao/node-mysql/dao-strategy/strategy.go b/server/dao/node-mysql/dao-strategy/strategy.go index a3d5f90ceaebf988e8ed5b8678d6d10d80f8e771..7924c7d6d518dfc81e2863f95f98df142f24235a 100644 --- a/server/dao/node-mysql/dao-strategy/strategy.go +++ b/server/dao/node-mysql/dao-strategy/strategy.go @@ -27,7 +27,7 @@ func GetAllStrategy() (map[string]*entity.Strategy, *entity.Strategy, error) { s := new(entity.Strategy) err := rows.Scan(&s.StrategyID, &s.StrategyName, &s.Auth, &s.EnableStatus, &s.StrategyType) if err != nil { - log.Warn("GetAllStrategy ",err) + log.Warn("GetAllStrategy ", err) continue } diff --git a/server/driver/driver.go b/server/driver/driver.go index 050334f56563b4a91be52bea4707fdf70c093627..0f3b41bff074f409aab7f4c9e2be65e1eadbfff9 100644 --- a/server/driver/driver.go +++ b/server/driver/driver.go @@ -1,39 +1,41 @@ package driver -const( - Static="static" - Discovery="discovery" +const ( + Static = "static" + Discovery = "discovery" ) + type Driver struct { - Name string `json:"name"` - Type string `json:"type"` + Name string `json:"name"` + Type string `json:"type"` Title string `json:"title"` - Desc string `json:"desc"` + Desc string `json:"desc"` } + var ( - all []*Driver - typeNames map[string]string + all []*Driver + typeNames map[string]string driverOfType map[string][]*Driver - drivers map[string]*Driver + drivers map[string]*Driver ) -func init() { - typeNames =map[string]string{ - Static:"静态服务", - Discovery:"服务发现", +func init() { + typeNames = map[string]string{ + Static: "静态服务", + Discovery: "服务发现", } all = []*Driver{ { - Name:"static", - Title:"Static", - Type:Static, - Desc:"静态服务", + Name: "static", + Title: "Static", + Type: Static, + Desc: "静态服务", }, { - Name:"eureka", - Title:"Eureka", - Type:Discovery, - Desc:"Eureka服务发现", + Name: "eureka", + Title: "Eureka", + Type: Discovery, + Desc: "Eureka服务发现", }, { Name: "consul", @@ -45,17 +47,17 @@ func init() { drivers = make(map[string]*Driver) driverOfType = make(map[string][]*Driver) - for t:=range typeNames{ - driverOfType[t] = make([]*Driver,0,len(all)) + for t := range typeNames { + driverOfType[t] = make([]*Driver, 0, len(all)) } - for _,d:=range all{ + for _, d := range all { drivers[d.Name] = d - driverOfType[d.Type] = append(driverOfType[d.Type],d) + driverOfType[d.Type] = append(driverOfType[d.Type], d) } } -func All() []*Driver{ +func All() []*Driver { return all } @@ -63,16 +65,16 @@ func GetByType(t string) []*Driver { return driverOfType[t] } -func Get(name string) (*Driver,bool) { - d,has:=drivers[name] - return d,has +func Get(name string) (*Driver, bool) { + d, has := drivers[name] + return d, has } -func TypeName(t string)(string,bool) { - n,has:=typeNames[t] - return n,has +func TypeName(t string) (string, bool) { + n, has := typeNames[t] + return n, has } func Types() map[string]string { return typeNames -} \ No newline at end of file +} diff --git a/server/entity/balance-entity-service/balance.go b/server/entity/balance-entity-service/balance.go index b38ffdf5afe997335b7debda6d8c00feae352d57..4c804c36f8494a898c4b1122cab8a6758c42e64b 100644 --- a/server/entity/balance-entity-service/balance.go +++ b/server/entity/balance-entity-service/balance.go @@ -3,27 +3,27 @@ package entity import "github.com/eolinker/goku/server/driver" type Balance struct { - Name string - ServiceName string + Name string + ServiceName string ServiceDriver string - ServiceType string - AppName string - Static string + ServiceType string + AppName string + Static string StaticCluster string - Desc string - CreateTime string - UpdateTime string + Desc string + CreateTime string + UpdateTime string } -func (e *Balance)Type()*Balance { +func (e *Balance) Type() *Balance { - if e!=nil{ + if e != nil { - d,has:=driver.Get(e.ServiceDriver) - if has{ + d, has := driver.Get(e.ServiceDriver) + if has { e.ServiceType = d.Type } } return e -} \ No newline at end of file +} diff --git a/server/entity/balance-entity/balance.go b/server/entity/balance-entity/balance.go index 3c5bd6cc111d1c272e91552f7441acd641d275cd..f71c5016f947e9fe19c0d3c0b6050cee6bf18e66 100644 --- a/server/entity/balance-entity/balance.go +++ b/server/entity/balance-entity/balance.go @@ -37,7 +37,6 @@ type BalanceConfig struct { ServersConfigOrg string `json:"staticOrg"` } - type BalanceServerConfig struct { Server string `json:"server"` Weight int `json:"weight"` @@ -46,6 +45,7 @@ type BalanceServerConfig struct { type _OldVersionBalanceInfo struct { BalanceConfig []*BalanceServerConfig `json:"loadBalancingServer"` } + // //func (info *BalanceInfo) Encode() *BalanceInfoEntity { // diff --git a/server/entity/cluster.go b/server/entity/cluster.go index 9fd69ae7c53de3754a6ae6026532d0f383065986..7a3444fbac56e8d486c624e4e6f8fdeeaf759f63 100644 --- a/server/entity/cluster.go +++ b/server/entity/cluster.go @@ -4,9 +4,9 @@ import "fmt" //const ClusterDefaultName = "default" type Cluster struct { - Id int `json:"-" yaml:"-"` - Name string `json:"name" yaml:"name"` - Title string `json:"title" yaml:"title"` + Id int `json:"-" yaml:"-"` + Name string `json:"name" yaml:"name"` + Title string `json:"title" yaml:"title"` } type ClusterInfo struct { Id int `json:"-" yaml:"-"` @@ -40,12 +40,11 @@ func (c *ClusterDB) GetSource() string { return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", c.UserName, c.Password, c.Host, c.Port, c.Database) } - -func (c*ClusterInfo)Cluster()*Cluster { +func (c *ClusterInfo) Cluster() *Cluster { return &Cluster{ - Id:c.Id, - Name:c.Name, - Title:c.Title, + Id: c.Id, + Name: c.Name, + Title: c.Title, } -} \ No newline at end of file +} diff --git a/server/entity/config-log/log.go b/server/entity/config-log/log.go index e64739c76c67f4622e6fb6cdf9fad1d53418c5f7..44e4f2b8784e1d7edc7a2216eca81aa4174c7c2a 100644 --- a/server/entity/config-log/log.go +++ b/server/entity/config-log/log.go @@ -1,13 +1,12 @@ package entity type LogConfig struct { - Name string + Name string Enable int - Dir string - File string - Level string + Dir string + File string + Level string Period string Expire int Fields string } - diff --git a/server/entity/console-entity/ams_import.go b/server/entity/console-entity/ams_import.go index c906a302b3a8ee971f2adfc91a7e09a634631876..ac2ef601032247f9368ed95f345f51e80a4a9001 100644 --- a/server/entity/console-entity/ams_import.go +++ b/server/entity/console-entity/ams_import.go @@ -1,27 +1,27 @@ package entity type AmsProject struct { - ProjectInfo AmsProjectInfo `json:"projectInfo"` - ApiGroupList []AmsGroupInfo `json:"apiGroupList"` + ProjectInfo AmsProjectInfo `json:"projectInfo"` + ApiGroupList []AmsGroupInfo `json:"apiGroupList"` } type AmsProjectInfo struct { - ProjectName string `json:"projectName"` + ProjectName string `json:"projectName"` } type AmsGroupInfo struct { - GroupName string `json:"groupName"` - ChildGroupList []AmsGroupInfo `json:"childGroupList"` - ApiList []AmsApiInfo `json:"apiList"` - ApiGroupChildList []AmsGroupInfo `json:"apiGroupChildList"` + GroupName string `json:"groupName"` + ChildGroupList []AmsGroupInfo `json:"childGroupList"` + ApiList []AmsApiInfo `json:"apiList"` + ApiGroupChildList []AmsGroupInfo `json:"apiGroupChildList"` } type AmsApiInfo struct { - BaseInfo AmsApi `json:"baseInfo"` + BaseInfo AmsApi `json:"baseInfo"` } type AmsApi struct { - ApiName string `json:"apiName"` - ApiURI string `json:"apiURI"` - ApiRequestType int `json:"apiRequestType"` -} \ No newline at end of file + ApiName string `json:"apiName"` + ApiURI string `json:"apiURI"` + ApiRequestType int `json:"apiRequestType"` +} diff --git a/server/entity/console-entity/message.go b/server/entity/console-entity/message.go index b78c5685369bc4f690892ff629f233ad8a7c0f91..abe66e1212b28a8b0d12f497f02784b74cab1ab6 100644 --- a/server/entity/console-entity/message.go +++ b/server/entity/console-entity/message.go @@ -1,8 +1,8 @@ package entity type Message struct { - MsgID int `json:"msgID"` - Msg string `json:"msg"` - UpdateTime string `json:"updateTime"` - MsgType int `json:"msgType"` -} \ No newline at end of file + MsgID int `json:"msgID"` + Msg string `json:"msg"` + UpdateTime string `json:"updateTime"` + MsgType int `json:"msgType"` +} diff --git a/server/entity/console-entity/node.go b/server/entity/console-entity/node.go index 1be7840724549178154e4d1dbab4080fec092980..d2cbe0f7f252b48306d5f8bdfdcb03d43837d594 100644 --- a/server/entity/console-entity/node.go +++ b/server/entity/console-entity/node.go @@ -1,10 +1,10 @@ package entity type Node struct { - NodeID int `json:"nodeID"` - NodeName string `json:"nodeName"` - NodeIP string `json:"nodeIP"` - NodePort string `json:"nodePort"` + NodeID int `json:"nodeID"` + NodeName string `json:"nodeName"` + NodeIP string `json:"nodeIP"` + NodePort string `json:"nodePort"` CreateTime string `json:"createTime"` UpdateTime string `json:"updateTime"` @@ -14,9 +14,9 @@ type Node struct { GroupID int `json:"groupID,omitempty"` GroupName string `json:"groupName,omitempty"` IsUpdate bool `json:"isUpdate"` - Cluster string `json:"cluster"` + Cluster string `json:"cluster"` ClusterTitle string `json:"cluster_title"` - GatewayPath string `json:"gatewayPath"` + GatewayPath string `json:"gatewayPath"` //*SSHInfo } diff --git a/server/entity/console-entity/project.go b/server/entity/console-entity/project.go index a34788ff932ac02d9c08e1aca89dfb36c9f0b14a..75fed4f587df83af35673c438ab0c58c2f97dfe3 100644 --- a/server/entity/console-entity/project.go +++ b/server/entity/console-entity/project.go @@ -1,8 +1,8 @@ package entity type Project struct { - ProjectID int `json:"projectID"` - ProjectName string `json:"projectName"` - CreateTime string `json:"createTime"` - UpdateTime string `json:"updateTime"` -} \ No newline at end of file + ProjectID int `json:"projectID"` + ProjectName string `json:"projectName"` + CreateTime string `json:"createTime"` + UpdateTime string `json:"updateTime"` +} diff --git a/server/entity/console-entity/redis.go b/server/entity/console-entity/redis.go index c7f7b57ad557d51694d36caf8b08429df43335bd..da1d559870f93841e34cbe6595825bcb1dcc6338 100644 --- a/server/entity/console-entity/redis.go +++ b/server/entity/console-entity/redis.go @@ -1,7 +1,7 @@ package entity type RedisNode struct { - Server string - Password string + Server string + Password string ClusterId int } diff --git a/server/entity/console-entity/service.go b/server/entity/console-entity/service.go index af267e560c291a0217b0413becf74a77a349b2f0..a6cf4a39e04b216b178f03ab93fc0930e65645ab 100644 --- a/server/entity/console-entity/service.go +++ b/server/entity/console-entity/service.go @@ -1,18 +1,17 @@ package entity - type Service struct { - Name string - Driver string - Desc string - IsDefault bool - Config string - ClusterConfig string - HealthCheck bool - HealthCheckPath string - HealthCheckPeriod int - HealthCheckCode string + Name string + Driver string + Desc string + IsDefault bool + Config string + ClusterConfig string + HealthCheck bool + HealthCheckPath string + HealthCheckPeriod int + HealthCheckCode string HealthCheckTimeOut int - CreateTime string - UpdateTime string + CreateTime string + UpdateTime string } diff --git a/server/entity/node-entity/api.go b/server/entity/node-entity/api.go index b48eb6c332534c310ddcce789d257b6ad0af87cc..1c13a06528add5a8d357731b98c9e14a30906287 100644 --- a/server/entity/node-entity/api.go +++ b/server/entity/node-entity/api.go @@ -19,6 +19,5 @@ type Api struct { type ApiExtend struct { *Api - Target string - + Target string } diff --git a/server/entity/node-entity/balance.go b/server/entity/node-entity/balance.go index 1cc032034d97654c037a53b9ae2c2fbba69f43ee..42ea4673919f862053da816b7530442c31f2881c 100644 --- a/server/entity/node-entity/balance.go +++ b/server/entity/node-entity/balance.go @@ -3,24 +3,24 @@ package entity import "github.com/eolinker/goku/server/driver" type Balance struct { - Name string - ServiceName string + Name string + ServiceName string ServiceDriver string - ServiceType string - AppName string - Static string + ServiceType string + AppName string + Static string StaticCluster string } -func (e *Balance)Type()*Balance { +func (e *Balance) Type() *Balance { - if e!=nil{ + if e != nil { - d,has:=driver.Get(e.ServiceDriver) - if has{ + d, has := driver.Get(e.ServiceDriver) + if has { e.ServiceType = d.Type } } return e -} \ No newline at end of file +} diff --git a/server/entity/node-entity/service.go b/server/entity/node-entity/service.go index de5404777dbee92e74dfdbbf611828bcaf03e34d..274bd9e2552df2193bc24b6c3b4af136605b6cf7 100644 --- a/server/entity/node-entity/service.go +++ b/server/entity/node-entity/service.go @@ -1,16 +1,15 @@ package entity type Service struct { - Name string - Driver string - Desc string - IsDefault bool - Config string - ClusterConfig string - HealthCheck bool - HealthCheckPath string - HealthCheckPeriod int - HealthCheckCode string + Name string + Driver string + Desc string + IsDefault bool + Config string + ClusterConfig string + HealthCheck bool + HealthCheckPath string + HealthCheckPeriod int + HealthCheckCode string HealthCheckTimeOut int - } diff --git a/server/entity/plugin-entity/plugin.go b/server/entity/plugin-entity/plugin.go index 919d442131c7f8db10630c3c016936e546c19096..250ac12d8d18201978c97b57c06aa7b44b3d6ca9 100644 --- a/server/entity/plugin-entity/plugin.go +++ b/server/entity/plugin-entity/plugin.go @@ -13,13 +13,12 @@ type Plugin struct { IsStop int `json:"isStop"` } - type PluginParams struct { PluginName string `json:"pluginName"` PluginConfig string `json:"pluginConfig"` PluginIndex int `json:"pluginPriority"` //PluginInfo string `json:"pluginInfo"` - IsStop int `json:"isStop"` + IsStop int `json:"isStop"` } type PluginSlice []*Plugin diff --git a/server/monitor/monitor-key/key.go b/server/monitor/monitor-key/key.go index 072be289897dde0ce41cd3d868afffca7ded2591..9a90980753b0afd9252869cb13d93cebac348829 100644 --- a/server/monitor/monitor-key/key.go +++ b/server/monitor/monitor-key/key.go @@ -15,27 +15,26 @@ const ( ProxyStatus5xxCount ProxyTimeoutCount - - MonitorKeyTypeSize = int(ProxyTimeoutCount)+1 - + MonitorKeyTypeSize = int(ProxyTimeoutCount) + 1 ) + var ( keys []MonitorKeyType ) func init() { - ks:=make([]MonitorKeyType,MonitorKeyTypeSize) + ks := make([]MonitorKeyType, MonitorKeyTypeSize) - for i:=range ks{ + for i := range ks { ks[i] = MonitorKeyType(i) } keys = ks } -func Keys()[]MonitorKeyType { +func Keys() []MonitorKeyType { return keys } -func ToString(key int)string { +func ToString(key int) string { return MonitorKeyType(key).String() } func (t MonitorKeyType) String() string { diff --git a/server/monitor/monitor-key/redis.go b/server/monitor/monitor-key/redis.go index a179c1f0e07c762783d186fbf526086ec1dbecff..54dc955f023838d298eb021fc6447601002ca9fd 100644 --- a/server/monitor/monitor-key/redis.go +++ b/server/monitor/monitor-key/redis.go @@ -4,34 +4,34 @@ import ( "bytes" ) -func StrategyMapKey(cluster,now string)string { - key:= splicing("monitor-strategy:",cluster,":",now) +func StrategyMapKey(cluster, now string) string { + key := splicing("monitor-strategy:", cluster, ":", now) //fmt.Println("StrategyMapKey:",key) return key } -func APiMapKey(cluster,strategyId ,now string) string { - key:= splicing("monitor-api:",cluster,":",strategyId,":",now) +func APiMapKey(cluster, strategyId, now string) string { + key := splicing("monitor-api:", cluster, ":", strategyId, ":", now) //fmt.Println("APiMapKey:",key) return key } -func ApiValueKey(cluster,strategyId string,apiId string,now string)string { - key := splicing("monitor-value:",cluster,":",strategyId,":",apiId,":",now) +func ApiValueKey(cluster, strategyId string, apiId string, now string) string { + key := splicing("monitor-value:", cluster, ":", strategyId, ":", apiId, ":", now) //fmt.Println("ApiValueKey:",key) return key } -func splicing(args ...string)string { +func splicing(args ...string) string { - l:= 0 - for _,arg:= range args{ + l := 0 + for _, arg := range args { - l+= len(arg) + l += len(arg) } - buf:=make([]byte,0,l) - b:=bytes.NewBuffer(buf) + buf := make([]byte, 0, l) + b := bytes.NewBuffer(buf) - for _,arg:= range args{ + for _, arg := range args { b.WriteString(arg) } return b.String() -} \ No newline at end of file +} diff --git a/server/monitor/monitor-key/value.go b/server/monitor/monitor-key/value.go index bc730cb3a346f5584af057fad03f38e20ee89401..98e4dd4b06d793cb04f3c7883db19312a622812b 100644 --- a/server/monitor/monitor-key/value.go +++ b/server/monitor/monitor-key/value.go @@ -2,37 +2,36 @@ package monitor_key type MonitorValues []int64 - -func (a MonitorValues) Add(key MonitorKeyType) { +func (a MonitorValues) Add(key MonitorKeyType) { index := int(key) - if index < len(a){ + if index < len(a) { a[index]++ } } -func (a MonitorValues)Get(key MonitorKeyType) int64 { - if a==nil{ +func (a MonitorValues) Get(key MonitorKeyType) int64 { + if a == nil { return 0 } index := int(key) - if index < len(a){ + if index < len(a) { return a[index] } return 0 } -func (a MonitorValues)Append(args ...MonitorValues) { +func (a MonitorValues) Append(args ...MonitorValues) { if len(args) == 0 { return } - for _,arg:=range args{ + for _, arg := range args { - for i:=range arg{ - a[i]+= arg[i] + for i := range arg { + a[i] += arg[i] } } return } func MakeValue() MonitorValues { - return make(MonitorValues,MonitorKeyTypeSize) -} \ No newline at end of file + return make(MonitorValues, MonitorKeyTypeSize) +} diff --git a/server/monitor/monitor-read/monitor.go b/server/monitor/monitor-read/monitor.go index 36c397ab73cbca3325fc1b17c8b75de7b53b401b..066ba908b313a5cc9db4a4dc81d5738d37d45a36 100644 --- a/server/monitor/monitor-read/monitor.go +++ b/server/monitor/monitor-read/monitor.go @@ -9,87 +9,87 @@ import ( "strconv" "time" ) + var ( - period = 30*time.Second + period = 30 * time.Second ) -func SetPeriod(sec int) { - period = time.Duration(sec)* time.Second +func SetPeriod(sec int) { + period = time.Duration(sec) * time.Second } func InitMonitorRead(clusters []*entity.Cluster) error { - for _,c:=range clusters{ - _,has:= redis_manager.Get(c.Name) - if !has{ - return fmt.Errorf("no redis for cluster:%s",c.Name) + for _, c := range clusters { + _, has := redis_manager.Get(c.Name) + if !has { + return fmt.Errorf("no redis for cluster:%s", c.Name) } } - for _,c:=range clusters{ - go doLoopForCluster(c.Name,c.Id) + for _, c := range clusters { + go doLoopForCluster(c.Name, c.Id) } return nil } -func doLoopForCluster(clusterName string,clusterId int) { +func doLoopForCluster(clusterName string, clusterId int) { + t := time.NewTimer(period) - t:=time.NewTimer(period) - - for{ + for { select { - case <-t.C:{ - read(clusterName,clusterId,time.Now()) - } + case <-t.C: + { + read(clusterName, clusterId, time.Now()) + } } t.Reset(period) } } -func read(clusterName string,clusterId int,t time.Time) { - hour:= t.Format("2006010215") - now:= t.Format("2006-01-02 15:04:05") +func read(clusterName string, clusterId int, t time.Time) { + hour := t.Format("2006010215") + now := t.Format("2006-01-02 15:04:05") - - hourValue ,_:=strconv.Atoi(hour) + hourValue, _ := strconv.Atoi(hour) // 包含 strate == "" - strategyIds,err:=readStrategyId(hour,clusterName) - if err!= nil{ + strategyIds, err := readStrategyId(hour, clusterName) + if err != nil { return } - for _,strategyId:=range strategyIds{ + for _, strategyId := range strategyIds { - apiIds,err:=readApiId(hour,clusterName,strategyId) - if err!= nil{ + apiIds, err := readApiId(hour, clusterName, strategyId) + if err != nil { continue } - for _,apiId:=range apiIds{ + for _, apiId := range apiIds { - valus,err:=readValue(hour,clusterName,strategyId,apiId) - if err!=nil{ + valus, err := readValue(hour, clusterName, strategyId, apiId) + if err != nil { continue } - apiID ,_:= strconv.Atoi(apiId) + apiID, _ := strconv.Atoi(apiId) - dao_monitor.Save(strategyId,apiID,clusterId,hourValue,now,valus) + dao_monitor.Save(strategyId, apiID, clusterId, hourValue, now, valus) } } } -func readStrategyId(now,cluster string)([]string ,error) { - key:= monitor_key.StrategyMapKey(cluster,now) - conn,_:= redis_manager.Get(cluster) +func readStrategyId(now, cluster string) ([]string, error) { + key := monitor_key.StrategyMapKey(cluster, now) + conn, _ := redis_manager.Get(cluster) return conn.HKeys(key).Result() } -func readApiId(now ,cluster,strategyId string)([]string ,error){ - key:= monitor_key.APiMapKey(cluster,strategyId,now) - conn,_:= redis_manager.Get(cluster) +func readApiId(now, cluster, strategyId string) ([]string, error) { + key := monitor_key.APiMapKey(cluster, strategyId, now) + conn, _ := redis_manager.Get(cluster) return conn.HKeys(key).Result() } -func readValue(now,cluster,strategyId string,apiId string) (map[string]string,error) { - conn,_:= redis_manager.Get(cluster) - key := monitor_key.ApiValueKey(cluster,strategyId,apiId,now) +func readValue(now, cluster, strategyId string, apiId string) (map[string]string, error) { + conn, _ := redis_manager.Get(cluster) + key := monitor_key.ApiValueKey(cluster, strategyId, apiId, now) return conn.HGetAll(key).Result() -} \ No newline at end of file +} diff --git a/server/monitor/monitor-write/monitor.go b/server/monitor/monitor-write/monitor.go index 89d3996ec393f4b7fd082ed1deef86b5f05aa6d8..1aeb067a1d4fa5c9ac6a5d847bab79301668a8ea 100644 --- a/server/monitor/monitor-write/monitor.go +++ b/server/monitor/monitor-write/monitor.go @@ -83,7 +83,7 @@ func temporaryStorage() { select { case <-t.C: - if len(ts.strategys)>0{ + if len(ts.strategys) > 0 { o := ts ts = &_MonitorMap{ strategys: make(map[string]*_StrategyInfo), diff --git a/utils/alert.go b/utils/alert.go index d76e16b7409d460b13bec7dedf528dd8ebb12eb5..274650d17accb001f5fdde0a9e4b2a52fbfa2809 100644 --- a/utils/alert.go +++ b/utils/alert.go @@ -4,7 +4,6 @@ import ( log "github.com/eolinker/goku/goku-log" "io/ioutil" "net" - "os" "strings" "time" ) @@ -36,10 +35,10 @@ func SendAlertMail(sender, senderPassword, smtpAddress, smtpPort, smtpProtocol, bodyStr = strings.Replace(bodyStr, "$apiName", apiName, -1) host := net.JoinHostPort(smtpAddress, smtpPort) subject := "GoKu告警:" + requestURL + "接口在" + period[alertPeriod] + "分钟内转发失败" + alertCount + "次" - err = SendToMail(sender, senderPassword, host, receiverMail, subject, bodyStr, "html", smtpProtocol) + err := SendToMail(sender, senderPassword, host, receiverMail, subject, bodyStr, "html", smtpProtocol) if err != nil { - log.Warn("SendAlertMail:",err) + log.Warn("SendAlertMail:", err) + return false, err } return true, nil } - diff --git a/utils/mail.go b/utils/mail.go index e962644784362e2c4b82c1e6de07d402bec5630d..4231fcba562bd4498d61b86e6dd7bccb4e8ef45c 100644 --- a/utils/mail.go +++ b/utils/mail.go @@ -34,7 +34,7 @@ func SendToMail(user, password, host, to, subject, body, mailtype, smtpProtocol } var err error msg := []byte("To: " + to + "\r\nFrom: " + user + ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body) - log.Debug("SendToMail",msg) + log.Debug("SendToMail", msg) if smtpProtocol != "0" { err = SendMailUsingTLS( host, diff --git a/utils/ssh.go b/utils/ssh.go index 4f4bcb3fa25431da2d691146e6e7711a33110932..1f78ab8d1700433d67b1940216b638026c60d0a3 100644 --- a/utils/ssh.go +++ b/utils/ssh.go @@ -1,88 +1,88 @@ package utils import ( - "fmt" - "golang.org/x/crypto/ssh" - "net" - "time" - // "io/ioutil" + "fmt" + "golang.org/x/crypto/ssh" + "net" + "time" + // "io/ioutil" ) func Connect(user, password, host, key string, port int, cipherList []string) (*ssh.Session, error) { - var ( - auth []ssh.AuthMethod - addr string - clientConfig *ssh.ClientConfig - client *ssh.Client - config ssh.Config - session *ssh.Session - err error - ) - // get auth method - auth = make([]ssh.AuthMethod, 0) - if key == "" { - auth = append(auth, ssh.Password(password)) - } else { - // pemBytes, err := ioutil.ReadFile(key) - // if err != nil { - // return nil, err - // } - // fmt.Println(key) + var ( + auth []ssh.AuthMethod + addr string + clientConfig *ssh.ClientConfig + client *ssh.Client + config ssh.Config + session *ssh.Session + err error + ) + // get auth method + auth = make([]ssh.AuthMethod, 0) + if key == "" { + auth = append(auth, ssh.Password(password)) + } else { + // pemBytes, err := ioutil.ReadFile(key) + // if err != nil { + // return nil, err + // } + // fmt.Println(key) - pemBytes := []byte(key) - var signer ssh.Signer - if password == "" { - signer, err = ssh.ParsePrivateKey(pemBytes) - } else { + pemBytes := []byte(key) + var signer ssh.Signer + if password == "" { + signer, err = ssh.ParsePrivateKey(pemBytes) + } else { // 使用私钥解析密码 - signer, err = ssh.ParsePrivateKeyWithPassphrase(pemBytes, []byte(password)) - } - if err != nil { - return nil, err - } - auth = append(auth, ssh.PublicKeys(signer)) - } - - if len(cipherList) == 0 { - config = ssh.Config{ - Ciphers: []string{"aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "arcfour256", "arcfour128", "aes128-cbc", "3des-cbc", "aes192-cbc", "aes256-cbc"}, - } - } else { - config = ssh.Config{ - Ciphers: cipherList, - } - } - clientConfig = &ssh.ClientConfig{ - User: user, - Auth: auth, - Timeout: 30 * time.Second, - Config: config, - HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error { - return nil - }, - } - - // connet to ssh - addr = fmt.Sprintf("%s:%d", host, port) - - if client, err = ssh.Dial("tcp", addr, clientConfig); err != nil { - return nil, err - } - - // create session - if session, err = client.NewSession(); err != nil { - return nil, err - } - - modes := ssh.TerminalModes{ - ssh.ECHO: 0, // disable echoing - ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud - ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud - } - - if err := session.RequestPty("xterm", 80, 40, modes); err != nil { - return nil, err - } - - return session, nil -} \ No newline at end of file + signer, err = ssh.ParsePrivateKeyWithPassphrase(pemBytes, []byte(password)) + } + if err != nil { + return nil, err + } + auth = append(auth, ssh.PublicKeys(signer)) + } + + if len(cipherList) == 0 { + config = ssh.Config{ + Ciphers: []string{"aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "arcfour256", "arcfour128", "aes128-cbc", "3des-cbc", "aes192-cbc", "aes256-cbc"}, + } + } else { + config = ssh.Config{ + Ciphers: cipherList, + } + } + clientConfig = &ssh.ClientConfig{ + User: user, + Auth: auth, + Timeout: 30 * time.Second, + Config: config, + HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error { + return nil + }, + } + + // connet to ssh + addr = fmt.Sprintf("%s:%d", host, port) + + if client, err = ssh.Dial("tcp", addr, clientConfig); err != nil { + return nil, err + } + + // create session + if session, err = client.NewSession(); err != nil { + return nil, err + } + + modes := ssh.TerminalModes{ + ssh.ECHO: 0, // disable echoing + ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud + ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud + } + + if err := session.RequestPty("xterm", 80, 40, modes); err != nil { + return nil, err + } + + return session, nil +} diff --git a/utils/string.go b/utils/string.go index d364b2c2dc5179b7c3e64bd6f83069c6a63d53be..b7361a9c269dd01eef9989f6778e067f3f81639a 100644 --- a/utils/string.go +++ b/utils/string.go @@ -2,18 +2,18 @@ package utils import "strings" -func TrimPrefixAll(s string,r string) string{ +func TrimPrefixAll(s string, r string) string { - for strings.HasPrefix(s,r){ - s= strings.TrimPrefix(s,r) + for strings.HasPrefix(s, r) { + s = strings.TrimPrefix(s, r) } return s } -func TrimSuffixAll(s string,r string) string{ +func TrimSuffixAll(s string, r string) string { - for strings.HasSuffix(s,r){ - s= strings.TrimSuffix(s,r) + for strings.HasSuffix(s, r) { + s = strings.TrimSuffix(s, r) } return s -} \ No newline at end of file +} diff --git a/utils/uuid.go b/utils/uuid.go index 9bc1e5d8d0fa9a48077af159cfc822f23ce4271e..3fff6e8d27a9ff3b644f20d90855feb00732c53c 100644 --- a/utils/uuid.go +++ b/utils/uuid.go @@ -1,16 +1,15 @@ - package utils import ( + "log" + "os/exec" "strings" - "log" - "os/exec" ) - + func TimeUUID() string { - out, err := exec.Command("uuidgen").Output() - if err != nil { - log.Fatal(err) - } - return strings.Replace(string(out),"\n","",-1) -} \ No newline at end of file + out, err := exec.Command("uuidgen").Output() + if err != nil { + log.Fatal(err) + } + return strings.Replace(string(out), "\n", "", -1) +}