mirror of
https://github.com/go-kratos/kratos.git
synced 2026-05-22 10:15:24 +02:00
ci: add golangci-lint (#675)
This commit is contained in:
+15
-19
@@ -19,13 +19,18 @@ jobs:
|
||||
- ubuntu-latest
|
||||
|
||||
steps:
|
||||
|
||||
|
||||
- name: Set up Go ${{ matrix.go_version }}
|
||||
uses: actions/setup-go@v1
|
||||
with:
|
||||
go-version: ${{ matrix.go_version }}
|
||||
id: go
|
||||
|
||||
- name: Set up Env
|
||||
run: |
|
||||
echo "GOPATH=$(go env GOPATH)" >> $GITHUB_ENV
|
||||
echo "$(go env GOPATH)/bin" >> $GITHUB_PATH
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v2
|
||||
|
||||
@@ -51,14 +56,19 @@ jobs:
|
||||
- name: Build
|
||||
run: go build ./...
|
||||
|
||||
- name: Golangci
|
||||
run: |
|
||||
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.33.0
|
||||
golangci-lint run --out-format=github-actions
|
||||
|
||||
- name: Test
|
||||
run: go test ./... -coverprofile=coverage.txt -covermode=atomic
|
||||
|
||||
|
||||
- name: Coverage
|
||||
run: bash <(curl -s https://codecov.io/bash)
|
||||
|
||||
scaffold:
|
||||
|
||||
|
||||
name: Scaffold Test on ${{ matrix.os }} - Go${{ matrix.go_version }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
@@ -67,7 +77,7 @@ jobs:
|
||||
- 1.13
|
||||
os:
|
||||
- ubuntu-latest
|
||||
|
||||
|
||||
steps:
|
||||
|
||||
- name: Set up Go ${{ matrix.go_version }}
|
||||
@@ -76,25 +86,11 @@ jobs:
|
||||
go-version: ${{ matrix.go_version }}
|
||||
id: go
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Cache dependencies
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
# Cache
|
||||
path: ~/go/pkg/mod
|
||||
# Cache key
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
# An ordered list of keys to use for restoring the cache if no cache hit occurred for key
|
||||
restore-keys: |
|
||||
${{ runner.os }}-go-
|
||||
|
||||
- name: Set up Env
|
||||
run: |
|
||||
echo "GOPATH=$(go env GOPATH)" >> $GITHUB_ENV
|
||||
echo "$(go env GOPATH)/bin" >> $GITHUB_PATH
|
||||
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v2
|
||||
|
||||
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
# [index] https://github.com/golangci/golangci-lint
|
||||
# [example] https://github.com/golangci/golangci-lint/blob/master/.golangci.example.yml
|
||||
|
||||
run:
|
||||
tests: true #是否包含测试文件
|
||||
issues-exit-code: 0
|
||||
|
||||
linters-settings:
|
||||
# govet:
|
||||
# check-shadowing: true #启用了对同名变量名在函数中被隐藏的警告
|
||||
gofmt:
|
||||
simplify: true
|
||||
goimports:
|
||||
local-prefixes: "github.com/go-kratos/kratos" # 格式化代码时,本地代码单独块
|
||||
gocritic:
|
||||
enabled-tags:
|
||||
- diagnostic
|
||||
# - style
|
||||
# - performance
|
||||
disabled-checks:
|
||||
#- wrapperFunc
|
||||
#- dupImport # https://github.com/go-critic/go-critic/issues/845
|
||||
- commentedOutCode
|
||||
- ifElseChain
|
||||
- elseif
|
||||
settings: # settings passed to gocritic
|
||||
captLocal: # must be valid enabled check name
|
||||
paramsOnly: true
|
||||
# rangeValCopy:
|
||||
# sizeThreshold: 32
|
||||
lll:
|
||||
line-length: 500
|
||||
funlen:
|
||||
lines: 500
|
||||
statements: 500
|
||||
gocyclo:
|
||||
min-complexity: 100
|
||||
|
||||
linters:
|
||||
disable-all: true
|
||||
enable:
|
||||
# https://golangci-lint.run/usage/configuration/
|
||||
- bodyclose # http.resp.body 内存泄露检查
|
||||
- deadcode # 无用的变量声明检查
|
||||
- depguard # 自定义依赖包白、黑名单 控制导包
|
||||
- dogsled # 空白标识符的赋值检查 默认为2
|
||||
#- dupl # 重复代码检查
|
||||
- errcheck # 未判断的error返回值检查
|
||||
- funlen # 接口最大行数检查
|
||||
#- gochecknoinits # 包中定义init()函数检查
|
||||
#- goconst # 常量字符串检查
|
||||
- gocritic #
|
||||
- gocyclo # 代码复杂度检查
|
||||
- gofmt # 优化代码
|
||||
- goimports # 自动增加和删除包
|
||||
- golint # 代码风格检查
|
||||
#- gomnd # 参数、赋值、用例、条件、操作和返回语句检查
|
||||
- goprintffuncname #
|
||||
- gosec # 源代码安全检查
|
||||
- gosimple # 可以优化的代码检查 注:该工具已整合到staticcheck中
|
||||
- govet # 代码正确性检查
|
||||
- ineffassign # 无效赋值检查
|
||||
- interfacer # 建议接口的使用方式
|
||||
- lll # 行最大字符
|
||||
- misspell # 拼写错误检查
|
||||
- nakedret # 大于指定函数长度的函数的无约束返回值检查
|
||||
- nolintlint #
|
||||
- rowserrcheck # sql.Rows.Err检查
|
||||
- scopelint # 循环变量引用检查,排除test文件
|
||||
- staticcheck # 静态检查
|
||||
- structcheck # 结构体字段的约束条件检查
|
||||
- stylecheck # 代码风格检查
|
||||
- typecheck # 类型检查
|
||||
- unconvert # 类型转换检查
|
||||
- unparam # 未使用参数检查
|
||||
#- unused # 未使用变量、函数检查
|
||||
- varcheck # 报告exported变量和常量
|
||||
- whitespace # 空行检查
|
||||
|
||||
severity:
|
||||
# Default value is empty string.
|
||||
# Set the default severity for issues. If severity rules are defined and the issues
|
||||
# do not match or no severity is provided to the rule this will be the default
|
||||
# severity applied. Severities should match the supported severity names of the
|
||||
# selected out format.
|
||||
# - Code climate: https://docs.codeclimate.com/docs/issues#issue-severity
|
||||
# - Checkstyle: https://checkstyle.sourceforge.io/property_types.html#severity
|
||||
# - Github: https://help.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-error-message
|
||||
default-severity: error
|
||||
# The default value is false.
|
||||
# If set to true severity-rules regular expressions become case sensitive.
|
||||
case-sensitive: false
|
||||
# Default value is empty list.
|
||||
# When a list of severity rules are provided, severity information will be added to lint
|
||||
# issues. Severity rules have the same filtering capability as exclude rules except you
|
||||
# are allowed to specify one matcher per severity rule.
|
||||
# Only affects out formats that support setting severity information.
|
||||
rules:
|
||||
- linters:
|
||||
- dupl
|
||||
- nakedret
|
||||
- lll
|
||||
- misspell
|
||||
- goprintffuncname
|
||||
- stylecheck
|
||||
- deadcode
|
||||
- whitespace
|
||||
- unparam
|
||||
- golint
|
||||
- gosec
|
||||
- staticcheck
|
||||
- structcheck
|
||||
- gocritic
|
||||
- errcheck
|
||||
- rowserrcheck
|
||||
- unconvert
|
||||
- gosimple
|
||||
- rowserrcheck
|
||||
- ineffassign
|
||||
severity: warning
|
||||
|
||||
issues:
|
||||
# Excluding configuration per-path, per-linter, per-text and per-source
|
||||
exclude-rules:
|
||||
- path: _test\.go
|
||||
linters:
|
||||
- gomnd
|
||||
- gocyclo
|
||||
- errcheck
|
||||
- dupl
|
||||
- gosec
|
||||
- scopelint
|
||||
- interfacer
|
||||
- govet
|
||||
# https://github.com/go-critic/go-critic/issues/926
|
||||
- linters:
|
||||
- gocritic
|
||||
text: "unnecessaryDefer:"
|
||||
-2
@@ -167,10 +167,8 @@ func TestASCIIConnGetMulti(t *testing.T) {
|
||||
reply = r["get_multi_2"]
|
||||
compareItem(t, reply, test.a[1])
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestASCIIConnSet(t *testing.T) {
|
||||
|
||||
Vendored
+1
-1
@@ -84,7 +84,7 @@ func Dial(network, address string, options ...DialOption) (Conn, error) {
|
||||
return nil, pkgerr.WithStack(err)
|
||||
}
|
||||
pconn, err := newASCIIConn(netConn, do.readTimeout, do.writeTimeout)
|
||||
return &conn{pconn: pconn, ed: newEncodeDecoder()}, nil
|
||||
return &conn{pconn: pconn, ed: newEncodeDecoder()}, err
|
||||
}
|
||||
|
||||
type conn struct {
|
||||
|
||||
Vendored
+2
-2
@@ -5,8 +5,9 @@ import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
test "github.com/go-kratos/kratos/pkg/cache/memcache/test"
|
||||
"github.com/gogo/protobuf/proto"
|
||||
|
||||
test "github.com/go-kratos/kratos/pkg/cache/memcache/test"
|
||||
)
|
||||
|
||||
func TestConnRaw(t *testing.T) {
|
||||
@@ -120,7 +121,6 @@ func TestConnSerialization(t *testing.T) {
|
||||
t.Fatalf("compare failed error, %v %v", tc.a.Object.(*TestObj), no)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
Vendored
-2
@@ -404,7 +404,6 @@ func TestNewPool(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestPool_Get(t *testing.T) {
|
||||
|
||||
type args struct {
|
||||
ctx context.Context
|
||||
}
|
||||
@@ -474,7 +473,6 @@ func TestPool_Get(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestPool_Close(t *testing.T) {
|
||||
|
||||
type args struct {
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
Vendored
+3
-1
@@ -19,7 +19,9 @@ func (m MockErr) Err() error { return m.Error }
|
||||
func (m MockErr) Close() error { return m.Error }
|
||||
|
||||
// Do .
|
||||
func (m MockErr) Do(commandName string, args ...interface{}) (interface{}, error) { return nil, m.Error }
|
||||
func (m MockErr) Do(commandName string, args ...interface{}) (interface{}, error) {
|
||||
return nil, m.Error
|
||||
}
|
||||
|
||||
// Send .
|
||||
func (m MockErr) Send(commandName string, args ...interface{}) error { return m.Error }
|
||||
|
||||
Vendored
+1
-2
@@ -51,7 +51,6 @@ type cmd struct {
|
||||
|
||||
func (p *pipeliner) Send(commandName string, args ...interface{}) {
|
||||
p.cmds = append(p.cmds, &cmd{commandName: commandName, args: args})
|
||||
return
|
||||
}
|
||||
|
||||
func (p *pipeliner) Exec(ctx context.Context) (rs *Replies, err error) {
|
||||
@@ -64,7 +63,7 @@ func (p *pipeliner) Exec(ctx context.Context) (rs *Replies, err error) {
|
||||
for len(p.cmds) > 0 {
|
||||
cmd := p.cmds[0]
|
||||
p.cmds = p.cmds[1:]
|
||||
if err := c.Send(cmd.commandName, cmd.args...); err != nil {
|
||||
if err = c.Send(cmd.commandName, cmd.args...); err != nil {
|
||||
p.cmds = p.cmds[:0]
|
||||
return nil, err
|
||||
}
|
||||
|
||||
Vendored
-1
@@ -128,7 +128,6 @@ func TestPoolReuse(t *testing.T) {
|
||||
c2.Do("PING")
|
||||
c1.Close()
|
||||
c2.Close()
|
||||
|
||||
}
|
||||
|
||||
d.check("before close", p, 2, 2)
|
||||
|
||||
Vendored
-1
@@ -219,7 +219,6 @@ func TestRedis_Do(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRedis_Conn(t *testing.T) {
|
||||
|
||||
type args struct {
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
Vendored
-1
@@ -326,7 +326,6 @@ var (
|
||||
)
|
||||
|
||||
func structSpecForType(t reflect.Type) *structSpec {
|
||||
|
||||
structSpecMutex.RLock()
|
||||
ss, found := structSpecCache[t]
|
||||
structSpecMutex.RUnlock()
|
||||
|
||||
Vendored
-3
@@ -171,7 +171,6 @@ var scanStructTests = []struct {
|
||||
|
||||
func TestScanStruct(t *testing.T) {
|
||||
for _, tt := range scanStructTests {
|
||||
|
||||
var reply []interface{}
|
||||
for _, v := range tt.reply {
|
||||
reply = append(reply, []byte(v))
|
||||
@@ -280,7 +279,6 @@ var scanSliceTests = []struct {
|
||||
|
||||
func TestScanSlice(t *testing.T) {
|
||||
for _, tt := range scanSliceTests {
|
||||
|
||||
typ := reflect.ValueOf(tt.dest).Type()
|
||||
dest := reflect.New(typ)
|
||||
|
||||
@@ -417,7 +415,6 @@ func ExampleArgs() {
|
||||
}
|
||||
|
||||
for _, id := range []string{"id1", "id2"} {
|
||||
|
||||
v, err := Values(c.Do("HGETALL", id))
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
|
||||
Vendored
-1
@@ -99,5 +99,4 @@ func TestScript(t *testing.T) {
|
||||
if !reflect.DeepEqual(v, reply) {
|
||||
t.Errorf("s.Send(c, ..); c.Receive() = %v, want %v", v, reply)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Vendored
+5
-4
@@ -6,11 +6,12 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-kratos/kratos/pkg/net/trace"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/go-kratos/kratos/pkg/net/trace"
|
||||
)
|
||||
|
||||
const testTraceSlowLogThreshold = time.Duration(250 * time.Millisecond)
|
||||
const testTraceSlowLogThreshold = 250 * time.Millisecond
|
||||
|
||||
type mockTrace struct {
|
||||
tags []trace.Tag
|
||||
@@ -181,7 +182,7 @@ func BenchmarkTraceConn(b *testing.B) {
|
||||
t := &traceConn{
|
||||
Conn: c,
|
||||
connTags: []trace.Tag{trace.TagString(trace.TagPeerAddress, "abc")},
|
||||
slowLogThreshold: time.Duration(1 * time.Second),
|
||||
slowLogThreshold: 1 * time.Second,
|
||||
}
|
||||
c2 := t.WithContext(context.TODO())
|
||||
if _, err := c2.Do("PING"); err != nil {
|
||||
@@ -199,7 +200,7 @@ func TestTraceConnPending(t *testing.T) {
|
||||
tc := &traceConn{
|
||||
Conn: c,
|
||||
connTags: []trace.Tag{trace.TagString(trace.TagPeerAddress, "abc")},
|
||||
slowLogThreshold: time.Duration(1 * time.Second),
|
||||
slowLogThreshold: 1 * time.Second,
|
||||
}
|
||||
err = tc.Send("SET", "a", "x")
|
||||
if err != nil {
|
||||
|
||||
Vendored
+4
-4
@@ -28,9 +28,9 @@ const (
|
||||
|
||||
// env configuration.
|
||||
var (
|
||||
// Region avaliable region where app at.
|
||||
// Region available region where app at.
|
||||
Region string
|
||||
// Zone avaliable zone where app at.
|
||||
// Zone available zone where app at.
|
||||
Zone string
|
||||
// Hostname machine hostname.
|
||||
Hostname string
|
||||
@@ -59,8 +59,8 @@ func init() {
|
||||
|
||||
func addFlag(fs *flag.FlagSet) {
|
||||
// env
|
||||
fs.StringVar(&Region, "region", defaultString("REGION", _region), "avaliable region. or use REGION env variable, value: sh etc.")
|
||||
fs.StringVar(&Zone, "zone", defaultString("ZONE", _zone), "avaliable zone. or use ZONE env variable, value: sh001/sh002 etc.")
|
||||
fs.StringVar(&Region, "region", defaultString("REGION", _region), "available region. or use REGION env variable, value: sh etc.")
|
||||
fs.StringVar(&Zone, "zone", defaultString("ZONE", _zone), "available zone. or use ZONE env variable, value: sh001/sh002 etc.")
|
||||
fs.StringVar(&AppID, "appid", os.Getenv("APP_ID"), "appid is global unique application id, register by service tree. or use APP_ID env variable.")
|
||||
fs.StringVar(&DeployEnv, "deploy.env", defaultString("DEPLOY_ENV", _deployEnv), "deploy env. or use DEPLOY_ENV env variable, value: dev/fat1/uat/pre/prod etc.")
|
||||
fs.StringVar(&Color, "deploy.color", os.Getenv("DEPLOY_COLOR"), "deploy.color is the identification of different experimental group.")
|
||||
|
||||
@@ -65,8 +65,8 @@ func (s *mockServer) ConfigHandler(rw http.ResponseWriter, req *http.Request) {
|
||||
var namespace, releaseKey = strings.Split(strs[4], "?")[0], req.FormValue("releaseKey")
|
||||
config := s.Get(namespace)
|
||||
|
||||
var result = result{NamespaceName: namespace, Configurations: config, ReleaseKey: releaseKey}
|
||||
bts, err := json.Marshal(&result)
|
||||
ret := result{NamespaceName: namespace, Configurations: config, ReleaseKey: releaseKey}
|
||||
bts, err := json.Marshal(&ret)
|
||||
if err != nil {
|
||||
rw.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
|
||||
@@ -87,7 +87,7 @@ func loadValue(fpath string) (*Value, error) {
|
||||
// conf = /data/conf/app/
|
||||
// conf = /data/conf/app/xxx.toml
|
||||
func NewFile(base string) (Client, error) {
|
||||
// paltform slash
|
||||
// platform slash
|
||||
base = filepath.FromSlash(base)
|
||||
|
||||
paths, err := readAllPaths(base)
|
||||
|
||||
@@ -16,7 +16,7 @@ type testUnmarshler struct {
|
||||
func TestValueUnmarshal(t *testing.T) {
|
||||
s := `
|
||||
int = 100
|
||||
text = "hello"
|
||||
text = "hello"
|
||||
`
|
||||
v := Value{val: s, raw: s}
|
||||
obj := new(testUnmarshler)
|
||||
@@ -36,7 +36,7 @@ func TestValue(t *testing.T) {
|
||||
"text",
|
||||
},
|
||||
{
|
||||
time.Duration(time.Second * 10),
|
||||
time.Second * 10,
|
||||
"10s",
|
||||
},
|
||||
{
|
||||
|
||||
@@ -18,7 +18,7 @@ func NewGroup(new func() interface{}) *Group {
|
||||
panic("container.group: can't assign a nil to the new function")
|
||||
}
|
||||
return &Group{
|
||||
new: new,
|
||||
new: new,
|
||||
objs: make(map[string]interface{}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ func TestGroupGet(t *testing.T) {
|
||||
v = g.Get("/x/internal/dummy/user")
|
||||
assert.Equal(t, 1, v.(int))
|
||||
assert.Equal(t, 2, count)
|
||||
|
||||
}
|
||||
|
||||
func TestGroupReset(t *testing.T) {
|
||||
@@ -36,7 +35,7 @@ func TestGroupReset(t *testing.T) {
|
||||
})
|
||||
|
||||
length := 0
|
||||
for _,_ = range g.objs {
|
||||
for range g.objs {
|
||||
length++
|
||||
}
|
||||
|
||||
@@ -52,16 +51,15 @@ func TestGroupClear(t *testing.T) {
|
||||
})
|
||||
g.Get("/x/internal/dummy/user")
|
||||
length := 0
|
||||
for _,_ = range g.objs {
|
||||
for range g.objs {
|
||||
length++
|
||||
}
|
||||
assert.Equal(t, 1, length)
|
||||
|
||||
g.Clear()
|
||||
length = 0
|
||||
for _,_ = range g.objs {
|
||||
for range g.objs {
|
||||
length++
|
||||
}
|
||||
assert.Equal(t, 0, length)
|
||||
|
||||
}
|
||||
|
||||
@@ -139,7 +139,7 @@ func TestListPoolExhausted(t *testing.T) {
|
||||
conn, err := pool.Get(context.TODO())
|
||||
assert.Nil(t, err)
|
||||
_, err = pool.Get(ctx)
|
||||
// config active == 1, so no avaliable conns make connection exhausted.
|
||||
// config active == 1, so no available conns make connection exhausted.
|
||||
assert.NotNil(t, err)
|
||||
pool.Put(context.TODO(), conn, false)
|
||||
_, err = pool.Get(ctx)
|
||||
|
||||
@@ -167,7 +167,7 @@ func TestSlicePoolExhausted(t *testing.T) {
|
||||
conn, err := pool.Get(context.TODO())
|
||||
assert.Nil(t, err)
|
||||
_, err = pool.Get(ctx)
|
||||
// config active == 1, so no avaliable conns make connection exhausted.
|
||||
// config active == 1, so no available conns make connection exhausted.
|
||||
assert.NotNil(t, err)
|
||||
pool.Put(context.TODO(), conn, false)
|
||||
_, err = pool.Get(ctx)
|
||||
|
||||
@@ -36,7 +36,6 @@ func TestCoDel200(t *testing.T) {
|
||||
testPush(q, qps, delay, drop, tm)
|
||||
fmt.Printf("qps %v process time %v drop %d timeout %d \n", int64(time.Second/qps), delay, *drop, *tm)
|
||||
time.Sleep(time.Second)
|
||||
|
||||
}
|
||||
|
||||
func TestCoDel100(t *testing.T) {
|
||||
@@ -46,7 +45,6 @@ func TestCoDel100(t *testing.T) {
|
||||
delay := time.Millisecond * 1000
|
||||
testPush(q, qps, delay, drop, tm)
|
||||
fmt.Printf("qps %v process time %v drop %d timeout %d \n", int64(time.Second/qps), delay, *drop, *tm)
|
||||
|
||||
}
|
||||
|
||||
func TestCoDel50(t *testing.T) {
|
||||
|
||||
@@ -285,7 +285,7 @@ func (c *Client) Ping(ctx context.Context) (err error) {
|
||||
if c.config.TestRowKey != "" {
|
||||
testRowKey = c.config.TestRowKey
|
||||
}
|
||||
values := map[string]map[string][]byte{"test": map[string][]byte{"test": []byte("test")}}
|
||||
values := map[string]map[string][]byte{"test": {"test": []byte("test")}}
|
||||
_, err = c.PutStr(ctx, "test", testRowKey, values)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ func MaxSize(n int64) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// ChanSize set internal chan size default 8192 use about 64k memory on x64 platfrom static,
|
||||
// ChanSize set internal chan size default 8192 use about 64k memory on x64 platform static,
|
||||
// because filewriter has internal object pool, change chan size bigger may cause filewriter use
|
||||
// a lot of memory, because sync.Pool can't set expire time memory won't free until program exit.
|
||||
func ChanSize(n int) Option {
|
||||
|
||||
@@ -92,7 +92,6 @@ func TestLogWithMirror(t *testing.T) {
|
||||
Infov(mdcontext, KV("key1", "val1"), KV("key2", ""), KV("log", "log content"), KV("msg", "msg content"))
|
||||
|
||||
Infov(context.Background(), KV("key1", "val1"), KV("key2", ""), KV("log", "log content"), KV("msg", "msg content"))
|
||||
|
||||
}
|
||||
|
||||
func TestOverwriteSouce(t *testing.T) {
|
||||
|
||||
+2
-2
@@ -62,7 +62,7 @@ type pattern struct {
|
||||
bufPool sync.Pool
|
||||
}
|
||||
|
||||
// Render implemet Formater
|
||||
// Render implements Formater
|
||||
func (p *pattern) Render(w io.Writer, d map[string]interface{}) error {
|
||||
builder := p.bufPool.Get().(*strings.Builder)
|
||||
defer func() {
|
||||
@@ -77,7 +77,7 @@ func (p *pattern) Render(w io.Writer, d map[string]interface{}) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Render implemet Formater as string
|
||||
// Render implements Formater as string
|
||||
func (p *pattern) RenderString(d map[string]interface{}) string {
|
||||
builder := p.bufPool.Get().(*strings.Builder)
|
||||
defer func() {
|
||||
|
||||
@@ -12,11 +12,12 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/go-kratos/kratos/pkg/log"
|
||||
"github.com/go-kratos/kratos/pkg/naming"
|
||||
"go.etcd.io/etcd/clientv3"
|
||||
"go.etcd.io/etcd/mvcc/mvccpb"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/go-kratos/kratos/pkg/log"
|
||||
"github.com/go-kratos/kratos/pkg/naming"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -155,7 +156,6 @@ func (e *EtcdBuilder) Build(appid string, opts ...naming.BuildOpt) naming.Resolv
|
||||
// Scheme return etcd's scheme
|
||||
func (e *EtcdBuilder) Scheme() string {
|
||||
return "etcd"
|
||||
|
||||
}
|
||||
|
||||
// Register is register instance
|
||||
@@ -185,7 +185,6 @@ func (e *EtcdBuilder) Register(ctx context.Context, ins *naming.Instance) (cance
|
||||
})
|
||||
|
||||
go func() {
|
||||
|
||||
ticker := time.NewTicker(time.Duration(registerTTL/3) * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
@@ -270,7 +269,6 @@ func (a *appInfo) fetchstore(appID string) (err error) {
|
||||
return nil
|
||||
}
|
||||
func (a *appInfo) store(ins *naming.InstancesInfo) {
|
||||
|
||||
a.ins.Store(ins)
|
||||
a.e.mutex.RLock()
|
||||
for rs := range a.resolver {
|
||||
@@ -284,7 +282,7 @@ func (a *appInfo) store(ins *naming.InstancesInfo) {
|
||||
|
||||
func (a *appInfo) paserIns(resp *clientv3.GetResponse) (ins *naming.InstancesInfo, err error) {
|
||||
ins = &naming.InstancesInfo{
|
||||
Instances: make(map[string][]*naming.Instance, 0),
|
||||
Instances: make(map[string][]*naming.Instance),
|
||||
}
|
||||
for _, ev := range resp.Kvs {
|
||||
in := new(naming.Instance)
|
||||
|
||||
+3
-5
@@ -73,7 +73,7 @@ func Filter(schema string, clusters map[string]struct{}) BuildOpt {
|
||||
|
||||
func defulatSubset(inss []*Instance, size int) []*Instance {
|
||||
backends := inss
|
||||
if len(backends) <= int(size) {
|
||||
if len(backends) <= size {
|
||||
return backends
|
||||
}
|
||||
clientID := env.Hostname
|
||||
@@ -93,7 +93,7 @@ func defulatSubset(inss []*Instance, size int) []*Instance {
|
||||
backends[i], backends[j] = backends[j], backends[i]
|
||||
})
|
||||
start := (id % uint64(count)) * uint64(size)
|
||||
return backends[int(start) : int(start)+int(size)]
|
||||
return backends[int(start) : int(start)+size]
|
||||
}
|
||||
|
||||
// Subset Subset option.
|
||||
@@ -159,9 +159,7 @@ func ScheduleNode(clientZone string) BuildOpt {
|
||||
}
|
||||
}
|
||||
for _, zone := range zones {
|
||||
for _, ins := range zone.inss {
|
||||
instances = append(instances, ins)
|
||||
}
|
||||
instances = append(instances, zone.inss...)
|
||||
}
|
||||
//如果没有拿到节点,则选择直接获取
|
||||
if len(instances) == 0 {
|
||||
|
||||
+35
-35
@@ -30,36 +30,36 @@ func Test_Subset(t *testing.T) {
|
||||
|
||||
func Test_FilterClusters(t *testing.T) {
|
||||
inss := map[string][]*Instance{
|
||||
"sh001": []*Instance{&Instance{
|
||||
"sh001": {{
|
||||
Addrs: []string{"grpc://127.0.0.1:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c1"},
|
||||
}, &Instance{
|
||||
}, {
|
||||
Addrs: []string{"http://127.0.0.2:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c1"},
|
||||
}, &Instance{
|
||||
}, {
|
||||
Addrs: []string{"grpc://127.0.0.3:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c2"},
|
||||
}},
|
||||
"sh002": []*Instance{&Instance{
|
||||
"sh002": {{
|
||||
Addrs: []string{"grpc://127.0.0.1:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c3"},
|
||||
}, &Instance{
|
||||
}, {
|
||||
Addrs: []string{"zk://127.0.0.2:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c3"},
|
||||
}},
|
||||
}
|
||||
res := map[string][]*Instance{
|
||||
"sh001": []*Instance{&Instance{
|
||||
"sh001": {{
|
||||
Addrs: []string{"grpc://127.0.0.1:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c1"},
|
||||
}},
|
||||
"sh002": []*Instance{&Instance{
|
||||
"sh002": {{
|
||||
Addrs: []string{"grpc://127.0.0.1:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c3"},
|
||||
}},
|
||||
}
|
||||
var opt BuildOptions
|
||||
f := Filter("grpc", map[string]struct{}{"c1": struct{}{}, "c3": struct{}{}})
|
||||
f := Filter("grpc", map[string]struct{}{"c1": {}, "c3": {}})
|
||||
f.Apply(&opt)
|
||||
filtered := opt.Filter(inss)
|
||||
equal := reflect.DeepEqual(filtered, res)
|
||||
@@ -70,33 +70,33 @@ func Test_FilterClusters(t *testing.T) {
|
||||
|
||||
func Test_FilterInvalidAddr(t *testing.T) {
|
||||
inss := map[string][]*Instance{
|
||||
"sh001": []*Instance{&Instance{
|
||||
"sh001": {{
|
||||
Addrs: []string{"grpc://127.0.0.1:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c1"},
|
||||
}, &Instance{
|
||||
}, {
|
||||
Addrs: []string{"http://127.0.0.2:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c1"},
|
||||
}, &Instance{
|
||||
}, {
|
||||
Addrs: []string{"grpc://127.0.0.3:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c2"},
|
||||
}},
|
||||
"sh002": []*Instance{&Instance{
|
||||
"sh002": {{
|
||||
Addrs: []string{"grpc://127.0.0.1:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c3"},
|
||||
}, &Instance{
|
||||
}, {
|
||||
Addrs: []string{"zk://127.0.0.2:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c3"},
|
||||
}},
|
||||
}
|
||||
res := map[string][]*Instance{
|
||||
"sh001": []*Instance{&Instance{
|
||||
"sh001": {{
|
||||
Addrs: []string{"grpc://127.0.0.1:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c1"},
|
||||
}, &Instance{
|
||||
}, {
|
||||
Addrs: []string{"grpc://127.0.0.3:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c2"},
|
||||
}},
|
||||
"sh002": []*Instance{&Instance{
|
||||
"sh002": {{
|
||||
Addrs: []string{"grpc://127.0.0.1:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c3"},
|
||||
}},
|
||||
@@ -114,33 +114,33 @@ func Test_FilterInvalidAddr(t *testing.T) {
|
||||
func Test_Schedule(t *testing.T) {
|
||||
app := &InstancesInfo{
|
||||
Instances: map[string][]*Instance{
|
||||
"sh001": []*Instance{&Instance{
|
||||
"sh001": {{
|
||||
Zone: "sh001",
|
||||
Addrs: []string{"grpc://127.0.0.1:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c1"},
|
||||
}, &Instance{
|
||||
}, {
|
||||
Zone: "sh001",
|
||||
Addrs: []string{"grpc://127.0.0.2:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c1"},
|
||||
}, &Instance{
|
||||
}, {
|
||||
Zone: "sh001",
|
||||
Addrs: []string{"grpc://127.0.0.3:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c2"},
|
||||
}},
|
||||
"sh002": []*Instance{&Instance{
|
||||
"sh002": {{
|
||||
Zone: "sh002",
|
||||
Addrs: []string{"grpc://127.0.0.1:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c3"},
|
||||
}, &Instance{
|
||||
}, {
|
||||
Zone: "sh002",
|
||||
Addrs: []string{"grpc://127.0.0.2:9000"},
|
||||
Metadata: map[string]string{MetaCluster: "c3"},
|
||||
}},
|
||||
},
|
||||
Scheduler: &Scheduler{map[string]*ZoneStrategy{"sh001": &ZoneStrategy{
|
||||
Scheduler: &Scheduler{map[string]*ZoneStrategy{"sh001": {
|
||||
Zones: map[string]*Strategy{
|
||||
"sh001": &Strategy{10},
|
||||
"sh002": &Strategy{20},
|
||||
"sh001": {10},
|
||||
"sh002": {20},
|
||||
},
|
||||
}}},
|
||||
}
|
||||
@@ -156,10 +156,10 @@ func Test_Schedule(t *testing.T) {
|
||||
func Test_Schedule2(t *testing.T) {
|
||||
app := &InstancesInfo{
|
||||
Instances: map[string][]*Instance{},
|
||||
Scheduler: &Scheduler{map[string]*ZoneStrategy{"sh001": &ZoneStrategy{
|
||||
Scheduler: &Scheduler{map[string]*ZoneStrategy{"sh001": {
|
||||
Zones: map[string]*Strategy{
|
||||
"sh001": &Strategy{10},
|
||||
"sh002": &Strategy{20},
|
||||
"sh001": {10},
|
||||
"sh002": {20},
|
||||
},
|
||||
}}},
|
||||
}
|
||||
@@ -191,10 +191,10 @@ func Test_Schedule2(t *testing.T) {
|
||||
func Test_Schedule3(t *testing.T) {
|
||||
app := &InstancesInfo{
|
||||
Instances: map[string][]*Instance{},
|
||||
Scheduler: &Scheduler{map[string]*ZoneStrategy{"sh001": &ZoneStrategy{
|
||||
Scheduler: &Scheduler{map[string]*ZoneStrategy{"sh001": {
|
||||
Zones: map[string]*Strategy{
|
||||
"sh001": &Strategy{1},
|
||||
"sh002": &Strategy{30},
|
||||
"sh001": {1},
|
||||
"sh002": {30},
|
||||
},
|
||||
}}},
|
||||
}
|
||||
@@ -226,10 +226,10 @@ func Test_Schedule3(t *testing.T) {
|
||||
func Test_Schedule4(t *testing.T) {
|
||||
app := &InstancesInfo{
|
||||
Instances: map[string][]*Instance{},
|
||||
Scheduler: &Scheduler{map[string]*ZoneStrategy{"sh001": &ZoneStrategy{
|
||||
Scheduler: &Scheduler{map[string]*ZoneStrategy{"sh001": {
|
||||
Zones: map[string]*Strategy{
|
||||
"sh001": &Strategy{1},
|
||||
"sh002": &Strategy{30},
|
||||
"sh001": {1},
|
||||
"sh002": {30},
|
||||
},
|
||||
}}},
|
||||
}
|
||||
@@ -254,9 +254,9 @@ func Test_Schedule4(t *testing.T) {
|
||||
func Test_Schedule5(t *testing.T) {
|
||||
app := &InstancesInfo{
|
||||
Instances: map[string][]*Instance{},
|
||||
Scheduler: &Scheduler{map[string]*ZoneStrategy{"sh001": &ZoneStrategy{
|
||||
Scheduler: &Scheduler{map[string]*ZoneStrategy{"sh001": {
|
||||
Zones: map[string]*Strategy{
|
||||
"sh002": &Strategy{30},
|
||||
"sh002": {30},
|
||||
},
|
||||
}}},
|
||||
}
|
||||
|
||||
@@ -12,10 +12,11 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/go-zookeeper/zk"
|
||||
|
||||
"github.com/go-kratos/kratos/pkg/log"
|
||||
"github.com/go-kratos/kratos/pkg/naming"
|
||||
xtime "github.com/go-kratos/kratos/pkg/time"
|
||||
"github.com/go-zookeeper/zk"
|
||||
)
|
||||
|
||||
// Config is zookeeper config.
|
||||
@@ -80,7 +81,7 @@ func New(c *Config) (zkb *Zookeeper, err error) {
|
||||
c.Timeout = xtime.Duration(time.Second)
|
||||
}
|
||||
if len(c.Endpoints) == 0 {
|
||||
errInfo := fmt.Sprintf("zookeeper New failed, endpoints is null")
|
||||
errInfo := "zookeeper New failed, endpoints is null"
|
||||
log.Error(errInfo)
|
||||
return nil, errors.New(errInfo)
|
||||
}
|
||||
@@ -90,7 +91,7 @@ func New(c *Config) (zkb *Zookeeper, err error) {
|
||||
log.Error(fmt.Sprintf("zk Connect err:(%v)", err))
|
||||
return
|
||||
}
|
||||
log.Info(fmt.Sprintf("zk Connect ok!"))
|
||||
log.Info("zk Connect ok!")
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
zkb = &Zookeeper{
|
||||
@@ -255,7 +256,7 @@ func (z *Zookeeper) register(ctx context.Context, ins *naming.Instance) (err err
|
||||
if err = z.registerPeerServer(nodePath, ins); err != nil {
|
||||
log.Warn(fmt.Sprintf("registerServer, fail to RegisterPeerServer node:%s error:(%v)", addr, err))
|
||||
} else {
|
||||
log.Info(fmt.Sprintf("registerServer, succeed to RegistServer node."))
|
||||
log.Info("registerServer, succeed to RegistServer node.")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -336,7 +337,7 @@ func (a *appInfo) fetchstore(appID string) (err error) {
|
||||
}
|
||||
log.Info(fmt.Sprintf("fetchstore, ok to get Children of node:(%v), childs:(%v)", prefix, childs))
|
||||
ins := &naming.InstancesInfo{
|
||||
Instances: make(map[string][]*naming.Instance, 0),
|
||||
Instances: make(map[string][]*naming.Instance),
|
||||
}
|
||||
for _, child := range childs {
|
||||
nodePath := prefix + "/" + child
|
||||
@@ -350,7 +351,6 @@ func (a *appInfo) fetchstore(appID string) (err error) {
|
||||
return err
|
||||
}
|
||||
ins.Instances[in.Zone] = append(ins.Instances[in.Zone], in)
|
||||
|
||||
}
|
||||
a.store(ins)
|
||||
return nil
|
||||
|
||||
@@ -61,7 +61,6 @@ func TestBindingDefault(t *testing.T) {
|
||||
|
||||
assert.Equal(t, Default("POST", MIMEMultipartPOSTForm), Form)
|
||||
assert.Equal(t, Default("PUT", MIMEMultipartPOSTForm), Form)
|
||||
|
||||
}
|
||||
|
||||
func TestStripContentType(t *testing.T) {
|
||||
|
||||
@@ -47,4 +47,4 @@ func kindOfData(data interface{}) reflect.Kind {
|
||||
func (v *defaultValidator) GetValidate() *validator.Validate {
|
||||
v.lazyinit()
|
||||
return v.validate
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Render http reponse render.
|
||||
// Render http response render.
|
||||
type Render interface {
|
||||
// Render render it to http response writer.
|
||||
Render(http.ResponseWriter) error
|
||||
|
||||
@@ -236,7 +236,6 @@ func (n *node) addRoute(path string, handlers []HandlerFunc) {
|
||||
}
|
||||
n.insertChild(numParams, path, fullPath, handlers)
|
||||
return
|
||||
|
||||
} else if i == len(path) { // Make node a (in-path) leaf
|
||||
if n.handlers != nil {
|
||||
panic("handlers are already registered for path '" + fullPath + "'")
|
||||
@@ -316,7 +315,6 @@ func (n *node) insertChild(numParams uint8, path string, fullPath string, handle
|
||||
n.children = []*node{child}
|
||||
n = child
|
||||
}
|
||||
|
||||
} else { // catchAll
|
||||
if end != max || numParams > 1 {
|
||||
panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'")
|
||||
@@ -514,7 +512,7 @@ func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPa
|
||||
ciPath = make([]byte, 0, len(path)+1) // preallocate enough memory
|
||||
|
||||
// Outer loop for walking the tree
|
||||
for len(path) >= len(n.path) && strings.ToLower(path[:len(n.path)]) == strings.ToLower(n.path) {
|
||||
for len(path) >= len(n.path) && strings.EqualFold(path[:len(n.path)], n.path) {
|
||||
path = path[len(n.path):]
|
||||
ciPath = append(ciPath, n.path...)
|
||||
|
||||
@@ -528,8 +526,8 @@ func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPa
|
||||
// must use recursive approach since both index and
|
||||
// ToLower(index) could exist. We must check both.
|
||||
if r == unicode.ToLower(index) {
|
||||
out, found := n.children[i].findCaseInsensitivePath(path, fixTrailingSlash)
|
||||
if found {
|
||||
out, _found := n.children[i].findCaseInsensitivePath(path, fixTrailingSlash)
|
||||
if _found {
|
||||
return append(ciPath, out...), true
|
||||
}
|
||||
}
|
||||
@@ -618,7 +616,7 @@ func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPa
|
||||
return ciPath, true
|
||||
}
|
||||
if len(path)+1 == len(n.path) && n.path[len(path)] == '/' &&
|
||||
strings.ToLower(path) == strings.ToLower(n.path[:len(path)]) &&
|
||||
strings.EqualFold(path, n.path[:len(path)]) &&
|
||||
n.handlers != nil {
|
||||
return append(ciPath, n.path...), true
|
||||
}
|
||||
|
||||
@@ -39,15 +39,15 @@ const (
|
||||
)
|
||||
|
||||
var outgoingKey = map[string]struct{}{
|
||||
Color: struct{}{},
|
||||
RemoteIP: struct{}{},
|
||||
RemotePort: struct{}{},
|
||||
Mirror: struct{}{},
|
||||
Criticality: struct{}{},
|
||||
Color: {},
|
||||
RemoteIP: {},
|
||||
RemotePort: {},
|
||||
Mirror: {},
|
||||
Criticality: {},
|
||||
}
|
||||
|
||||
var incomingKey = map[string]struct{}{
|
||||
Caller: struct{}{},
|
||||
Caller: {},
|
||||
}
|
||||
|
||||
// IsOutgoingKey represent this key should propagate by rpc.
|
||||
|
||||
@@ -84,7 +84,6 @@ func TestBool(t *testing.T) {
|
||||
|
||||
mdcontext = NewContext(context.Background(), MD{Mirror: "0"})
|
||||
assert.Equal(t, false, Bool(mdcontext, Mirror))
|
||||
|
||||
}
|
||||
func TestInt64(t *testing.T) {
|
||||
mdcontext := NewContext(context.Background(), MD{Mid: int64(1)})
|
||||
|
||||
@@ -191,7 +191,6 @@ func TestBalancerPick(t *testing.T) {
|
||||
t.Fatalf("the (%d) subconn picked(%s),but expected(%s)", i, sc.addr.Addr, res[i])
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func Benchmark_Wrr(b *testing.B) {
|
||||
@@ -299,7 +298,6 @@ func (c *controller) updateStatics() {
|
||||
sc.prevUsage = usage
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (c *controller) control(extraLoad, extraDelay int64) {
|
||||
|
||||
@@ -8,11 +8,6 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/go-kratos/kratos/pkg/conf/env"
|
||||
"github.com/go-kratos/kratos/pkg/log"
|
||||
nmd "github.com/go-kratos/kratos/pkg/net/metadata"
|
||||
wmeta "github.com/go-kratos/kratos/pkg/net/rpc/warden/internal/metadata"
|
||||
"github.com/go-kratos/kratos/pkg/stat/metric"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/balancer"
|
||||
"google.golang.org/grpc/balancer/base"
|
||||
@@ -20,6 +15,12 @@ import (
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/resolver"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/go-kratos/kratos/pkg/conf/env"
|
||||
"github.com/go-kratos/kratos/pkg/log"
|
||||
nmd "github.com/go-kratos/kratos/pkg/net/metadata"
|
||||
wmeta "github.com/go-kratos/kratos/pkg/net/rpc/warden/internal/metadata"
|
||||
"github.com/go-kratos/kratos/pkg/stat/metric"
|
||||
)
|
||||
|
||||
var _ base.PickerBuilder = &wrrPickerBuilder{}
|
||||
@@ -94,13 +95,13 @@ func (c *subConn) latencySummary() (latency float64, count int64) {
|
||||
|
||||
// statistics is info for log
|
||||
type statistics struct {
|
||||
addr string
|
||||
ewt int64
|
||||
cs float64
|
||||
ss float64
|
||||
addr string
|
||||
ewt int64
|
||||
cs float64
|
||||
ss float64
|
||||
latency float64
|
||||
cpu float64
|
||||
req int64
|
||||
cpu float64
|
||||
req int64
|
||||
}
|
||||
|
||||
// Stats is grpc Interceptor for client to collect server stats
|
||||
@@ -298,5 +299,4 @@ func (p *wrrPicker) pick(ctx context.Context, opts balancer.PickInfo) (balancer.
|
||||
p.mu.Unlock()
|
||||
log.Info("warden wrr(%s): %+v", conn.addr.ServerName, stats)
|
||||
}, nil
|
||||
|
||||
}
|
||||
|
||||
@@ -179,7 +179,6 @@ func onBreaker(breaker breaker.Breaker, err *error) {
|
||||
if ecode.EqualError(ecode.ServerErr, *err) || ecode.EqualError(ecode.ServiceUnavailable, *err) || ecode.EqualError(ecode.Deadline, *err) || ecode.EqualError(ecode.LimitExceed, *err) {
|
||||
breaker.MarkFailed()
|
||||
return
|
||||
|
||||
}
|
||||
}
|
||||
breaker.MarkSuccess()
|
||||
|
||||
@@ -38,7 +38,6 @@ func (s *helloServer) StreamHello(ss pb.Greeter_StreamHelloServer) error {
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
func ExampleServer() {
|
||||
|
||||
@@ -113,7 +113,6 @@ func main() {
|
||||
}
|
||||
wg.Done()
|
||||
}(i)
|
||||
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
@@ -140,7 +139,6 @@ func main() {
|
||||
log.Printf("received requests_OK : %d\n", atomic.LoadUint64(&transOK))
|
||||
log.Printf("throughput (TPS) : %d\n", int64(c*m)*1000/totalT)
|
||||
log.Printf("mean: %v ms, median: %v ms, max: %v ms, min: %v ms, p99: %v ms, p999:%v ms\n", mean/1e6, median/1e6, max/1e6, min/1e6, tp99/1e6, tp999/1e6)
|
||||
|
||||
}
|
||||
|
||||
func prepareArgs() *proto.BenchmarkMessage {
|
||||
|
||||
@@ -50,7 +50,6 @@ func main() {
|
||||
}
|
||||
wg.Wait()
|
||||
fmt.Printf("per request cost %v\n", all/int64(request*concurrency))
|
||||
|
||||
}
|
||||
|
||||
func sayHello(in *pb.HelloRequest) {
|
||||
|
||||
@@ -46,5 +46,4 @@ func newServer() {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ func TestFromError(t *testing.T) {
|
||||
gst := FromError(err)
|
||||
|
||||
//assert.Equal(t, codes.InvalidArgument, gst.Code())
|
||||
// NOTE: set all grpc.status as Unkown when error is ecode.Codes for compatible
|
||||
// NOTE: set all grpc.status as Unknown when error is ecode.Codes for compatible
|
||||
assert.Equal(t, codes.Unknown, gst.Code())
|
||||
// NOTE: gst.Message == str(ecode.Code) for compatible php leagcy code
|
||||
assert.Equal(t, err.Message(), gst.Message())
|
||||
@@ -93,7 +93,7 @@ func TestFromError(t *testing.T) {
|
||||
gst := FromError(err)
|
||||
|
||||
//assert.Equal(t, codes.Unauthenticated, gst.Code())
|
||||
// NOTE: set all grpc.status as Unkown when error is ecode.Codes for compatible
|
||||
// NOTE: set all grpc.status as Unknown when error is ecode.Codes for compatible
|
||||
assert.Equal(t, codes.Unknown, gst.Code())
|
||||
assert.Len(t, gst.Details(), 1)
|
||||
details := gst.Details()
|
||||
|
||||
@@ -5,11 +5,12 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/go-kratos/kratos/pkg/log"
|
||||
limit "github.com/go-kratos/kratos/pkg/ratelimit"
|
||||
"github.com/go-kratos/kratos/pkg/ratelimit/bbr"
|
||||
"github.com/go-kratos/kratos/pkg/stat/metric"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
@@ -27,7 +27,7 @@ func (s *Server) recovery() grpc.UnaryServerInterceptor {
|
||||
}
|
||||
buf = buf[:rs]
|
||||
pl := fmt.Sprintf("grpc server panic: %v\n%v\n%s\n", req, rerr, buf)
|
||||
fmt.Fprintf(os.Stderr, pl)
|
||||
fmt.Fprint(os.Stderr, pl)
|
||||
log.Error(pl)
|
||||
err = status.Errorf(codes.Unknown, ecode.ServerErr.Error())
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ func (d *Direct) Watch() <-chan struct{} {
|
||||
func (d *Direct) Unwatch(id string) {
|
||||
}
|
||||
|
||||
//Fetch fetch isntances.
|
||||
//Fetch fetch instances.
|
||||
func (d *Direct) Fetch(ctx context.Context) (res *naming.InstancesInfo, found bool) {
|
||||
var ins []*naming.Instance
|
||||
addrs := strings.Split(d.id, ",")
|
||||
|
||||
@@ -71,7 +71,6 @@ func (b *Builder) Build(target resolver.Target, cc resolver.ClientConn, opts res
|
||||
if t, err := strconv.ParseInt(sub[0], 10, 64); err == nil {
|
||||
ss = t
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -299,7 +299,7 @@ func (s *Server) RunUnix(file string) error {
|
||||
}
|
||||
|
||||
// Start create a new goroutine run server with configured listen addr
|
||||
// will panic if any error happend
|
||||
// will panic if any error happened
|
||||
// return server itself
|
||||
func (s *Server) Start() (*Server, error) {
|
||||
_, err := s.startWithAddr()
|
||||
@@ -310,7 +310,7 @@ func (s *Server) Start() (*Server, error) {
|
||||
}
|
||||
|
||||
// StartWithAddr create a new goroutine run server with configured listen addr
|
||||
// will panic if any error happend
|
||||
// will panic if any error happened
|
||||
// return server itself and the actually listened address (if configured listen
|
||||
// port is zero, the os will allocate an unused port)
|
||||
func (s *Server) StartWithAddr() (*Server, net.Addr, error) {
|
||||
|
||||
@@ -336,7 +336,6 @@ func testLinkTimeout(t *testing.T) {
|
||||
if !ecode.EqualError(ecode.Deadline, err) {
|
||||
t.Fatalf("testLinkTimeout must return error RPCDeadline,err:%v", err)
|
||||
}
|
||||
|
||||
}
|
||||
func testClientConfig(t *testing.T) {
|
||||
_, err := runClient(context.Background(), &clientConfig2, t, "timeout_test2", 0)
|
||||
@@ -520,7 +519,7 @@ func BenchmarkServer(b *testing.B) {
|
||||
b.Fatalf("c.SayHello failed: %v,req: %v %v", err, "benchmark", 1)
|
||||
}
|
||||
if !resp.Success {
|
||||
b.Error("repsonse not success!")
|
||||
b.Error("response not success!")
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -2,6 +2,7 @@ package warden
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
|
||||
@@ -69,9 +69,9 @@ var emptyContext = spanContext{}
|
||||
// sample-rate: s-{base16(BigEndian(float32))}
|
||||
func (c spanContext) String() string {
|
||||
base := make([]string, 4)
|
||||
base[0] = strconv.FormatUint(uint64(c.TraceID), 16)
|
||||
base[1] = strconv.FormatUint(uint64(c.SpanID), 16)
|
||||
base[2] = strconv.FormatUint(uint64(c.ParentID), 16)
|
||||
base[0] = strconv.FormatUint(c.TraceID, 16)
|
||||
base[1] = strconv.FormatUint(c.SpanID, 16)
|
||||
base[2] = strconv.FormatUint(c.ParentID, 16)
|
||||
base[3] = strconv.FormatUint(uint64(c.Flags), 16)
|
||||
return strings.Join(base, ":")
|
||||
}
|
||||
|
||||
@@ -253,7 +253,7 @@ func buildTag(tag *Tag, maxTagValueLength int) *j.Tag {
|
||||
jTag.VLong = &vLong
|
||||
jTag.VType = j.TagType_LONG
|
||||
case int64:
|
||||
vLong := int64(value)
|
||||
vLong := value
|
||||
jTag.VLong = &vLong
|
||||
jTag.VType = j.TagType_LONG
|
||||
case uint64:
|
||||
@@ -265,7 +265,7 @@ func buildTag(tag *Tag, maxTagValueLength int) *j.Tag {
|
||||
jTag.VDouble = &vDouble
|
||||
jTag.VType = j.TagType_DOUBLE
|
||||
case float64:
|
||||
vDouble := float64(value)
|
||||
vDouble := value
|
||||
jTag.VDouble = &vDouble
|
||||
jTag.VType = j.TagType_DOUBLE
|
||||
case bool:
|
||||
|
||||
@@ -2,13 +2,15 @@ package zipkin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
protogen "github.com/go-kratos/kratos/pkg/net/trace/proto"
|
||||
"time"
|
||||
|
||||
"github.com/go-kratos/kratos/pkg/net/trace"
|
||||
protogen "github.com/go-kratos/kratos/pkg/net/trace/proto"
|
||||
|
||||
"github.com/openzipkin/zipkin-go/model"
|
||||
"github.com/openzipkin/zipkin-go/reporter"
|
||||
"github.com/openzipkin/zipkin-go/reporter/http"
|
||||
|
||||
"github.com/go-kratos/kratos/pkg/net/trace"
|
||||
)
|
||||
|
||||
type report struct {
|
||||
|
||||
@@ -9,9 +9,10 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/go-kratos/kratos/pkg/ratelimit"
|
||||
"github.com/go-kratos/kratos/pkg/stat/metric"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func confForTest() *Config {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
package metric
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestWindowResetWindow(t *testing.T) {
|
||||
|
||||
@@ -10,12 +10,8 @@ func fakeRunTask(ctx context.Context) error {
|
||||
|
||||
func ExampleGroup_group() {
|
||||
g := Group{}
|
||||
g.Go(func(context.Context) error {
|
||||
return fakeRunTask(context.Background())
|
||||
})
|
||||
g.Go(func(context.Context) error {
|
||||
return fakeRunTask(context.Background())
|
||||
})
|
||||
g.Go(fakeRunTask)
|
||||
g.Go(fakeRunTask)
|
||||
if err := g.Wait(); err != nil {
|
||||
// handle err
|
||||
}
|
||||
@@ -23,12 +19,8 @@ func ExampleGroup_group() {
|
||||
|
||||
func ExampleGroup_ctx() {
|
||||
g := WithContext(context.Background())
|
||||
g.Go(func(ctx context.Context) error {
|
||||
return fakeRunTask(ctx)
|
||||
})
|
||||
g.Go(func(ctx context.Context) error {
|
||||
return fakeRunTask(ctx)
|
||||
})
|
||||
g.Go(fakeRunTask)
|
||||
g.Go(fakeRunTask)
|
||||
if err := g.Wait(); err != nil {
|
||||
// handle err
|
||||
}
|
||||
@@ -36,12 +28,8 @@ func ExampleGroup_ctx() {
|
||||
|
||||
func ExampleGroup_cancel() {
|
||||
g := WithCancel(context.Background())
|
||||
g.Go(func(ctx context.Context) error {
|
||||
return fakeRunTask(ctx)
|
||||
})
|
||||
g.Go(func(ctx context.Context) error {
|
||||
return fakeRunTask(ctx)
|
||||
})
|
||||
g.Go(fakeRunTask)
|
||||
g.Go(fakeRunTask)
|
||||
if err := g.Wait(); err != nil {
|
||||
// handle err
|
||||
}
|
||||
@@ -51,12 +39,8 @@ func ExampleGroup_maxproc() {
|
||||
g := Group{}
|
||||
// set max concurrency
|
||||
g.GOMAXPROCS(2)
|
||||
g.Go(func(ctx context.Context) error {
|
||||
return fakeRunTask(context.Background())
|
||||
})
|
||||
g.Go(func(ctx context.Context) error {
|
||||
return fakeRunTask(context.Background())
|
||||
})
|
||||
g.Go(fakeRunTask)
|
||||
g.Go(fakeRunTask)
|
||||
if err := g.Wait(); err != nil {
|
||||
// handle err
|
||||
}
|
||||
|
||||
@@ -23,9 +23,9 @@ var (
|
||||
singleFlight = flag.Bool("singleflight", false, "enable singleflight")
|
||||
nullCache = flag.String("nullcache", "", "null cache")
|
||||
checkNullCode = flag.String("check_null_code", "", "check null code")
|
||||
cacheErr = flag.String("cache_err", "continue", "cache err to contine or break")
|
||||
cacheErr = flag.String("cache_err", "continue", "cache err to continue or break")
|
||||
batchSize = flag.Int("batch", 0, "batch size")
|
||||
batchErr = flag.String("batch_err", "break", "batch err to contine or break")
|
||||
batchErr = flag.String("batch_err", "break", "batch err to continue or break")
|
||||
maxGroup = flag.Int("max_group", 0, "max group size")
|
||||
sync = flag.Bool("sync", false, "add cache in sync way.")
|
||||
paging = flag.Bool("paging", false, "use paging in single template")
|
||||
|
||||
@@ -24,7 +24,7 @@ var (
|
||||
expire = flag.String("expire", "", "expire time code")
|
||||
structName = flag.String("struct_name", "dao", "struct name")
|
||||
batchSize = flag.Int("batch", 0, "batch size")
|
||||
batchErr = flag.String("batch_err", "break", "batch err to contine or break")
|
||||
batchErr = flag.String("batch_err", "break", "batch err to continue or break")
|
||||
maxGroup = flag.Int("max_group", 0, "max group size")
|
||||
checkNullCode = flag.String("check_null_code", "", "check null code")
|
||||
nullExpire = flag.String("null_expire", "", "null cache expire time code")
|
||||
|
||||
@@ -20,4 +20,4 @@ func installBMGen() error {
|
||||
|
||||
func genBM(files []string) error {
|
||||
return generate(_bmProtoc, files)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,13 +11,14 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/golang/protobuf/protoc-gen-go/descriptor"
|
||||
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/gen"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/naming"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/typemap"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/utils"
|
||||
"github.com/golang/protobuf/protoc-gen-go/descriptor"
|
||||
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const Version = "v0.1"
|
||||
|
||||
@@ -4,11 +4,12 @@ import (
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/golang/protobuf/proto"
|
||||
"github.com/golang/protobuf/protoc-gen-go/descriptor"
|
||||
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/extensions/gogoproto"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/tag"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/typemap"
|
||||
"github.com/golang/protobuf/proto"
|
||||
"github.com/golang/protobuf/protoc-gen-go/descriptor"
|
||||
)
|
||||
|
||||
// GetJSONFieldName get name from gogoproto.jsontag
|
||||
@@ -95,7 +96,6 @@ func IsMap(field *descriptor.FieldDescriptorProto, reg *typemap.Registry) bool {
|
||||
// IsRepeated Is this field repeated?
|
||||
func IsRepeated(field *descriptor.FieldDescriptorProto) bool {
|
||||
return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED
|
||||
|
||||
}
|
||||
|
||||
// GetFieldRequired is field required?
|
||||
|
||||
@@ -5,11 +5,12 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/tag"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/typemap"
|
||||
"github.com/golang/protobuf/proto"
|
||||
"github.com/golang/protobuf/protoc-gen-go/descriptor"
|
||||
"google.golang.org/genproto/googleapis/api/annotations"
|
||||
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/tag"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/typemap"
|
||||
)
|
||||
|
||||
// HTTPInfo http info for method
|
||||
|
||||
@@ -6,10 +6,11 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/utils"
|
||||
"github.com/golang/protobuf/protoc-gen-go/descriptor"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/siddontang/go/ioutil2"
|
||||
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/utils"
|
||||
)
|
||||
|
||||
// GetVersionPrefix 根据go包名获取api版本前缀
|
||||
|
||||
@@ -5,9 +5,10 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/utils"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/siddontang/go/ioutil2"
|
||||
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/utils"
|
||||
)
|
||||
|
||||
// if proto file is inside a project (that has a /api directory)
|
||||
@@ -73,6 +74,7 @@ func NewProjInfo(file string, modDirName string, modImportPath string) (projInfo
|
||||
i := strings.Index(projInfo.AbsolutePath, modDirName)
|
||||
if i == -1 {
|
||||
err = errors.Errorf("project is not inside module, project=%s, module=%s", projPath, modDirName)
|
||||
return nil, err
|
||||
}
|
||||
relativePath := projInfo.AbsolutePath[i+len(modDirName):]
|
||||
projInfo.ImportPath = modImportPath + relativePath
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
package tag
|
||||
|
||||
import (
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/extensions/gogoproto"
|
||||
"github.com/golang/protobuf/proto"
|
||||
"github.com/golang/protobuf/protoc-gen-go/descriptor"
|
||||
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/extensions/gogoproto"
|
||||
)
|
||||
|
||||
func GetMoreTags(field *descriptor.FieldDescriptorProto) *string {
|
||||
|
||||
@@ -6,14 +6,15 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/golang/protobuf/proto"
|
||||
"github.com/golang/protobuf/protoc-gen-go/descriptor"
|
||||
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
|
||||
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/generator"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/naming"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/tag"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/typemap"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/utils"
|
||||
"github.com/golang/protobuf/proto"
|
||||
"github.com/golang/protobuf/protoc-gen-go/descriptor"
|
||||
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
|
||||
)
|
||||
|
||||
type bm struct {
|
||||
@@ -122,8 +123,7 @@ func (t *bm) generateImports(file *descriptor.FileDescriptorProto) {
|
||||
// It's legal to import a message and use it as an input or output for a
|
||||
// method. Make sure to import the package of any such message. First, dedupe
|
||||
// them.
|
||||
deps := make(map[string]string) // Map of package name to quoted import path.
|
||||
deps = t.DeduceDeps(file)
|
||||
deps := t.DeduceDeps(file)
|
||||
for pkg, importPath := range deps {
|
||||
t.P(`import `, pkg, ` `, importPath)
|
||||
}
|
||||
@@ -132,7 +132,6 @@ func (t *bm) generateImports(file *descriptor.FileDescriptorProto) {
|
||||
t.P(`var _ *bm.Context`)
|
||||
t.P(`var _ context.Context`)
|
||||
t.P(`var _ binding.StructValidator`)
|
||||
|
||||
}
|
||||
|
||||
// Big header comments to makes it easier to visually parse a generated file.
|
||||
|
||||
@@ -7,13 +7,14 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/golang/protobuf/protoc-gen-go/descriptor"
|
||||
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
|
||||
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/gen"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/generator"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/naming"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/tag"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/typemap"
|
||||
"github.com/golang/protobuf/protoc-gen-go/descriptor"
|
||||
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
|
||||
)
|
||||
|
||||
type swaggerGen struct {
|
||||
|
||||
@@ -4,11 +4,12 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/generator"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/naming"
|
||||
"github.com/golang/protobuf/proto"
|
||||
"github.com/golang/protobuf/protoc-gen-go/descriptor"
|
||||
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
|
||||
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/generator"
|
||||
"github.com/go-kratos/kratos/tool/protobuf/pkg/naming"
|
||||
)
|
||||
|
||||
type ecode struct {
|
||||
|
||||
Reference in New Issue
Block a user