Skip to content

Commit

Permalink
feat: update plugin for code style (polarismesh#733)
Browse files Browse the repository at this point in the history
* feat: update namespace for code style

* feat: update plugin for code style.
  • Loading branch information
daheige committed Oct 11, 2022
1 parent ed3d7a0 commit 90ad169
Show file tree
Hide file tree
Showing 25 changed files with 54 additions and 90 deletions.
2 changes: 2 additions & 0 deletions namespace/namespace.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import (
"github.com/polarismesh/polaris/common/utils"
)

var _ NamespaceOperateServer = (*Server)(nil)

func (s *Server) allowAutoCreate() bool {
return s.cfg.AutoCreate
}
Expand Down
6 changes: 2 additions & 4 deletions plugin/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,8 @@ import (
"github.com/polarismesh/polaris/common/log"
)

var (
// 插件初始化原子变量
authOnce = &sync.Once{}
)
// 插件初始化原子变量
var authOnce sync.Once

// Auth AUTH插件接口
type Auth interface {
Expand Down
26 changes: 9 additions & 17 deletions plugin/auth/defaultauth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion plugin/auth/defaultauth/default.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const (

var (
// emptyVal 空对象,占位而已
emptyVal struct{} = struct{}{}
emptyVal = struct{}{}
)

// 自注册到插件列表
Expand Down
2 changes: 1 addition & 1 deletion plugin/auth/platform/platform.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const (
// PluginName plugin name
PluginName = "platform"
// DefaultTimeDiff default time diff
DefaultTimeDiff = -1 * time.Second * 5
DefaultTimeDiff = -5 * time.Second
)

// init 初始化注册函数
Expand Down
5 changes: 1 addition & 4 deletions plugin/cmdb/memory/memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
4 changes: 1 addition & 3 deletions plugin/discoverevent.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
21 changes: 6 additions & 15 deletions plugin/discoverevent/local/event_local.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,8 @@ import (
)

const (
PluginName string = "discoverEventLocal"
defaultBufferSize int = 1024
)

var (
emptyModelDiscoverEvent = model.DiscoverEvent{}
PluginName = "discoverEventLocal"
defaultBufferSize = 1024
)

func init() {
Expand Down Expand Up @@ -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 插件名称
Expand Down Expand Up @@ -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)
},
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down
8 changes: 4 additions & 4 deletions plugin/discoverevent/loki/event_loki.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ import (
)

const (
PluginName string = "discoverEventLoki"
defaultBatchSize int = 512
defaultQueueSize int = 1024
PluginName = "discoverEventLoki"
defaultBatchSize = 512
defaultQueueSize = 1024
)

func init() {
Expand Down Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion plugin/discoverevent/loki/event_loki_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 4 additions & 1 deletion plugin/discoverevent/loki/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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 != "" {
Expand Down
4 changes: 1 addition & 3 deletions plugin/discoverstatis.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ import (
"github.com/polarismesh/polaris/common/log"
)

var (
discoverStatisOnce = &sync.Once{}
)
var discoverStatisOnce sync.Once

// DiscoverStatis 服务发现统计插件接口
type DiscoverStatis interface {
Expand Down
6 changes: 2 additions & 4 deletions plugin/history.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,8 @@ import (
"github.com/polarismesh/polaris/common/model"
)

var (
// 插件初始化原子变量
historyOnce = &sync.Once{}
)
// 插件初始化原子变量
var historyOnce sync.Once

// History 历史记录插件
type History interface {
Expand Down
8 changes: 4 additions & 4 deletions plugin/history/loki/history_loki.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion plugin/history/loki/history_loki_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion plugin/history/loki/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 1 addition & 3 deletions plugin/password.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ import (
"github.com/polarismesh/polaris/common/log"
)

var (
passwordOnce = &sync.Once{}
)
var passwordOnce sync.Once

// ParsePassword 密码插件
type ParsePassword interface {
Expand Down
2 changes: 1 addition & 1 deletion plugin/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import (
var (
pluginSet = make(map[string]Plugin)
config = &Config{}
once = &sync.Once{}
once sync.Once
)

// RegisterPlugin 注册插件
Expand Down
4 changes: 1 addition & 3 deletions plugin/ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
10 changes: 2 additions & 8 deletions plugin/ratelimit/lrurate/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}

Expand All @@ -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()
}

Expand Down
2 changes: 1 addition & 1 deletion plugin/ratelimit/lrurate/lrurate.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 90ad169

Please sign in to comment.