diff --git a/namespace/namespace.go b/namespace/namespace.go index 8da93b292..bef2508ab 100644 --- a/namespace/namespace.go +++ b/namespace/namespace.go @@ -31,6 +31,8 @@ import ( "github.com/polarismesh/polaris/common/utils" ) +var _ NamespaceOperateServer = (*Server)(nil) + func (s *Server) allowAutoCreate() bool { return s.cfg.AutoCreate } diff --git a/plugin/auth.go b/plugin/auth.go index ce8697e60..af0ad4994 100644 --- a/plugin/auth.go +++ b/plugin/auth.go @@ -26,10 +26,8 @@ import ( "github.com/polarismesh/polaris/common/log" ) -var ( - // 插件初始化原子变量 - authOnce = &sync.Once{} -) +// 插件初始化原子变量 +var authOnce sync.Once // Auth AUTH插件接口 type Auth interface { diff --git a/plugin/auth/defaultauth/auth.go b/plugin/auth/defaultauth/auth.go index 1287dd31a..c675eda91 100644 --- a/plugin/auth/defaultauth/auth.go +++ b/plugin/auth/defaultauth/auth.go @@ -65,29 +65,25 @@ func (da *defaultAuth) Allow(platformID, platformToken string) bool { // CheckPermission 权限检查 func (da *defaultAuth) CheckPermission(reqCtx interface{}, authRule interface{}) (bool, error) { - ctx, ok := reqCtx.(*model.AcquireContext) if !ok { return false, ErrorInvalidParameter } userId := utils.ParseUserID(ctx.GetRequestContext()) - strategies, ok := authRule.([]*model.StrategyDetail) - + strategies, _ := authRule.([]*model.StrategyDetail) if len(strategies) == 0 { return true, nil } reqRes := ctx.GetAccessResources() var ( - checkNamespace bool = false - checkService bool = true - checkConfigGroup bool = true + checkNamespace = false + checkService = true + checkConfigGroup = true ) - for index := range strategies { - rule := strategies[index] - + for _, rule := range strategies { if !da.checkAction(rule.Action, ctx.GetOperation()) { continue } @@ -133,18 +129,15 @@ func (da *defaultAuth) checkAction(expect string, actual model.ResourceOperation // @param searchMaps 鉴权策略中某一类型的资源列表信息 // @return bool 是否可以操作本次被访问的所有资源 func checkAnyElementExist(userId string, waitSearch []model.ResourceEntry, searchMaps *SearchMap) bool { - if len(waitSearch) == 0 { - return true - } - if searchMaps.passAll { + if len(waitSearch) == 0 || searchMaps.passAll { return true } - for i := range waitSearch { - entry := waitSearch[i] + for _, entry := range waitSearch { if entry.Owner == userId { continue } + if _, ok := searchMaps.items[entry.ID]; !ok { return false } @@ -168,8 +161,7 @@ func buildSearchMap(ss []model.StrategyResource) []*SearchMap { passAll: false, } - for i := range ss { - val := ss[i] + for _, val := range ss { if val.ResType == int32(api.ResourceType_Namespaces) { nsSearchMaps.items[val.ResID] = emptyVal nsSearchMaps.passAll = (val.ResID == "*") || nsSearchMaps.passAll diff --git a/plugin/auth/defaultauth/default.go b/plugin/auth/defaultauth/default.go index c4aff31dc..de7ec57d9 100644 --- a/plugin/auth/defaultauth/default.go +++ b/plugin/auth/defaultauth/default.go @@ -27,7 +27,7 @@ const ( var ( // emptyVal 空对象,占位而已 - emptyVal struct{} = struct{}{} + emptyVal = struct{}{} ) // 自注册到插件列表 diff --git a/plugin/auth/platform/platform.go b/plugin/auth/platform/platform.go index 9097ec688..8601f4599 100644 --- a/plugin/auth/platform/platform.go +++ b/plugin/auth/platform/platform.go @@ -35,7 +35,7 @@ const ( // PluginName plugin name PluginName = "platform" // DefaultTimeDiff default time diff - DefaultTimeDiff = -1 * time.Second * 5 + DefaultTimeDiff = -5 * time.Second ) // init 初始化注册函数 diff --git a/plugin/cmdb/memory/memory.go b/plugin/cmdb/memory/memory.go index f8185ba8f..8f9107e5e 100644 --- a/plugin/cmdb/memory/memory.go +++ b/plugin/cmdb/memory/memory.go @@ -62,14 +62,11 @@ func (m *Memory) GetLocation(host string) (*model.Location, error) { // Range 实现CMDB插件接口 func (m *Memory) Range(handler func(host string, location *model.Location) (bool, error)) error { - cont, err := handler("", nil) + _, err := handler("", nil) if err != nil { return err } - if !cont { - return nil - } return nil } diff --git a/plugin/discoverevent.go b/plugin/discoverevent.go index 2297e7170..bd18c3599 100644 --- a/plugin/discoverevent.go +++ b/plugin/discoverevent.go @@ -25,9 +25,7 @@ import ( "github.com/polarismesh/polaris/common/model" ) -var ( - discoverEventOnce = &sync.Once{} -) +var discoverEventOnce sync.Once // DiscoverChannel is used to receive discover events from the agent type DiscoverChannel interface { diff --git a/plugin/discoverevent/local/event_local.go b/plugin/discoverevent/local/event_local.go index 466d81a01..31ab575bc 100644 --- a/plugin/discoverevent/local/event_local.go +++ b/plugin/discoverevent/local/event_local.go @@ -32,12 +32,8 @@ import ( ) const ( - PluginName string = "discoverEventLocal" - defaultBufferSize int = 1024 -) - -var ( - emptyModelDiscoverEvent = model.DiscoverEvent{} + PluginName = "discoverEventLocal" + defaultBufferSize = 1024 ) func init() { @@ -100,10 +96,10 @@ func (holder *eventBufferHolder) Size() int { type discoverEventLocal struct { eventCh chan model.DiscoverEvent eventLog *zap.Logger - bufferPool *sync.Pool + bufferPool sync.Pool curEventBuffer *eventBufferHolder cursor int - syncLock *sync.Mutex + syncLock sync.Mutex } // Name 插件名称 @@ -137,8 +133,7 @@ func (el *discoverEventLocal) Initialize(conf *plugin.ConfigEntry) error { config.RotationMaxAge, ) - el.syncLock = &sync.Mutex{} - el.bufferPool = &sync.Pool{ + el.bufferPool = sync.Pool{ New: func() interface{} { return newEventBufferHolder(defaultBufferSize) }, @@ -168,9 +163,9 @@ func (el *discoverEventLocal) PublishEvent(event model.DiscoverEvent) { // Run 执行主逻辑 func (el *discoverEventLocal) Run() { - // 定时刷新事件到日志的定时器 syncInterval := time.NewTicker(time.Duration(10) * time.Second) + defer syncInterval.Stop() for { select { @@ -199,19 +194,15 @@ func (el *discoverEventLocal) switchEventBuffer() { // writeToFile 事件落盘 func (el *discoverEventLocal) writeToFile(eventHolder *eventBufferHolder) { - el.syncLock.Lock() - defer func() { el.syncLock.Unlock() eventHolder.Reset() el.bufferPool.Put(eventHolder) - }() for eventHolder.HasNext() { event := eventHolder.Next() - el.eventLog.Info(fmt.Sprintf( "%s|%s|%s|%d|%s|%d|%s", event.Namespace, diff --git a/plugin/discoverevent/loki/event_loki.go b/plugin/discoverevent/loki/event_loki.go index d8c277167..eb67ff2cf 100644 --- a/plugin/discoverevent/loki/event_loki.go +++ b/plugin/discoverevent/loki/event_loki.go @@ -25,9 +25,9 @@ import ( ) const ( - PluginName string = "discoverEventLoki" - defaultBatchSize int = 512 - defaultQueueSize int = 1024 + PluginName = "discoverEventLoki" + defaultBatchSize = 512 + defaultQueueSize = 1024 ) func init() { @@ -61,7 +61,7 @@ func (d *discoverEventLoki) Initialize(conf *plugin.ConfigEntry) error { } d.eventLog = lokiLogger d.eventCh = make(chan model.DiscoverEvent, queueSize) - d.stopCh = make(chan struct{}) + d.stopCh = make(chan struct{}, 1) go d.Run() return nil } diff --git a/plugin/discoverevent/loki/event_loki_test.go b/plugin/discoverevent/loki/event_loki_test.go index 322dd639e..b1e736548 100644 --- a/plugin/discoverevent/loki/event_loki_test.go +++ b/plugin/discoverevent/loki/event_loki_test.go @@ -88,7 +88,7 @@ func Test_discoverEventLoki_Destroy(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { d := &discoverEventLoki{ - stopCh: make(chan struct{}), + stopCh: make(chan struct{}, 1), } err := d.Destroy() assert.Nil(t, err) diff --git a/plugin/discoverevent/loki/logger.go b/plugin/discoverevent/loki/logger.go index 3006ee9ab..4f3213bfc 100644 --- a/plugin/discoverevent/loki/logger.go +++ b/plugin/discoverevent/loki/logger.go @@ -152,14 +152,16 @@ func (l *LokiLogger) Log(events []model.DiscoverEvent) { log.Errorf("[Discoverevent][LokiLogger] marshal push request error: %v", err) return } + buf = snappy.Encode(nil, buf) resp, err := l.send(context.Background(), buf) if err != nil { log.Errorf("[Discoverevent][LokiLogger] send request error: %v", err) return } + defer resp.Body.Close() + if resp.StatusCode != http.StatusNoContent { - defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Errorf("[Discoverevent][LokiLogger] read resp body error: %v", err) @@ -178,6 +180,7 @@ func (l *LokiLogger) send(ctx context.Context, reqBody []byte) (*http.Response, if err != nil { return nil, err } + req = req.WithContext(ctx) req.Header.Set("Content-Type", contentType) if l.tenantID != "" { diff --git a/plugin/discoverstatis.go b/plugin/discoverstatis.go index 6b9df5bdc..7c7b627ec 100644 --- a/plugin/discoverstatis.go +++ b/plugin/discoverstatis.go @@ -25,9 +25,7 @@ import ( "github.com/polarismesh/polaris/common/log" ) -var ( - discoverStatisOnce = &sync.Once{} -) +var discoverStatisOnce sync.Once // DiscoverStatis 服务发现统计插件接口 type DiscoverStatis interface { diff --git a/plugin/history.go b/plugin/history.go index 95fbfd7c3..6d0c056ae 100644 --- a/plugin/history.go +++ b/plugin/history.go @@ -25,10 +25,8 @@ import ( "github.com/polarismesh/polaris/common/model" ) -var ( - // 插件初始化原子变量 - historyOnce = &sync.Once{} -) +// 插件初始化原子变量 +var historyOnce sync.Once // History 历史记录插件 type History interface { diff --git a/plugin/history/loki/history_loki.go b/plugin/history/loki/history_loki.go index 736a379d9..6a1879303 100644 --- a/plugin/history/loki/history_loki.go +++ b/plugin/history/loki/history_loki.go @@ -29,9 +29,9 @@ import ( // 把操作记录记录到Loki const ( // PluginName plugin name - PluginName string = "HistoryLoki" - defaultBatchSize int = 512 - defaultQueueSize int = 1024 + PluginName = "HistoryLoki" + defaultBatchSize = 512 + defaultQueueSize = 1024 ) func init() { @@ -65,7 +65,7 @@ func (h *HistoryLoki) Initialize(conf *plugin.ConfigEntry) error { } h.logger = lokiLogger h.entryCh = make(chan *model.RecordEntry, queueSize) - h.stopCh = make(chan struct{}) + h.stopCh = make(chan struct{}, 1) go h.Run() return nil } diff --git a/plugin/history/loki/history_loki_test.go b/plugin/history/loki/history_loki_test.go index 86c4f194d..23e156b75 100644 --- a/plugin/history/loki/history_loki_test.go +++ b/plugin/history/loki/history_loki_test.go @@ -94,7 +94,7 @@ func TestHistoryLoki_Destroy(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { d := &HistoryLoki{ - stopCh: make(chan struct{}), + stopCh: make(chan struct{}, 1), } err := d.Destroy() assert.Nil(t, err) diff --git a/plugin/history/loki/logger.go b/plugin/history/loki/logger.go index f315c0fe9..6401b9d3f 100644 --- a/plugin/history/loki/logger.go +++ b/plugin/history/loki/logger.go @@ -157,8 +157,9 @@ func (l *LokiLogger) Log(entries []*model.RecordEntry) { log.Errorf("[History][LokiLogger] send request error: %v", err) return } + defer resp.Body.Close() + if resp.StatusCode != http.StatusNoContent { - defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Errorf("[History][LokiLogger] read resp body error: %v", err) diff --git a/plugin/password.go b/plugin/password.go index 4aa44e106..0d8f00ea8 100644 --- a/plugin/password.go +++ b/plugin/password.go @@ -24,9 +24,7 @@ import ( "github.com/polarismesh/polaris/common/log" ) -var ( - passwordOnce = &sync.Once{} -) +var passwordOnce sync.Once // ParsePassword 密码插件 type ParsePassword interface { diff --git a/plugin/plugin.go b/plugin/plugin.go index 08da1172b..ec44a8704 100644 --- a/plugin/plugin.go +++ b/plugin/plugin.go @@ -25,7 +25,7 @@ import ( var ( pluginSet = make(map[string]Plugin) config = &Config{} - once = &sync.Once{} + once sync.Once ) // RegisterPlugin 注册插件 diff --git a/plugin/ratelimit.go b/plugin/ratelimit.go index 41bb160c7..f388de0c9 100644 --- a/plugin/ratelimit.go +++ b/plugin/ratelimit.go @@ -49,9 +49,7 @@ var RatelimitStr = map[RatelimitType]string{ InstanceRatelimit: "instance-limit", } -var ( - rateLimitOnce = sync.Once{} -) +var rateLimitOnce sync.Once // Ratelimit Ratelimit插件接口 type Ratelimit interface { diff --git a/plugin/ratelimit/lrurate/base.go b/plugin/ratelimit/lrurate/base.go index 42c3ccce0..dc058daf3 100644 --- a/plugin/ratelimit/lrurate/base.go +++ b/plugin/ratelimit/lrurate/base.go @@ -54,11 +54,8 @@ func hash(str string) uint32 { // allowIP ip限流 func allowIP(id string) bool { key := hash(id) - ipLruCache.ContainsOrAdd(key, rate.NewLimiter(rate.Limit(rateLimitIPRate), rateLimitIPBurst)) - - value, ok := ipLruCache.Get(key) - if ok { + if value, ok := ipLruCache.Get(key); ok { return value.(*rate.Limiter).Allow() } @@ -68,11 +65,8 @@ func allowIP(id string) bool { // allowService service限流 func allowService(id string) bool { key := hash(id) - serviceLruCache.ContainsOrAdd(key, rate.NewLimiter(rate.Limit(rateLimitServiceRate), rateLimitServiceBurst)) - - value, ok := serviceLruCache.Get(key) - if ok { + if value, ok := serviceLruCache.Get(key); ok { return value.(*rate.Limiter).Allow() } diff --git a/plugin/ratelimit/lrurate/lrurate.go b/plugin/ratelimit/lrurate/lrurate.go index 2a6959531..83fc280f0 100644 --- a/plugin/ratelimit/lrurate/lrurate.go +++ b/plugin/ratelimit/lrurate/lrurate.go @@ -137,7 +137,7 @@ func (m *LRURate) Destroy() error { // Allow 实现CMDB插件接口 func (m *LRURate) Allow(rateType plugin.RatelimitType, id string) bool { - switch plugin.RatelimitType(rateType) { + switch rateType { case plugin.IPRatelimit: return allowIP(id) case plugin.ServiceRatelimit: diff --git a/plugin/ratelimit/token/api_limit.go b/plugin/ratelimit/token/api_limit.go index 999867b0a..469970f42 100644 --- a/plugin/ratelimit/token/api_limit.go +++ b/plugin/ratelimit/token/api_limit.go @@ -29,7 +29,7 @@ import ( // apiRatelimit 接口限流类 type apiRatelimit struct { rules map[string]*BucketRatelimit // 存储规则 - apis *sync.Map // 存储api -> apiLimiter + apis sync.Map // 存储api -> apiLimiter config *APILimitConfig } @@ -67,7 +67,7 @@ func (art *apiRatelimit) parseRules(rules []*RateLimitRule) error { return errors.New("invalid api rate limit config, rules are empty") } - art.rules = make(map[string]*BucketRatelimit) + art.rules = make(map[string]*BucketRatelimit, len(rules)) for _, entry := range rules { if entry.Name == "" { return errors.New("invalid api rate limit config, some rules name are empty") @@ -90,7 +90,6 @@ func (art *apiRatelimit) parseApis(apis []*APILimitInfo) error { return errors.New("invalid api rate limit config, apis are empty") } - art.apis = new(sync.Map) for _, entry := range apis { if entry.Name == "" { return errors.New("invalid api rate limit config, api name is empty") @@ -98,6 +97,7 @@ func (art *apiRatelimit) parseApis(apis []*APILimitInfo) error { if entry.Rule == "" { return errors.New("invalid api rate limit config, api rule is empty") } + limit, ok := art.rules[entry.Rule] if !ok { return errors.New("invalid api rate limit config, api rule is not found") diff --git a/plugin/statis.go b/plugin/statis.go index 6b80794a2..c2029129a 100644 --- a/plugin/statis.go +++ b/plugin/statis.go @@ -24,9 +24,7 @@ import ( "github.com/polarismesh/polaris/common/log" ) -var ( - statisOnce = &sync.Once{} -) +var statisOnce sync.Once const ( ComponentServer = "server" diff --git a/plugin/statis/local/common.go b/plugin/statis/local/common.go index 43ace9248..0e504ebbd 100644 --- a/plugin/statis/local/common.go +++ b/plugin/statis/local/common.go @@ -59,7 +59,7 @@ const ( var ( // metricDescList Metrics Description Defines the list - metricDescList []metricDesc = []metricDesc{ + metricDescList = []metricDesc{ { Name: MetricForClientRqTotal, Help: "total number of client requests", diff --git a/plugin/statis/local/local.go b/plugin/statis/local/local.go index 65478ed58..74697c0f6 100644 --- a/plugin/statis/local/local.go +++ b/plugin/statis/local/local.go @@ -149,9 +149,7 @@ func (s *StatisWorker) Run() { time.Sleep(time.Duration(diff) * time.Second) ticker := time.NewTicker(s.interval) - defer func() { - ticker.Stop() - }() + defer ticker.Stop() for { select {