From d56e449e08020497dec6a178ee1d0ef3c10e3b7c Mon Sep 17 00:00:00 2001 From: Greg Weber Date: Wed, 22 Aug 2018 17:22:40 -0700 Subject: [PATCH 1/2] switch from juju/errors to pkg/errors pkg/errors maintains a stack trace and its not slower --- cmd/pd-server/main.go | 15 +++--- cmd/pd-tso-bench/main.go | 2 +- pd-client/client.go | 48 +++++++++---------- pdctl/command/global.go | 4 +- pdctl/command/operator.go | 4 +- pkg/apiutil/apiutil.go | 6 +-- pkg/etcdutil/etcdutil.go | 8 ++-- pkg/faketikv/client.go | 12 ++--- pkg/faketikv/cluster.go | 6 +-- pkg/faketikv/drive.go | 12 ++--- pkg/integration_test/cluster.go | 26 +++++------ pkg/integration_test/config.go | 4 +- pkg/integration_test/member_test.go | 2 +- pkg/logutil/log.go | 4 +- pkg/typeutil/duration.go | 8 ++-- pkg/typeutil/size.go | 8 ++-- pkg/typeutil/string_slice.go | 4 +- server/api/classifier.go | 2 +- server/api/config.go | 2 +- server/api/diagnose.go | 4 +- server/api/label.go | 6 +-- server/api/member.go | 6 +-- server/api/store.go | 4 +- server/api/trend.go | 6 +-- server/api/util.go | 10 ++-- server/api/utiletcdhttpapi.go | 6 +-- server/cluster.go | 14 +++--- server/cluster_info.go | 18 +++---- server/cluster_info_test.go | 4 +- server/cluster_worker.go | 25 +++++----- server/config.go | 36 +++++++------- server/coordinator.go | 6 +-- server/coordinator_test.go | 2 +- server/core/kv.go | 40 ++++++++-------- server/core/kv_test.go | 2 +- server/etcd_kv.go | 16 +++---- server/grpc_service.go | 66 +++++++++++++------------- server/handler.go | 70 ++++++++++++++-------------- server/id.go | 10 ++-- server/join.go | 12 ++--- server/leader.go | 27 +++++------ server/namespace/classifier.go | 2 +- server/option.go | 8 ++-- server/schedule/basic_cluster.go | 4 +- server/schedule/mockcluster.go | 4 +- server/schedule/operator.go | 6 +-- server/schedule/operator_kind.go | 2 +- server/schedule/scheduler.go | 2 +- server/schedulers/adjacent_region.go | 6 +-- server/schedulers/evict_leader.go | 6 +-- server/schedulers/grant_leader.go | 6 +-- server/schedulers/scatter_range.go | 2 +- server/server.go | 66 +++++++++++++------------- server/testutil.go | 6 +-- server/tso.go | 12 ++--- server/util.go | 18 +++---- table/codec.go | 2 +- table/namespace_classifier.go | 20 ++++---- table/namespace_handler.go | 2 +- 59 files changed, 372 insertions(+), 369 deletions(-) diff --git a/cmd/pd-server/main.go b/cmd/pd-server/main.go index 864b3589549..39c457415ce 100644 --- a/cmd/pd-server/main.go +++ b/cmd/pd-server/main.go @@ -16,16 +16,17 @@ package main import ( "context" "flag" + "fmt" "os" "os/signal" "syscall" "github.com/grpc-ecosystem/go-grpc-prometheus" - "github.com/juju/errors" "github.com/pingcap/pd/pkg/logutil" "github.com/pingcap/pd/pkg/metricutil" "github.com/pingcap/pd/server" "github.com/pingcap/pd/server/api" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" // Register schedulers. @@ -50,12 +51,12 @@ func main() { case flag.ErrHelp: os.Exit(0) default: - log.Fatalf("parse cmd flags error: %s\n", errors.ErrorStack(err)) + log.Fatalf("parse cmd flags error: %s\n", fmt.Sprintf("%+v", err)) } err = logutil.InitLogger(&cfg.Log) if err != nil { - log.Fatalf("initialize logger error: %s\n", errors.ErrorStack(err)) + log.Fatalf("initialize logger error: %s\n", fmt.Sprintf("%+v", err)) } server.LogPDInfo() @@ -71,15 +72,15 @@ func main() { err = server.PrepareJoinCluster(cfg) if err != nil { - log.Fatal("join error ", errors.ErrorStack(err)) + log.Fatal("join error ", fmt.Sprintf("%+v", err)) } svr, err := server.CreateServer(cfg, api.NewHandler) if err != nil { - log.Fatalf("create server failed: %v", errors.ErrorStack(err)) + log.Fatalf("create server failed: %v", fmt.Sprintf("%+v", err)) } if err = server.InitHTTPClient(svr); err != nil { - log.Fatalf("initial http client for api handler failed: %v", errors.ErrorStack(err)) + log.Fatalf("initial http client for api handler failed: %v", fmt.Sprintf("%+v", err)) } sc := make(chan os.Signal, 1) @@ -97,7 +98,7 @@ func main() { }() if err := svr.Run(ctx); err != nil { - log.Fatalf("run server failed: %v", errors.ErrorStack(err)) + log.Fatalf("run server failed: %v", fmt.Sprintf("%+v", err)) } <-ctx.Done() diff --git a/cmd/pd-tso-bench/main.go b/cmd/pd-tso-bench/main.go index 10db0dfd92a..2bcd3179eaf 100644 --- a/cmd/pd-tso-bench/main.go +++ b/cmd/pd-tso-bench/main.go @@ -24,8 +24,8 @@ import ( "syscall" "time" - "github.com/juju/errors" "github.com/pingcap/pd/pd-client" + "github.com/pkg/errors" ) var ( diff --git a/pd-client/client.go b/pd-client/client.go index 99715456e43..97b6667d735 100644 --- a/pd-client/client.go +++ b/pd-client/client.go @@ -22,10 +22,10 @@ import ( "sync" "time" - "github.com/juju/errors" "github.com/opentracing/opentracing-go" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" "golang.org/x/net/context" "google.golang.org/grpc" @@ -131,10 +131,10 @@ func NewClient(pdAddrs []string, security SecurityOption) (Client, error) { c.connMu.clientConns = make(map[string]*grpc.ClientConn) if err := c.initClusterID(); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } if err := c.updateLeader(); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } log.Infof("[pd] init cluster id %v", c.clusterID) @@ -171,7 +171,7 @@ func (c *client) initClusterID() error { time.Sleep(time.Second) } - return errors.Trace(errFailInitClusterID) + return errors.WithStack(errFailInitClusterID) } func (c *client) updateLeader() error { @@ -182,14 +182,14 @@ func (c *client) updateLeader() error { if err != nil || members.GetLeader() == nil || len(members.GetLeader().GetClientUrls()) == 0 { select { case <-c.ctx.Done(): - return errors.Trace(err) + return errors.WithStack(err) default: continue } } c.updateURLs(members.GetMembers()) if err = c.switchLeader(members.GetLeader().GetClientUrls()); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } return nil } @@ -199,11 +199,11 @@ func (c *client) updateLeader() error { func (c *client) getMembers(ctx context.Context, url string) (*pdpb.GetMembersResponse, error) { cc, err := c.getOrCreateGRPCConn(url) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } members, err := pdpb.NewPDClient(cc).GetMembers(ctx, &pdpb.GetMembersRequest{}) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return members, nil } @@ -222,7 +222,7 @@ func (c *client) switchLeader(addrs []string) error { log.Infof("[pd] leader switches to: %v, previous: %v", addr, oldLeader) if _, err := c.getOrCreateGRPCConn(addr); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } c.connMu.Lock() @@ -273,11 +273,11 @@ func (c *client) getOrCreateGRPCConn(addr string) (*grpc.ClientConn, error) { } u, err := url.Parse(addr) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cc, err := grpc.Dial(u.Host, opt) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } c.connMu.Lock() defer c.connMu.Unlock() @@ -440,20 +440,20 @@ func (c *client) processTSORequests(stream pdpb.PD_TsoClient, requests []*tsoReq if err := stream.Send(req); err != nil { c.finishTSORequest(requests, 0, 0, err) - return errors.Trace(err) + return errors.WithStack(err) } resp, err := stream.Recv() if err != nil { - c.finishTSORequest(requests, 0, 0, errors.Trace(err)) - return errors.Trace(err) + c.finishTSORequest(requests, 0, 0, errors.WithStack(err)) + return errors.WithStack(err) } requestDuration.WithLabelValues("tso").Observe(time.Since(start).Seconds()) if err == nil && resp.GetCount() != uint32(len(requests)) { err = errTSOLength } if err != nil { - c.finishTSORequest(requests, 0, 0, errors.Trace(err)) - return errors.Trace(err) + c.finishTSORequest(requests, 0, 0, errors.WithStack(err)) + return errors.WithStack(err) } physical, logical := resp.GetTimestamp().GetPhysical(), resp.GetTimestamp().GetLogical() @@ -477,7 +477,7 @@ func (c *client) revokeTSORequest(err error) { n := len(c.tsoRequests) for i := 0; i < n; i++ { req := <-c.tsoRequests - req.done <- errors.Trace(err) + req.done <- errors.WithStack(err) } } @@ -564,13 +564,13 @@ func (req *tsoRequest) Wait() (int64, int64, error) { defer tsoReqPool.Put(req) if err != nil { cmdFailedDuration.WithLabelValues("tso").Observe(time.Since(req.start).Seconds()) - return 0, 0, errors.Trace(err) + return 0, 0, errors.WithStack(err) } physical, logical := req.physical, req.logical cmdDuration.WithLabelValues("tso").Observe(time.Since(req.start).Seconds()) return physical, logical, err case <-req.ctx.Done(): - return 0, 0, errors.Trace(req.ctx.Err()) + return 0, 0, errors.WithStack(req.ctx.Err()) } } @@ -597,7 +597,7 @@ func (c *client) GetRegion(ctx context.Context, key []byte) (*metapb.Region, *me if err != nil { cmdFailedDuration.WithLabelValues("get_region").Observe(time.Since(start).Seconds()) c.ScheduleCheckLeader() - return nil, nil, errors.Trace(err) + return nil, nil, errors.WithStack(err) } return resp.GetRegion(), resp.GetLeader(), nil } @@ -620,7 +620,7 @@ func (c *client) GetPrevRegion(ctx context.Context, key []byte) (*metapb.Region, if err != nil { cmdFailedDuration.WithLabelValues("get_prev_region").Observe(time.Since(start).Seconds()) c.ScheduleCheckLeader() - return nil, nil, errors.Trace(err) + return nil, nil, errors.WithStack(err) } return resp.GetRegion(), resp.GetLeader(), nil } @@ -643,7 +643,7 @@ func (c *client) GetRegionByID(ctx context.Context, regionID uint64) (*metapb.Re if err != nil { cmdFailedDuration.WithLabelValues("get_region_byid").Observe(time.Since(start).Seconds()) c.ScheduleCheckLeader() - return nil, nil, errors.Trace(err) + return nil, nil, errors.WithStack(err) } return resp.GetRegion(), resp.GetLeader(), nil } @@ -666,7 +666,7 @@ func (c *client) GetStore(ctx context.Context, storeID uint64) (*metapb.Store, e if err != nil { cmdFailedDuration.WithLabelValues("get_store").Observe(time.Since(start).Seconds()) c.ScheduleCheckLeader() - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } store := resp.GetStore() if store == nil { @@ -696,7 +696,7 @@ func (c *client) UpdateGCSafePoint(ctx context.Context, safePoint uint64) (uint6 if err != nil { cmdFailedDuration.WithLabelValues("update_gc_safe_point").Observe(time.Since(start).Seconds()) c.ScheduleCheckLeader() - return 0, errors.Trace(err) + return 0, errors.WithStack(err) } return resp.GetNewSafePoint(), nil } diff --git a/pdctl/command/global.go b/pdctl/command/global.go index f2fbb8fb9de..19f16991f3d 100644 --- a/pdctl/command/global.go +++ b/pdctl/command/global.go @@ -24,7 +24,7 @@ import ( "os" "github.com/coreos/etcd/pkg/transport" - "github.com/juju/errors" + "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -43,7 +43,7 @@ func InitHTTPSClient(CAPath, CertPath, KeyPath string) error { } tlsConfig, err := tlsInfo.ClientConfig() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } dialClient = &http.Client{Transport: &http.Transport{ diff --git a/pdctl/command/operator.go b/pdctl/command/operator.go index 2fcffcb89ff..8d728e82d03 100644 --- a/pdctl/command/operator.go +++ b/pdctl/command/operator.go @@ -18,7 +18,7 @@ import ( "net/http" "strconv" - "github.com/juju/errors" + "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -355,7 +355,7 @@ func parseUint64s(args []string) ([]uint64, error) { for _, arg := range args { v, err := strconv.ParseUint(arg, 10, 64) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } results = append(results, v) } diff --git a/pkg/apiutil/apiutil.go b/pkg/apiutil/apiutil.go index c024b78a5a5..ed232c31a8a 100644 --- a/pkg/apiutil/apiutil.go +++ b/pkg/apiutil/apiutil.go @@ -20,14 +20,14 @@ import ( "io/ioutil" "strconv" - "github.com/juju/errors" + "github.com/pkg/errors" ) // DeferClose captures the error returned from closing (if an error occurs). // This is designed to be used in a defer statement. func DeferClose(c io.Closer, err *error) { if cerr := c.Close(); cerr != nil && *err == nil { - *err = errors.Trace(cerr) + *err = errors.WithStack(cerr) } } @@ -55,7 +55,7 @@ func ReadJSON(r io.ReadCloser, data interface{}) error { defer DeferClose(r, &err) b, err := ioutil.ReadAll(r) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } err = json.Unmarshal(b, data) diff --git a/pkg/etcdutil/etcdutil.go b/pkg/etcdutil/etcdutil.go index 6a0b34c9bc6..2e9bdf1a1dd 100644 --- a/pkg/etcdutil/etcdutil.go +++ b/pkg/etcdutil/etcdutil.go @@ -22,7 +22,7 @@ import ( "github.com/coreos/etcd/clientv3" "github.com/coreos/etcd/etcdserver" "github.com/coreos/etcd/pkg/types" - "github.com/juju/errors" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -76,7 +76,7 @@ func AddEtcdMember(client *clientv3.Client, urls []string) (*clientv3.MemberAddR ctx, cancel := context.WithTimeout(client.Ctx(), DefaultRequestTimeout) addResp, err := client.MemberAdd(ctx, urls) cancel() - return addResp, errors.Trace(err) + return addResp, errors.WithStack(err) } // ListEtcdMembers returns a list of internal etcd members. @@ -84,7 +84,7 @@ func ListEtcdMembers(client *clientv3.Client) (*clientv3.MemberListResponse, err ctx, cancel := context.WithTimeout(client.Ctx(), DefaultRequestTimeout) listResp, err := client.MemberList(ctx) cancel() - return listResp, errors.Trace(err) + return listResp, errors.WithStack(err) } // RemoveEtcdMember removes a member by the given id. @@ -92,5 +92,5 @@ func RemoveEtcdMember(client *clientv3.Client, id uint64) (*clientv3.MemberRemov ctx, cancel := context.WithTimeout(client.Ctx(), DefaultRequestTimeout) rmResp, err := client.MemberRemove(ctx, id) cancel() - return rmResp, errors.Trace(err) + return rmResp, errors.WithStack(err) } diff --git a/pkg/faketikv/client.go b/pkg/faketikv/client.go index bc519920822..4ac0cc7f6ff 100644 --- a/pkg/faketikv/client.go +++ b/pkg/faketikv/client.go @@ -19,11 +19,11 @@ import ( "sync" "time" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/pkg/faketikv/simutil" "github.com/pingcap/pd/server/core" + "github.com/pkg/errors" "google.golang.org/grpc" ) @@ -77,11 +77,11 @@ func NewClient(pdAddr string, tag string) (Client, <-chan *pdpb.RegionHeartbeatR } cc, err := c.createConn() if err != nil { - return nil, nil, errors.Trace(err) + return nil, nil, errors.WithStack(err) } c.clientConn = cc if err := c.initClusterID(); err != nil { - return nil, nil, errors.Trace(err) + return nil, nil, errors.WithStack(err) } simutil.Logger.Infof("[%s][pd] init cluster id %v", tag, c.clusterID) c.wg.Add(1) @@ -107,13 +107,13 @@ func (c *client) initClusterID() error { return nil } - return errors.Trace(errFailInitClusterID) + return errors.WithStack(errFailInitClusterID) } func (c *client) getMembers(ctx context.Context) (*pdpb.GetMembersResponse, error) { members, err := c.pdClient().GetMembers(ctx, &pdpb.GetMembersRequest{}) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return members, nil } @@ -121,7 +121,7 @@ func (c *client) getMembers(ctx context.Context) (*pdpb.GetMembersResponse, erro func (c *client) createConn() (*grpc.ClientConn, error) { cc, err := grpc.Dial(strings.TrimPrefix(c.url, "http://"), grpc.WithInsecure()) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return cc, nil } diff --git a/pkg/faketikv/cluster.go b/pkg/faketikv/cluster.go index f60a475b9f3..186b2639bc3 100644 --- a/pkg/faketikv/cluster.go +++ b/pkg/faketikv/cluster.go @@ -16,9 +16,9 @@ package faketikv import ( "context" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/pd/pkg/faketikv/cases" + "github.com/pkg/errors" ) // ClusterInfo records all cluster information. @@ -37,7 +37,7 @@ func NewClusterInfo(pdAddr string, conf *cases.Conf) (*ClusterInfo, error) { for _, store := range conf.Stores { node, err := NewNode(store, pdAddr) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster.Nodes[store.ID] = node } @@ -71,5 +71,5 @@ func (c *ClusterInfo) allocID(storeID uint64) (uint64, error) { return 0, errors.Errorf("node %d not found", storeID) } id, err := node.client.AllocID(context.Background()) - return id, errors.Trace(err) + return id, errors.WithStack(err) } diff --git a/pkg/faketikv/drive.go b/pkg/faketikv/drive.go index 5b5c9530f7c..d0c45f2e5c7 100644 --- a/pkg/faketikv/drive.go +++ b/pkg/faketikv/drive.go @@ -16,11 +16,11 @@ package faketikv import ( "context" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/pkg/faketikv/cases" "github.com/pingcap/pd/pkg/faketikv/simutil" + "github.com/pkg/errors" ) // Driver promotes the cluster status change. @@ -52,18 +52,18 @@ func (d *Driver) Prepare() error { clusterInfo, err := NewClusterInfo(d.addr, d.conf) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } d.clusterInfo = clusterInfo conn, err := NewConn(d.clusterInfo.Nodes) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } raftEngine, err := NewRaftEngine(d.conf, conn) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } d.raftEngine = raftEngine @@ -74,7 +74,7 @@ func (d *Driver) Prepare() error { // Bootstrap. store, region, err := clusterInfo.GetBootstrapInfo(d.raftEngine) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } d.client = clusterInfo.Nodes[store.GetId()].client @@ -91,7 +91,7 @@ func (d *Driver) Prepare() error { for { id, err := d.client.AllocID(context.Background()) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if id > d.conf.MaxID { break diff --git a/pkg/integration_test/cluster.go b/pkg/integration_test/cluster.go index 116edfc2ca4..20902d243c2 100644 --- a/pkg/integration_test/cluster.go +++ b/pkg/integration_test/cluster.go @@ -21,10 +21,10 @@ import ( "github.com/coreos/etcd/clientv3" "github.com/coreos/go-semver/semver" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/server" "github.com/pingcap/pd/server/api" + "github.com/pkg/errors" ) // testServer states. @@ -46,17 +46,17 @@ var initHTTPClientOnce sync.Once func newTestServer(cfg *server.Config) (*testServer, error) { err := server.PrepareJoinCluster(cfg) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } svr, err := server.CreateServer(cfg, api.NewHandler) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } initHTTPClientOnce.Do(func() { err = server.InitHTTPClient(svr) }) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return &testServer{ server: svr, @@ -71,7 +71,7 @@ func (s *testServer) Run(ctx context.Context) error { return errors.Errorf("server(state%d) cannot run", s.state) } if err := s.server.Run(ctx); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } s.state = Running return nil @@ -141,7 +141,7 @@ func (s *testServer) GetEtcdLeader() (string, error) { req := &pdpb.GetMembersRequest{Header: &pdpb.RequestHeader{ClusterId: s.server.ClusterID()}} members, err := s.server.GetMembers(context.TODO(), req) if err != nil { - return "", errors.Trace(err) + return "", errors.WithStack(err) } return members.GetEtcdLeader().GetName(), nil } @@ -163,11 +163,11 @@ func newTestCluster(initialServerCount int) (*testCluster, error) { for _, conf := range config.InitialServers { serverConf, err := conf.Generate() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } s, err := newTestServer(serverConf) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } servers[conf.Name] = s } @@ -190,7 +190,7 @@ func (c *testCluster) RunServers(ctx context.Context, servers []*testServer) err } for _, c := range res { if err := <-c; err != nil { - return errors.Trace(err) + return errors.WithStack(err) } } return nil @@ -207,7 +207,7 @@ func (c *testCluster) RunInitialServers() error { func (c *testCluster) StopAll() error { for _, s := range c.servers { if err := s.Stop(); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } } return nil @@ -239,11 +239,11 @@ func (c *testCluster) WaitLeader() string { func (c *testCluster) Join() (*testServer, error) { conf, err := c.config.Join().Generate() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } s, err := newTestServer(conf) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } c.servers[conf.Name] = s return s, nil @@ -253,7 +253,7 @@ func (c *testCluster) Destroy() error { for _, s := range c.servers { err := s.Destroy() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } } return nil diff --git a/pkg/integration_test/config.go b/pkg/integration_test/config.go index 599beec3268..ea937cd6ae5 100644 --- a/pkg/integration_test/config.go +++ b/pkg/integration_test/config.go @@ -18,9 +18,9 @@ import ( "io/ioutil" "strings" - "github.com/juju/errors" "github.com/pingcap/pd/pkg/tempurl" "github.com/pingcap/pd/server" + "github.com/pkg/errors" ) type serverConfig struct { @@ -64,7 +64,7 @@ func (c *serverConfig) Generate() (*server.Config, error) { cfg := server.NewConfig() err := cfg.Parse(arguments) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return cfg, nil } diff --git a/pkg/integration_test/member_test.go b/pkg/integration_test/member_test.go index 456f3e335d5..e41391053ae 100644 --- a/pkg/integration_test/member_test.go +++ b/pkg/integration_test/member_test.go @@ -21,11 +21,11 @@ import ( "net/http" "time" - "github.com/juju/errors" . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/pkg/testutil" "github.com/pingcap/pd/server" + "github.com/pkg/errors" ) func (s *integrationTestSuite) TestMemberDelete(c *C) { diff --git a/pkg/logutil/log.go b/pkg/logutil/log.go index 86f553f0699..a2b5b3b47eb 100644 --- a/pkg/logutil/log.go +++ b/pkg/logutil/log.go @@ -24,7 +24,7 @@ import ( "sync" "github.com/coreos/pkg/capnslog" - "github.com/juju/errors" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" lumberjack "gopkg.in/natefinch/lumberjack.v2" ) @@ -242,7 +242,7 @@ func InitLogger(cfg *LogConfig) error { err = InitFileLog(&cfg.File) }) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } return nil } diff --git a/pkg/typeutil/duration.go b/pkg/typeutil/duration.go index 46148712917..c29c8de8ed6 100644 --- a/pkg/typeutil/duration.go +++ b/pkg/typeutil/duration.go @@ -18,7 +18,7 @@ import ( "strconv" "time" - "github.com/juju/errors" + "github.com/pkg/errors" ) // Duration is a wrapper of time.Duration for TOML and JSON. @@ -40,11 +40,11 @@ func (d *Duration) MarshalJSON() ([]byte, error) { func (d *Duration) UnmarshalJSON(text []byte) error { s, err := strconv.Unquote(string(text)) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } duration, err := time.ParseDuration(s) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } d.Duration = duration return nil @@ -54,5 +54,5 @@ func (d *Duration) UnmarshalJSON(text []byte) error { func (d *Duration) UnmarshalText(text []byte) error { var err error d.Duration, err = time.ParseDuration(string(text)) - return errors.Trace(err) + return errors.WithStack(err) } diff --git a/pkg/typeutil/size.go b/pkg/typeutil/size.go index 08523316ecd..3b58c73ccfa 100644 --- a/pkg/typeutil/size.go +++ b/pkg/typeutil/size.go @@ -17,7 +17,7 @@ import ( "strconv" gh "github.com/dustin/go-humanize" - "github.com/juju/errors" + "github.com/pkg/errors" ) // ByteSize is a retype uint64 for TOML and JSON. @@ -32,11 +32,11 @@ func (b ByteSize) MarshalJSON() ([]byte, error) { func (b *ByteSize) UnmarshalJSON(text []byte) error { s, err := strconv.Unquote(string(text)) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } v, err := gh.ParseBytes(s) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } *b = ByteSize(v) return nil @@ -46,7 +46,7 @@ func (b *ByteSize) UnmarshalJSON(text []byte) error { func (b *ByteSize) UnmarshalText(text []byte) error { v, err := gh.ParseBytes(string(text)) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } *b = ByteSize(v) return nil diff --git a/pkg/typeutil/string_slice.go b/pkg/typeutil/string_slice.go index 2ff515ca2ac..e62df9032ec 100644 --- a/pkg/typeutil/string_slice.go +++ b/pkg/typeutil/string_slice.go @@ -17,7 +17,7 @@ import ( "strconv" "strings" - "github.com/juju/errors" + "github.com/pkg/errors" ) //StringSlice is more friendly to json encode/decode @@ -32,7 +32,7 @@ func (s StringSlice) MarshalJSON() ([]byte, error) { func (s *StringSlice) UnmarshalJSON(text []byte) error { data, err := strconv.Unquote(string(text)) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if len(data) == 0 { *s = nil diff --git a/server/api/classifier.go b/server/api/classifier.go index e6847f633ef..31a081e68bf 100644 --- a/server/api/classifier.go +++ b/server/api/classifier.go @@ -16,8 +16,8 @@ package api import ( "net/http" - "github.com/juju/errors" "github.com/pingcap/pd/server" + "github.com/pkg/errors" "github.com/unrolled/render" ) diff --git a/server/api/config.go b/server/api/config.go index 6e93974984a..d05b07042c1 100644 --- a/server/api/config.go +++ b/server/api/config.go @@ -20,9 +20,9 @@ import ( "net/http" "github.com/gorilla/mux" - "github.com/juju/errors" "github.com/pingcap/pd/pkg/error_code" "github.com/pingcap/pd/server" + "github.com/pkg/errors" "github.com/unrolled/render" ) diff --git a/server/api/diagnose.go b/server/api/diagnose.go index 374a2532c38..23243787b94 100644 --- a/server/api/diagnose.go +++ b/server/api/diagnose.go @@ -19,9 +19,9 @@ import ( "net/http" "time" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/server" + "github.com/pkg/errors" "github.com/unrolled/render" ) @@ -115,7 +115,7 @@ func (d *diagnoseHandler) membersDiagnose(rdd *[]*Recommendation) error { req := &pdpb.GetMembersRequest{Header: &pdpb.RequestHeader{ClusterId: d.svr.ClusterID()}} members, err := d.svr.GetMembers(context.Background(), req) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } lenMembers := len(members.Members) if lenMembers > 0 { diff --git a/server/api/label.go b/server/api/label.go index 5586db236a9..4cb4dcedecf 100644 --- a/server/api/label.go +++ b/server/api/label.go @@ -18,9 +18,9 @@ import ( "regexp" "strings" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/pd/server" + "github.com/pkg/errors" "github.com/unrolled/render" ) @@ -102,11 +102,11 @@ func newStoresLabelFilter(name, value string) (*storesLabelFilter, error) { // add (?i) to set a case-insensitive flag keyPattern, err := regexp.Compile("(?i)" + name) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } valuePattern, err := regexp.Compile("(?i)" + value) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return &storesLabelFilter{ keyPattern: keyPattern, diff --git a/server/api/member.go b/server/api/member.go index 0450be9770b..404a9a73c76 100644 --- a/server/api/member.go +++ b/server/api/member.go @@ -20,10 +20,10 @@ import ( "strconv" "github.com/gorilla/mux" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/pkg/etcdutil" "github.com/pingcap/pd/server" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" "github.com/unrolled/render" ) @@ -53,7 +53,7 @@ func (h *memberHandler) listMembers() (*pdpb.GetMembersResponse, error) { req := &pdpb.GetMembersRequest{Header: &pdpb.RequestHeader{ClusterId: h.svr.ClusterID()}} members, err := h.svr.GetMembers(context.Background(), req) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } // Fill leader priorities. for _, m := range members.GetMembers() { @@ -68,7 +68,7 @@ func (h *memberHandler) listMembers() (*pdpb.GetMembersResponse, error) { } m.LeaderPriority = int32(leaderPriority) } - return members, errors.Trace(err) + return members, errors.WithStack(err) } func (h *memberHandler) DeleteByName(w http.ResponseWriter, r *http.Request) { diff --git a/server/api/store.go b/server/api/store.go index 1e0a1f51ceb..891cc8f7801 100644 --- a/server/api/store.go +++ b/server/api/store.go @@ -20,13 +20,13 @@ import ( "time" "github.com/gorilla/mux" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/pd/pkg/apiutil" "github.com/pingcap/pd/pkg/error_code" "github.com/pingcap/pd/pkg/typeutil" "github.com/pingcap/pd/server" "github.com/pingcap/pd/server/core" + "github.com/pkg/errors" "github.com/unrolled/render" ) @@ -360,7 +360,7 @@ func newStoreStateFilter(u *url.URL) (*storeStateFilter, error) { for _, s := range v { state, err := strconv.Atoi(s) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } storeState := metapb.StoreState(state) diff --git a/server/api/trend.go b/server/api/trend.go index eb8cd2a0951..b559716bdd0 100644 --- a/server/api/trend.go +++ b/server/api/trend.go @@ -18,10 +18,10 @@ import ( "strconv" "time" - "github.com/juju/errors" "github.com/pingcap/pd/pkg/typeutil" "github.com/pingcap/pd/server" "github.com/pingcap/pd/server/core" + "github.com/pkg/errors" "github.com/unrolled/render" ) @@ -116,7 +116,7 @@ func (h *trendHandler) getTrendStores() ([]trendStore, error) { } stores, err := h.GetStores() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } trendStores := make([]trendStore, 0, len(stores)) @@ -157,7 +157,7 @@ func (h *trendHandler) getStoreFlow(stats core.StoreHotRegionsStat, storeID uint func (h *trendHandler) getTrendHistory(start time.Time) (*trendHistory, error) { operatorHistory, err := h.GetHistory(start) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } // Use a tmp map to merge same histories together. historyMap := make(map[trendHistoryEntry]int) diff --git a/server/api/util.go b/server/api/util.go index 7e10134c44a..c94ab46cdac 100644 --- a/server/api/util.go +++ b/server/api/util.go @@ -20,10 +20,10 @@ import ( "io/ioutil" "net/http" - "github.com/juju/errors" "github.com/pingcap/pd/pkg/apiutil" "github.com/pingcap/pd/pkg/error_code" "github.com/pingcap/pd/server" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" "github.com/unrolled/render" ) @@ -70,11 +70,11 @@ func readJSON(r io.ReadCloser, data interface{}) error { b, err := ioutil.ReadAll(r) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } err = json.Unmarshal(b, data) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } return nil @@ -83,7 +83,7 @@ func readJSON(r io.ReadCloser, data interface{}) error { func postJSON(url string, data []byte) error { resp, err := server.DialClient.Post(url, "application/json", bytes.NewBuffer(data)) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } res, err := ioutil.ReadAll(resp.Body) resp.Body.Close() @@ -112,7 +112,7 @@ func doDelete(url string) error { func doGet(url string) (*http.Response, error) { resp, err := server.DialClient.Get(url) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } if resp.StatusCode != http.StatusOK { return nil, errors.Errorf("http get url %s return code %d", url, resp.StatusCode) diff --git a/server/api/utiletcdhttpapi.go b/server/api/utiletcdhttpapi.go index f0b34ebb6b2..4bac28ccc9f 100644 --- a/server/api/utiletcdhttpapi.go +++ b/server/api/utiletcdhttpapi.go @@ -17,7 +17,7 @@ import ( "fmt" "time" - "github.com/juju/errors" + "github.com/pkg/errors" ) const ( @@ -45,11 +45,11 @@ func getEtcdPeerStats(etcdClientURL string) (*PeerStats, error) { ps := &PeerStats{} resp, err := doGet(fmt.Sprintf("%s%s", etcdClientURL, etcdPeerStatsAPI)) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } defer resp.Body.Close() if err := readJSON(resp.Body, ps); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return ps, nil } diff --git a/server/cluster.go b/server/cluster.go index c3fceaf004b..051d9ad3838 100644 --- a/server/cluster.go +++ b/server/cluster.go @@ -19,13 +19,13 @@ import ( "sync" "time" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/pkg/error_code" "github.com/pingcap/pd/pkg/logutil" "github.com/pingcap/pd/server/core" "github.com/pingcap/pd/server/namespace" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -76,14 +76,14 @@ func newRaftCluster(s *Server, clusterID uint64) *RaftCluster { func (c *RaftCluster) loadClusterStatus() (*ClusterStatus, error) { data, err := c.s.kv.Load((c.s.kv.ClusterStatePath("raft_bootstrap_time"))) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } if len(data) == 0 { return &ClusterStatus{}, nil } t, err := parseTimestamp([]byte(data)) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return &ClusterStatus{RaftBootstrapTime: t}, nil } @@ -99,7 +99,7 @@ func (c *RaftCluster) start() error { cluster, err := loadClusterInfo(c.s.idAlloc, c.s.kv, c.s.scheduleOpt) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if cluster == nil { return nil @@ -107,7 +107,7 @@ func (c *RaftCluster) start() error { err = c.s.classifier.ReloadNamespaces() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } c.cachedCluster = cluster @@ -295,7 +295,7 @@ func (c *RaftCluster) UpdateStoreLabels(storeID uint64, labels []*metapb.StoreLa storeMeta.Labels = labels // putStore will perform label merge. err := c.putStore(storeMeta) - return errors.Trace(err) + return errors.WithStack(err) } func (c *RaftCluster) putStore(store *metapb.Store) error { @@ -435,7 +435,7 @@ func (c *RaftCluster) SetStoreWeight(storeID uint64, leader, region float64) err } if err := c.s.kv.SaveStoreWeight(storeID, leader, region); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } store.LeaderWeight, store.RegionWeight = leader, region diff --git a/server/cluster_info.go b/server/cluster_info.go index 7302a2600da..8ed864cc7a9 100644 --- a/server/cluster_info.go +++ b/server/cluster_info.go @@ -19,12 +19,12 @@ import ( "github.com/coreos/go-semver/semver" "github.com/gogo/protobuf/proto" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/server/core" "github.com/pingcap/pd/server/namespace" "github.com/pingcap/pd/server/schedule" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -58,7 +58,7 @@ func loadClusterInfo(id core.IDAllocator, kv *core.KV, opt *scheduleOption) (*cl c.meta = &metapb.Cluster{} ok, err := kv.LoadMeta(c.meta) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } if !ok { return nil, nil @@ -66,13 +66,13 @@ func loadClusterInfo(id core.IDAllocator, kv *core.KV, opt *scheduleOption) (*cl start := time.Now() if err := kv.LoadStores(c.core.Stores); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } log.Infof("load %v stores cost %v", c.core.Stores.GetStoreCount(), time.Since(start)) start = time.Now() if err := kv.LoadRegions(c.core.Regions); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } log.Infof("load %v regions cost %v", c.core.Regions.GetRegionCount(), time.Since(start)) @@ -124,7 +124,7 @@ func (c *clusterInfo) AllocPeer(storeID uint64) (*metapb.Peer, error) { peerID, err := c.allocID() if err != nil { log.Errorf("failed to alloc peer: %v", err) - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } peer := &metapb.Peer{ Id: peerID, @@ -154,7 +154,7 @@ func (c *clusterInfo) putMeta(meta *metapb.Cluster) error { func (c *clusterInfo) putMetaLocked(meta *metapb.Cluster) error { if c.kv != nil { if err := c.kv.SaveMeta(meta); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } } c.meta = meta @@ -177,7 +177,7 @@ func (c *clusterInfo) putStore(store *core.StoreInfo) error { func (c *clusterInfo) putStoreLocked(store *core.StoreInfo) error { if c.kv != nil { if err := c.kv.SaveStore(store.Store); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } } return c.core.PutStore(store) @@ -300,7 +300,7 @@ func (c *clusterInfo) putRegion(region *core.RegionInfo) error { func (c *clusterInfo) putRegionLocked(region *core.RegionInfo) error { if c.kv != nil { if err := c.kv.SaveRegion(region.Region); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } } return c.core.PutRegion(region) @@ -465,7 +465,7 @@ func (c *clusterInfo) handleRegionHeartbeat(region *core.RegionInfo) error { o := origin.GetRegionEpoch() // Region meta is stale, return an error. if r.GetVersion() < o.GetVersion() || r.GetConfVer() < o.GetConfVer() { - return errors.Trace(ErrRegionIsStale(region.Region, origin.Region)) + return errors.WithStack(ErrRegionIsStale(region.Region, origin.Region)) } if r.GetVersion() > o.GetVersion() { log.Infof("[region %d] %s, Version changed from {%d} to {%d}", region.GetId(), core.DiffRegionKeyInfo(origin, region), o.GetVersion(), r.GetVersion()) diff --git a/server/cluster_info_test.go b/server/cluster_info_test.go index ed5a5d1cc80..66d41c0d7bb 100644 --- a/server/cluster_info_test.go +++ b/server/cluster_info_test.go @@ -16,11 +16,11 @@ package server import ( "math/rand" - "github.com/juju/errors" . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/server/core" + "github.com/pkg/errors" ) var _ = Suite(&testStoresInfoSuite{}) @@ -32,7 +32,7 @@ func checkStaleRegion(origin *metapb.Region, region *metapb.Region) error { e := region.GetRegionEpoch() if e.GetVersion() < o.GetVersion() || e.GetConfVer() < o.GetConfVer() { - return errors.Trace(ErrRegionIsStale(region, origin)) + return errors.WithStack(ErrRegionIsStale(region, origin)) } return nil diff --git a/server/cluster_worker.go b/server/cluster_worker.go index c36cd0c82bc..7853256a3bf 100644 --- a/server/cluster_worker.go +++ b/server/cluster_worker.go @@ -15,19 +15,20 @@ package server import ( "bytes" + "fmt" "github.com/gogo/protobuf/proto" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/server/core" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) // HandleRegionHeartbeat processes RegionInfo reports from client. func (c *RaftCluster) HandleRegionHeartbeat(region *core.RegionInfo) error { if err := c.cachedCluster.handleRegionHeartbeat(region); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } // If the region peer count is 0, then we should not handle this. @@ -44,18 +45,18 @@ func (c *RaftCluster) handleAskSplit(request *pdpb.AskSplitRequest) (*pdpb.AskSp reqRegion := request.GetRegion() err := c.validRequestRegion(reqRegion) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } newRegionID, err := c.s.idAlloc.Alloc() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } peerIDs := make([]uint64, len(request.Region.Peers)) for i := 0; i < len(peerIDs); i++ { if peerIDs[i], err = c.s.idAlloc.Alloc(); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } } @@ -92,7 +93,7 @@ func (c *RaftCluster) handleAskBatchSplit(request *pdpb.AskBatchSplitRequest) (* splitCount := request.GetSplitCount() err := c.validRequestRegion(reqRegion) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } splitIDs := make([]*pdpb.SplitID, 0, splitCount) @@ -101,13 +102,13 @@ func (c *RaftCluster) handleAskBatchSplit(request *pdpb.AskBatchSplitRequest) (* for i := 0; i < int(splitCount); i++ { newRegionID, err := c.s.idAlloc.Alloc() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } peerIDs := make([]uint64, len(request.Region.Peers)) for i := 0; i < len(peerIDs); i++ { if peerIDs[i], err = c.s.idAlloc.Alloc(); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } } @@ -163,8 +164,8 @@ func (c *RaftCluster) handleReportSplit(request *pdpb.ReportSplitRequest) (*pdpb err := c.checkSplitRegion(left, right) if err != nil { - log.Warnf("report split region is invalid - %v, %v", request, errors.ErrorStack(err)) - return nil, errors.Trace(err) + log.Warnf("report split region is invalid - %v, %v", request, fmt.Sprintf("%+v", err)) + return nil, errors.WithStack(err) } // Build origin region by using left and right. @@ -180,8 +181,8 @@ func (c *RaftCluster) handleBatchReportSplit(request *pdpb.ReportBatchSplitReque err := c.checkSplitRegions(regions) if err != nil { - log.Warnf("report batch split region is invalid - %v, %v", request, errors.ErrorStack(err)) - return nil, errors.Trace(err) + log.Warnf("report batch split region is invalid - %v, %v", request, fmt.Sprintf("%+v", err)) + return nil, errors.WithStack(err) } last := len(regions) - 1 originRegion := proto.Clone(regions[last]).(*metapb.Region) diff --git a/server/config.go b/server/config.go index 12b2eb87425..86036a5910f 100644 --- a/server/config.go +++ b/server/config.go @@ -27,11 +27,11 @@ import ( "github.com/coreos/etcd/embed" "github.com/coreos/etcd/pkg/transport" "github.com/coreos/go-semver/semver" - "github.com/juju/errors" "github.com/pingcap/pd/pkg/logutil" "github.com/pingcap/pd/pkg/metricutil" "github.com/pingcap/pd/pkg/typeutil" "github.com/pingcap/pd/server/namespace" + "github.com/pkg/errors" ) // Config is the pd server configuration. @@ -224,7 +224,7 @@ func (c *Config) Parse(arguments []string) error { // Parse first to get config file. err := c.FlagSet.Parse(arguments) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } // Load config file if specified. @@ -232,7 +232,7 @@ func (c *Config) Parse(arguments []string) error { if c.configFile != "" { meta, err = c.configFromFile(c.configFile) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } // Backward compatibility for toml config @@ -251,7 +251,7 @@ func (c *Config) Parse(arguments []string) error { // Parse again to replace with command line options. err = c.FlagSet.Parse(arguments) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if len(c.FlagSet.Args()) != 0 { @@ -259,7 +259,7 @@ func (c *Config) Parse(arguments []string) error { } err = c.adjust(meta) - return errors.Trace(err) + return errors.WithStack(err) } func (c *Config) validate() error { @@ -268,15 +268,15 @@ func (c *Config) validate() error { } dataDir, err := filepath.Abs(c.DataDir) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } logFile, err := filepath.Abs(c.Log.File.Filename) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } rel, err := filepath.Rel(dataDir, filepath.Dir(logFile)) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if !strings.HasPrefix(rel, "..") { return errors.New("log directory shouldn't be the subdirectory of data directory") @@ -290,7 +290,7 @@ func (c *Config) adjust(meta *toml.MetaData) error { adjustString(&c.DataDir, fmt.Sprintf("default.%s", c.Name)) if err := c.validate(); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } adjustString(&c.ClientUrls, defaultClientUrls) @@ -336,10 +336,10 @@ func (c *Config) adjust(meta *toml.MetaData) error { adjustString(&c.Metric.PushJob, c.Name) if err := c.Schedule.adjust(); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if err := c.Replication.adjust(); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } adjustDuration(&c.heartbeatStreamBindInterval, defaultHeartbeatStreamRebindInterval) @@ -370,7 +370,7 @@ func (c *Config) String() string { // configFromFile loads config from file. func (c *Config) configFromFile(path string) (*toml.MetaData, error) { meta, err := toml.DecodeFile(path, c) - return &meta, errors.Trace(err) + return &meta, errors.WithStack(err) } // ScheduleConfig is the schedule configuration. @@ -628,7 +628,7 @@ func (s SecurityConfig) ToTLSConfig() (*tls.Config, error) { } tlsConfig, err := tlsInfo.ClientConfig() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return tlsConfig, nil } @@ -660,7 +660,7 @@ func ParseUrls(s string) ([]url.URL, error) { for _, item := range items { u, err := url.Parse(item) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } urls = append(urls, *u) @@ -698,22 +698,22 @@ func (c *Config) genEmbedEtcdConfig() (*embed.Config, error) { cfg.LPUrls, err = ParseUrls(c.PeerUrls) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cfg.APUrls, err = ParseUrls(c.AdvertisePeerUrls) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cfg.LCUrls, err = ParseUrls(c.ClientUrls) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cfg.ACUrls, err = ParseUrls(c.AdvertiseClientUrls) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return cfg, nil diff --git a/server/coordinator.go b/server/coordinator.go index fba4a133c00..1cab4b4bd84 100644 --- a/server/coordinator.go +++ b/server/coordinator.go @@ -20,7 +20,6 @@ import ( "sync" "time" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/eraftpb" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" @@ -28,6 +27,7 @@ import ( "github.com/pingcap/pd/server/core" "github.com/pingcap/pd/server/namespace" "github.com/pingcap/pd/server/schedule" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -386,7 +386,7 @@ func (c *coordinator) addScheduler(scheduler schedule.Scheduler, args ...string) s := newScheduleController(c, scheduler) if err := s.Prepare(c.cluster); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } c.wg.Add(1) @@ -410,7 +410,7 @@ func (c *coordinator) removeScheduler(name string) error { delete(c.schedulers, name) if err := c.cluster.opt.RemoveSchedulerCfg(name); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } return nil diff --git a/server/coordinator_test.go b/server/coordinator_test.go index 315f36633c9..7757b60eaff 100644 --- a/server/coordinator_test.go +++ b/server/coordinator_test.go @@ -18,7 +18,6 @@ import ( "math/rand" "time" - "github.com/juju/errors" . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/eraftpb" "github.com/pingcap/kvproto/pkg/metapb" @@ -28,6 +27,7 @@ import ( "github.com/pingcap/pd/server/namespace" "github.com/pingcap/pd/server/schedule" "github.com/pingcap/pd/server/schedulers" + "github.com/pkg/errors" ) func newTestOperator(regionID uint64, regionEpoch *metapb.RegionEpoch, kind schedule.OperatorKind) *schedule.Operator { diff --git a/server/core/kv.go b/server/core/kv.go index 33c0d5ffd18..1b35c6646f1 100644 --- a/server/core/kv.go +++ b/server/core/kv.go @@ -21,8 +21,8 @@ import ( "strconv" "github.com/gogo/protobuf/proto" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" + "github.com/pkg/errors" ) const ( @@ -109,7 +109,7 @@ func (kv *KV) DeleteRegion(region *metapb.Region) error { func (kv *KV) SaveConfig(cfg interface{}) error { value, err := json.Marshal(cfg) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } return kv.Save(configPath, string(value)) } @@ -118,14 +118,14 @@ func (kv *KV) SaveConfig(cfg interface{}) error { func (kv *KV) LoadConfig(cfg interface{}) (bool, error) { value, err := kv.Load(configPath) if err != nil { - return false, errors.Trace(err) + return false, errors.WithStack(err) } if value == "" { return false, nil } err = json.Unmarshal([]byte(value), cfg) if err != nil { - return false, errors.Trace(err) + return false, errors.WithStack(err) } return true, nil } @@ -138,22 +138,22 @@ func (kv *KV) LoadStores(stores *StoresInfo) error { key := kv.storePath(nextID) res, err := kv.LoadRange(key, endKey, minKVRangeLimit) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } for _, s := range res { store := &metapb.Store{} if err := store.Unmarshal([]byte(s)); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } storeInfo := NewStoreInfo(store) leaderWeight, err := kv.loadFloatWithDefaultValue(kv.storeLeaderWeightPath(storeInfo.GetId()), 1.0) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } storeInfo.LeaderWeight = leaderWeight regionWeight, err := kv.loadFloatWithDefaultValue(kv.storeRegionWeightPath(storeInfo.GetId()), 1.0) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } storeInfo.RegionWeight = regionWeight @@ -170,11 +170,11 @@ func (kv *KV) LoadStores(stores *StoresInfo) error { func (kv *KV) SaveStoreWeight(storeID uint64, leader, region float64) error { leaderValue := strconv.FormatFloat(leader, 'f', -1, 64) if err := kv.Save(kv.storeLeaderWeightPath(storeID), leaderValue); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } regionValue := strconv.FormatFloat(region, 'f', -1, 64) if err := kv.Save(kv.storeRegionWeightPath(storeID), regionValue); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } return nil } @@ -182,14 +182,14 @@ func (kv *KV) SaveStoreWeight(storeID uint64, leader, region float64) error { func (kv *KV) loadFloatWithDefaultValue(path string, def float64) (float64, error) { res, err := kv.Load(path) if err != nil { - return 0, errors.Trace(err) + return 0, errors.WithStack(err) } if res == "" { return def, nil } val, err := strconv.ParseFloat(res, 64) if err != nil { - return 0, errors.Trace(err) + return 0, errors.WithStack(err) } return val, nil } @@ -211,20 +211,20 @@ func (kv *KV) LoadRegions(regions *RegionsInfo) error { if rangeLimit /= 2; rangeLimit >= minKVRangeLimit { continue } - return errors.Trace(err) + return errors.WithStack(err) } for _, s := range res { region := &metapb.Region{} if err := region.Unmarshal([]byte(s)); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } nextID = region.GetId() + 1 overlaps := regions.SetRegion(NewRegionInfo(region, nil)) for _, item := range overlaps { if err := kv.DeleteRegion(item); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } } } @@ -240,7 +240,7 @@ func (kv *KV) SaveGCSafePoint(safePoint uint64) error { key := path.Join(gcPath, "safe_point") value := strconv.FormatUint(safePoint, 16) if err := kv.Save(key, value); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } return nil } @@ -250,14 +250,14 @@ func (kv *KV) LoadGCSafePoint() (uint64, error) { key := path.Join(gcPath, "safe_point") value, err := kv.Load(key) if err != nil { - return 0, errors.Trace(err) + return 0, errors.WithStack(err) } if value == "" { return 0, nil } safePoint, err := strconv.ParseUint(value, 16, 64) if err != nil { - return 0, errors.Trace(err) + return 0, errors.WithStack(err) } return safePoint, nil } @@ -265,7 +265,7 @@ func (kv *KV) LoadGCSafePoint() (uint64, error) { func (kv *KV) loadProto(key string, msg proto.Message) (bool, error) { value, err := kv.Load(key) if err != nil { - return false, errors.Trace(err) + return false, errors.WithStack(err) } if value == "" { return false, nil @@ -276,7 +276,7 @@ func (kv *KV) loadProto(key string, msg proto.Message) (bool, error) { func (kv *KV) saveProto(key string, msg proto.Message) error { value, err := proto.Marshal(msg) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } return kv.Save(key, string(value)) } diff --git a/server/core/kv_test.go b/server/core/kv_test.go index c9c4e13df79..8e88120f1c3 100644 --- a/server/core/kv_test.go +++ b/server/core/kv_test.go @@ -17,9 +17,9 @@ import ( "fmt" "math" - "github.com/juju/errors" . "github.com/pingcap/check" "github.com/pingcap/kvproto/pkg/metapb" + "github.com/pkg/errors" ) var _ = Suite(&testKVSuite{}) diff --git a/server/etcd_kv.go b/server/etcd_kv.go index 2dcb72f37e7..4fb893661d3 100644 --- a/server/etcd_kv.go +++ b/server/etcd_kv.go @@ -19,7 +19,7 @@ import ( "time" "github.com/coreos/etcd/clientv3" - "github.com/juju/errors" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -51,7 +51,7 @@ func (kv *etcdKVBase) Load(key string) (string, error) { resp, err := kvGet(kv.server.client, key) if err != nil { - return "", errors.Trace(err) + return "", errors.WithStack(err) } if n := len(resp.Kvs); n == 0 { return "", nil @@ -69,7 +69,7 @@ func (kv *etcdKVBase) LoadRange(key, endKey string, limit int) ([]string, error) withLimit := clientv3.WithLimit(int64(limit)) resp, err := kvGet(kv.server.client, key, withRange, withLimit) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } res := make([]string, 0, len(resp.Kvs)) for _, item := range resp.Kvs { @@ -84,10 +84,10 @@ func (kv *etcdKVBase) Save(key, value string) error { resp, err := kv.server.leaderTxn().Then(clientv3.OpPut(key, value)).Commit() if err != nil { log.Errorf("save to etcd error: %v", err) - return errors.Trace(err) + return errors.WithStack(err) } if !resp.Succeeded { - return errors.Trace(errTxnFailed) + return errors.WithStack(errTxnFailed) } return nil } @@ -98,10 +98,10 @@ func (kv *etcdKVBase) Delete(key string) error { resp, err := kv.server.leaderTxn().Then(clientv3.OpDelete(key)).Commit() if err != nil { log.Errorf("delete from etcd error: %v", err) - return errors.Trace(err) + return errors.WithStack(err) } if !resp.Succeeded { - return errors.Trace(errTxnFailed) + return errors.WithStack(errTxnFailed) } return nil } @@ -119,5 +119,5 @@ func kvGet(c *clientv3.Client, key string, opts ...clientv3.OpOption) (*clientv3 log.Warnf("kv gets too slow: key %v cost %v err %v", key, cost, err) } - return resp, errors.Trace(err) + return resp, errors.WithStack(err) } diff --git a/server/grpc_service.go b/server/grpc_service.go index 894353f5684..b2e9a59368d 100644 --- a/server/grpc_service.go +++ b/server/grpc_service.go @@ -20,10 +20,10 @@ import ( "sync/atomic" "time" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/server/core" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" "golang.org/x/net/context" "google.golang.org/grpc/codes" @@ -71,10 +71,10 @@ func (s *Server) Tso(stream pdpb.PD_TsoServer) error { return nil } if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if err = s.validateRequest(request.GetHeader()); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } count := request.GetCount() ts, err := s.getRespTS(count) @@ -87,7 +87,7 @@ func (s *Server) Tso(stream pdpb.PD_TsoServer) error { Count: count, } if err := stream.Send(response); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } } } @@ -95,7 +95,7 @@ func (s *Server) Tso(stream pdpb.PD_TsoServer) error { // Bootstrap implements gRPC PDServer. func (s *Server) Bootstrap(ctx context.Context, request *pdpb.BootstrapRequest) (*pdpb.BootstrapResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -120,7 +120,7 @@ func (s *Server) Bootstrap(ctx context.Context, request *pdpb.BootstrapRequest) // IsBootstrapped implements gRPC PDServer. func (s *Server) IsBootstrapped(ctx context.Context, request *pdpb.IsBootstrappedRequest) (*pdpb.IsBootstrappedResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -133,7 +133,7 @@ func (s *Server) IsBootstrapped(ctx context.Context, request *pdpb.IsBootstrappe // AllocID implements gRPC PDServer. func (s *Server) AllocID(ctx context.Context, request *pdpb.AllocIDRequest) (*pdpb.AllocIDResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } // We can use an allocator for all types ID allocation. @@ -151,7 +151,7 @@ func (s *Server) AllocID(ctx context.Context, request *pdpb.AllocIDRequest) (*pd // GetStore implements gRPC PDServer. func (s *Server) GetStore(ctx context.Context, request *pdpb.GetStoreRequest) (*pdpb.GetStoreResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -188,7 +188,7 @@ func checkStore2(cluster *RaftCluster, storeID uint64) *pdpb.Error { // PutStore implements gRPC PDServer. func (s *Server) PutStore(ctx context.Context, request *pdpb.PutStoreRequest) (*pdpb.PutStoreResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -218,7 +218,7 @@ func (s *Server) PutStore(ctx context.Context, request *pdpb.PutStoreRequest) (* // GetAllStores implements gRPC PDServer. func (s *Server) GetAllStores(ctx context.Context, request *pdpb.GetAllStoresRequest) (*pdpb.GetAllStoresResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -235,7 +235,7 @@ func (s *Server) GetAllStores(ctx context.Context, request *pdpb.GetAllStoresReq // StoreHeartbeat implements gRPC PDServer. func (s *Server) StoreHeartbeat(ctx context.Context, request *pdpb.StoreHeartbeatRequest) (*pdpb.StoreHeartbeatResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } if request.GetStats() == nil { @@ -284,10 +284,10 @@ func (s *heartbeatServer) Send(m *pdpb.RegionHeartbeatResponse) error { if err != nil { atomic.StoreInt32(&s.closed, 1) } - return errors.Trace(err) + return errors.WithStack(err) case <-time.After(regionHeartbeatSendTimeout): atomic.StoreInt32(&s.closed, 1) - return errors.Trace(errSendRegionHeartbeatTimeout) + return errors.WithStack(errSendRegionHeartbeatTimeout) } } @@ -298,7 +298,7 @@ func (s *heartbeatServer) Recv() (*pdpb.RegionHeartbeatRequest, error) { req, err := s.stream.Recv() if err != nil { atomic.StoreInt32(&s.closed, 1) - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return req, nil } @@ -312,7 +312,7 @@ func (s *Server) RegionHeartbeat(stream pdpb.PD_RegionHeartbeatServer) error { Header: s.notBootstrappedHeader(), } err := server.Send(resp) - return errors.Trace(err) + return errors.WithStack(err) } var lastBind time.Time @@ -322,11 +322,11 @@ func (s *Server) RegionHeartbeat(stream pdpb.PD_RegionHeartbeatServer) error { return nil } if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if err = s.validateRequest(request.GetHeader()); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } storeID := request.GetLeader().GetStoreId() @@ -357,7 +357,7 @@ func (s *Server) RegionHeartbeat(stream pdpb.PD_RegionHeartbeatServer) error { err = cluster.HandleRegionHeartbeat(region) if err != nil { - msg := errors.Trace(err).Error() + msg := errors.WithStack(err).Error() hbStreams.sendErr(region, pdpb.ErrorType_UNKNOWN, msg, storeLabel) } @@ -368,7 +368,7 @@ func (s *Server) RegionHeartbeat(stream pdpb.PD_RegionHeartbeatServer) error { // GetRegion implements gRPC PDServer. func (s *Server) GetRegion(ctx context.Context, request *pdpb.GetRegionRequest) (*pdpb.GetRegionResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -386,7 +386,7 @@ func (s *Server) GetRegion(ctx context.Context, request *pdpb.GetRegionRequest) // GetPrevRegion implements gRPC PDServer func (s *Server) GetPrevRegion(ctx context.Context, request *pdpb.GetRegionRequest) (*pdpb.GetRegionResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -405,7 +405,7 @@ func (s *Server) GetPrevRegion(ctx context.Context, request *pdpb.GetRegionReque // GetRegionByID implements gRPC PDServer. func (s *Server) GetRegionByID(ctx context.Context, request *pdpb.GetRegionByIDRequest) (*pdpb.GetRegionResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -424,7 +424,7 @@ func (s *Server) GetRegionByID(ctx context.Context, request *pdpb.GetRegionByIDR // AskSplit implements gRPC PDServer. func (s *Server) AskSplit(ctx context.Context, request *pdpb.AskSplitRequest) (*pdpb.AskSplitResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -452,7 +452,7 @@ func (s *Server) AskSplit(ctx context.Context, request *pdpb.AskSplitRequest) (* // AskBatchSplit implements gRPC PDServer. func (s *Server) AskBatchSplit(ctx context.Context, request *pdpb.AskBatchSplitRequest) (*pdpb.AskBatchSplitResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -483,7 +483,7 @@ func (s *Server) AskBatchSplit(ctx context.Context, request *pdpb.AskBatchSplitR // ReportSplit implements gRPC PDServer. func (s *Server) ReportSplit(ctx context.Context, request *pdpb.ReportSplitRequest) (*pdpb.ReportSplitResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -503,7 +503,7 @@ func (s *Server) ReportSplit(ctx context.Context, request *pdpb.ReportSplitReque // ReportBatchSplit implements gRPC PDServer. func (s *Server) ReportBatchSplit(ctx context.Context, request *pdpb.ReportBatchSplitRequest) (*pdpb.ReportBatchSplitResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -524,7 +524,7 @@ func (s *Server) ReportBatchSplit(ctx context.Context, request *pdpb.ReportBatch // GetClusterConfig implements gRPC PDServer. func (s *Server) GetClusterConfig(ctx context.Context, request *pdpb.GetClusterConfigRequest) (*pdpb.GetClusterConfigResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -540,7 +540,7 @@ func (s *Server) GetClusterConfig(ctx context.Context, request *pdpb.GetClusterC // PutClusterConfig implements gRPC PDServer. func (s *Server) PutClusterConfig(ctx context.Context, request *pdpb.PutClusterConfigRequest) (*pdpb.PutClusterConfigResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -562,7 +562,7 @@ func (s *Server) PutClusterConfig(ctx context.Context, request *pdpb.PutClusterC // ScatterRegion implements gRPC PDServer. func (s *Server) ScatterRegion(ctx context.Context, request *pdpb.ScatterRegionRequest) (*pdpb.ScatterRegionResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -591,7 +591,7 @@ func (s *Server) ScatterRegion(ctx context.Context, request *pdpb.ScatterRegionR // GetGCSafePoint implements gRPC PDServer. func (s *Server) GetGCSafePoint(ctx context.Context, request *pdpb.GetGCSafePointRequest) (*pdpb.GetGCSafePointResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -601,7 +601,7 @@ func (s *Server) GetGCSafePoint(ctx context.Context, request *pdpb.GetGCSafePoin safePoint, err := s.kv.LoadGCSafePoint() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return &pdpb.GetGCSafePointResponse{ @@ -613,7 +613,7 @@ func (s *Server) GetGCSafePoint(ctx context.Context, request *pdpb.GetGCSafePoin // UpdateGCSafePoint implements gRPC PDServer. func (s *Server) UpdateGCSafePoint(ctx context.Context, request *pdpb.UpdateGCSafePointRequest) (*pdpb.UpdateGCSafePointResponse, error) { if err := s.validateRequest(request.GetHeader()); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } cluster := s.GetRaftCluster() @@ -623,7 +623,7 @@ func (s *Server) UpdateGCSafePoint(ctx context.Context, request *pdpb.UpdateGCSa oldSafePoint, err := s.kv.LoadGCSafePoint() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } newSafePoint := request.SafePoint @@ -631,7 +631,7 @@ func (s *Server) UpdateGCSafePoint(ctx context.Context, request *pdpb.UpdateGCSa // Only save the safe point if it's greater than the previous one if newSafePoint > oldSafePoint { if err := s.kv.SaveGCSafePoint(newSafePoint); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } log.Infof("updated gc safe point to %d", newSafePoint) } else if newSafePoint < oldSafePoint { diff --git a/server/handler.go b/server/handler.go index 26e08bbd606..04c49e488ad 100644 --- a/server/handler.go +++ b/server/handler.go @@ -19,11 +19,11 @@ import ( "strings" "time" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/server/core" "github.com/pingcap/pd/server/schedule" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -63,7 +63,7 @@ func newHandler(s *Server) *Handler { func (h *Handler) getCoordinator() (*coordinator, error) { cluster := h.s.GetRaftCluster() if cluster == nil { - return nil, errors.Trace(ErrNotBootstrapped) + return nil, errors.WithStack(ErrNotBootstrapped) } return cluster.coordinator, nil } @@ -72,7 +72,7 @@ func (h *Handler) getCoordinator() (*coordinator, error) { func (h *Handler) GetSchedulers() ([]string, error) { c, err := h.getCoordinator() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return c.getSchedulers(), nil } @@ -81,14 +81,14 @@ func (h *Handler) GetSchedulers() ([]string, error) { func (h *Handler) GetStores() ([]*core.StoreInfo, error) { cluster := h.s.GetRaftCluster() if cluster == nil { - return nil, errors.Trace(ErrNotBootstrapped) + return nil, errors.WithStack(ErrNotBootstrapped) } storeMetas := cluster.GetStores() stores := make([]*core.StoreInfo, 0, len(storeMetas)) for _, s := range storeMetas { store, err := cluster.GetStore(s.GetId()) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } stores = append(stores, store) } @@ -137,11 +137,11 @@ func (h *Handler) GetHotKeysReadStores() map[uint64]uint64 { func (h *Handler) AddScheduler(name string, args ...string) error { c, err := h.getCoordinator() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } s, err := schedule.CreateScheduler(name, c.limiter, args...) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } log.Infof("create scheduler %s", s.GetName()) if err = c.addScheduler(s, args...); err != nil { @@ -149,21 +149,21 @@ func (h *Handler) AddScheduler(name string, args ...string) error { } else if err = h.opt.persist(c.cluster.kv); err != nil { log.Errorf("can not persist scheduler config: %v", err) } - return errors.Trace(err) + return errors.WithStack(err) } // RemoveScheduler removes a scheduler by name. func (h *Handler) RemoveScheduler(name string) error { c, err := h.getCoordinator() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if err = c.removeScheduler(name); err != nil { log.Errorf("can not remove scheduler %v: %v", name, err) } else if err = h.opt.persist(c.cluster.kv); err != nil { log.Errorf("can not persist scheduler config: %v", err) } - return errors.Trace(err) + return errors.WithStack(err) } // AddBalanceLeaderScheduler adds a balance-leader-scheduler. @@ -225,7 +225,7 @@ func (h *Handler) AddRandomMergeScheduler() error { func (h *Handler) GetOperator(regionID uint64) (*schedule.Operator, error) { c, err := h.getCoordinator() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } op := c.getOperator(regionID) @@ -240,7 +240,7 @@ func (h *Handler) GetOperator(regionID uint64) (*schedule.Operator, error) { func (h *Handler) RemoveOperator(regionID uint64) error { c, err := h.getCoordinator() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } op := c.getOperator(regionID) @@ -256,7 +256,7 @@ func (h *Handler) RemoveOperator(regionID uint64) error { func (h *Handler) GetOperators() ([]*schedule.Operator, error) { c, err := h.getCoordinator() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return c.getOperators(), nil } @@ -280,7 +280,7 @@ func (h *Handler) GetRegionOperators() ([]*schedule.Operator, error) { func (h *Handler) GetOperatorsOfKind(mask schedule.OperatorKind) ([]*schedule.Operator, error) { ops, err := h.GetOperators() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } var results []*schedule.Operator for _, op := range ops { @@ -295,7 +295,7 @@ func (h *Handler) GetOperatorsOfKind(mask schedule.OperatorKind) ([]*schedule.Op func (h *Handler) GetHistory(start time.Time) ([]schedule.OperatorHistory, error) { c, err := h.getCoordinator() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return c.getHistory(start), nil } @@ -306,7 +306,7 @@ var errAddOperator = errors.New("failed to add operator, maybe already have one" func (h *Handler) AddTransferLeaderOperator(regionID uint64, storeID uint64) error { c, err := h.getCoordinator() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } region := c.cluster.GetRegion(regionID) @@ -321,7 +321,7 @@ func (h *Handler) AddTransferLeaderOperator(regionID uint64, storeID uint64) err step := schedule.TransferLeader{FromStore: region.Leader.GetStoreId(), ToStore: newLeader.GetStoreId()} op := schedule.NewOperator("adminTransferLeader", regionID, region.GetRegionEpoch(), schedule.OpAdmin|schedule.OpLeader, step) if ok := c.addOperator(op); !ok { - return errors.Trace(errAddOperator) + return errors.WithStack(errAddOperator) } return nil } @@ -330,7 +330,7 @@ func (h *Handler) AddTransferLeaderOperator(regionID uint64, storeID uint64) err func (h *Handler) AddTransferRegionOperator(regionID uint64, storeIDs map[uint64]struct{}) error { c, err := h.getCoordinator() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } region := c.cluster.GetRegion(regionID) @@ -350,7 +350,7 @@ func (h *Handler) AddTransferRegionOperator(regionID uint64, storeIDs map[uint64 } peer, err := c.cluster.AllocPeer(id) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if c.cluster.IsRaftLearnerEnabled() { steps = append(steps, @@ -372,7 +372,7 @@ func (h *Handler) AddTransferRegionOperator(regionID uint64, storeIDs map[uint64 op := schedule.NewOperator("adminMoveRegion", regionID, region.GetRegionEpoch(), schedule.OpAdmin|schedule.OpRegion, steps...) if ok := c.addOperator(op); !ok { - return errors.Trace(errAddOperator) + return errors.WithStack(errAddOperator) } return nil } @@ -381,7 +381,7 @@ func (h *Handler) AddTransferRegionOperator(regionID uint64, storeIDs map[uint64 func (h *Handler) AddTransferPeerOperator(regionID uint64, fromStoreID, toStoreID uint64) error { c, err := h.getCoordinator() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } region := c.cluster.GetRegion(regionID) @@ -399,12 +399,12 @@ func (h *Handler) AddTransferPeerOperator(regionID uint64, fromStoreID, toStoreI } newPeer, err := c.cluster.AllocPeer(toStoreID) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } op := schedule.CreateMovePeerOperator("adminMovePeer", c.cluster, region, schedule.OpAdmin, fromStoreID, toStoreID, newPeer.GetId()) if ok := c.addOperator(op); !ok { - return errors.Trace(errAddOperator) + return errors.WithStack(errAddOperator) } return nil } @@ -413,7 +413,7 @@ func (h *Handler) AddTransferPeerOperator(regionID uint64, fromStoreID, toStoreI func (h *Handler) AddAddPeerOperator(regionID uint64, toStoreID uint64) error { c, err := h.getCoordinator() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } region := c.cluster.GetRegion(regionID) @@ -430,7 +430,7 @@ func (h *Handler) AddAddPeerOperator(regionID uint64, toStoreID uint64) error { } newPeer, err := c.cluster.AllocPeer(toStoreID) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } var steps []schedule.OperatorStep @@ -446,7 +446,7 @@ func (h *Handler) AddAddPeerOperator(regionID uint64, toStoreID uint64) error { } op := schedule.NewOperator("adminAddPeer", regionID, region.GetRegionEpoch(), schedule.OpAdmin|schedule.OpRegion, steps...) if ok := c.addOperator(op); !ok { - return errors.Trace(errAddOperator) + return errors.WithStack(errAddOperator) } return nil } @@ -455,7 +455,7 @@ func (h *Handler) AddAddPeerOperator(regionID uint64, toStoreID uint64) error { func (h *Handler) AddRemovePeerOperator(regionID uint64, fromStoreID uint64) error { c, err := h.getCoordinator() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } region := c.cluster.GetRegion(regionID) @@ -469,7 +469,7 @@ func (h *Handler) AddRemovePeerOperator(regionID uint64, fromStoreID uint64) err op := schedule.CreateRemovePeerOperator("adminRemovePeer", c.cluster, schedule.OpAdmin, region, fromStoreID) if ok := c.addOperator(op); !ok { - return errors.Trace(errAddOperator) + return errors.WithStack(errAddOperator) } return nil } @@ -478,7 +478,7 @@ func (h *Handler) AddRemovePeerOperator(regionID uint64, fromStoreID uint64) err func (h *Handler) AddMergeRegionOperator(regionID uint64, targetID uint64) error { c, err := h.getCoordinator() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } region := c.cluster.GetRegion(regionID) @@ -509,10 +509,10 @@ func (h *Handler) AddMergeRegionOperator(regionID uint64, targetID uint64) error op1, op2, err := schedule.CreateMergeRegionOperator("adminMergeRegion", c.cluster, region, target, schedule.OpAdmin) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if ok := c.addOperator(op1, op2); !ok { - return errors.Trace(ErrAddOperator) + return errors.WithStack(ErrAddOperator) } return nil } @@ -521,7 +521,7 @@ func (h *Handler) AddMergeRegionOperator(regionID uint64, targetID uint64) error func (h *Handler) AddSplitRegionOperator(regionID uint64, policy string) error { c, err := h.getCoordinator() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } region := c.cluster.GetRegion(regionID) @@ -536,7 +536,7 @@ func (h *Handler) AddSplitRegionOperator(regionID uint64, policy string) error { } op := schedule.NewOperator("adminSplitRegion", regionID, region.GetRegionEpoch(), schedule.OpAdmin, step) if ok := c.addOperator(op); !ok { - return errors.Trace(errAddOperator) + return errors.WithStack(errAddOperator) } return nil } @@ -545,7 +545,7 @@ func (h *Handler) AddSplitRegionOperator(regionID uint64, policy string) error { func (h *Handler) AddScatterRegionOperator(regionID uint64) error { c, err := h.getCoordinator() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } region := c.cluster.GetRegion(regionID) @@ -558,7 +558,7 @@ func (h *Handler) AddScatterRegionOperator(regionID uint64) error { return nil } if ok := c.addOperator(op); !ok { - return errors.Trace(errAddOperator) + return errors.WithStack(errAddOperator) } return nil } diff --git a/server/id.go b/server/id.go index 10e93a7db6e..a5bed9b2f94 100644 --- a/server/id.go +++ b/server/id.go @@ -17,7 +17,7 @@ import ( "sync" "github.com/coreos/etcd/clientv3" - "github.com/juju/errors" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -40,7 +40,7 @@ func (alloc *idAllocator) Alloc() (uint64, error) { if alloc.base == alloc.end { end, err := alloc.generate() if err != nil { - return 0, errors.Trace(err) + return 0, errors.WithStack(err) } alloc.end = end @@ -56,7 +56,7 @@ func (alloc *idAllocator) generate() (uint64, error) { key := alloc.s.getAllocIDPath() value, err := getValue(alloc.s.client, key) if err != nil { - return 0, errors.Trace(err) + return 0, errors.WithStack(err) } var ( @@ -71,7 +71,7 @@ func (alloc *idAllocator) generate() (uint64, error) { // update the key end, err = bytesToUint64(value) if err != nil { - return 0, errors.Trace(err) + return 0, errors.WithStack(err) } cmp = clientv3.Compare(clientv3.Value(key), "=", string(value)) @@ -81,7 +81,7 @@ func (alloc *idAllocator) generate() (uint64, error) { value = uint64ToBytes(end) resp, err := alloc.s.leaderTxn(cmp).Then(clientv3.OpPut(key, string(value))).Commit() if err != nil { - return 0, errors.Trace(err) + return 0, errors.WithStack(err) } if !resp.Succeeded { return 0, errors.New("generate id failed, we may not leader") diff --git a/server/join.go b/server/join.go index 1844dfc90d2..1f9dfbe53e1 100644 --- a/server/join.go +++ b/server/join.go @@ -21,8 +21,8 @@ import ( "github.com/coreos/etcd/clientv3" "github.com/coreos/etcd/embed" - "github.com/juju/errors" "github.com/pingcap/pd/pkg/etcdutil" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -84,7 +84,7 @@ func PrepareJoinCluster(cfg *Config) error { // Below are cases without data directory. tlsConfig, err := cfg.Security.ToTLSConfig() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } client, err := clientv3.New(clientv3.Config{ Endpoints: strings.Split(cfg.Join, ","), @@ -92,13 +92,13 @@ func PrepareJoinCluster(cfg *Config) error { TLS: tlsConfig, }) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } defer client.Close() listResp, err := etcdutil.ListEtcdMembers(client) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } existed := false @@ -117,12 +117,12 @@ func PrepareJoinCluster(cfg *Config) error { // - A deleted PD joins to previous cluster. addResp, err := etcdutil.AddEtcdMember(client, []string{cfg.AdvertisePeerUrls}) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } listResp, err = etcdutil.ListEtcdMembers(client) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } pds := []string{} diff --git a/server/leader.go b/server/leader.go index 18f968fb3aa..20aa0370072 100644 --- a/server/leader.go +++ b/server/leader.go @@ -15,6 +15,7 @@ package server import ( "context" + "fmt" "math/rand" "path" "strings" @@ -22,10 +23,10 @@ import ( "github.com/coreos/etcd/clientv3" "github.com/coreos/etcd/mvcc/mvccpb" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/pkg/etcdutil" "github.com/pingcap/pd/pkg/logutil" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -112,7 +113,7 @@ func (s *Server) leaderLoop() { } if err = s.campaignLeader(); err != nil { - log.Errorf("campaign leader err %s", errors.ErrorStack(err)) + log.Errorf("campaign leader err %s", fmt.Sprintf("%+v", err)) } } } @@ -160,7 +161,7 @@ func getLeader(c *clientv3.Client, leaderPath string) (*pdpb.Member, error) { leader := &pdpb.Member{} ok, err := getProtoMsg(c, leaderPath, leader) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } if !ok { return nil, nil @@ -211,7 +212,7 @@ func (s *Server) campaignLeader() error { } if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } leaderKey := s.getLeaderPath() @@ -221,7 +222,7 @@ func (s *Server) campaignLeader() error { Then(clientv3.OpPut(leaderKey, s.memberValue, clientv3.WithLease(clientv3.LeaseID(leaseResp.ID)))). Commit() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if !resp.Succeeded { return errors.New("campaign leader failed, other server may campaign ok") @@ -233,24 +234,24 @@ func (s *Server) campaignLeader() error { ch, err := lessor.KeepAlive(ctx, clientv3.LeaseID(leaseResp.ID)) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } log.Debugf("campaign leader ok %s", s.Name()) err = s.scheduleOpt.reload(s.kv) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } // Try to create raft cluster. err = s.createRaftCluster() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } defer s.stopRaftCluster() log.Debug("sync timestamp for tso") if err = s.syncTimestamp(); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } defer s.ts.Store(&atomicObject{ physical: zeroTime, @@ -275,7 +276,7 @@ func (s *Server) campaignLeader() error { } case <-tsTicker.C: if err = s.updateTimestamp(); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } etcdLeader := s.GetEtcdLeader() if etcdLeader != s.ID() { @@ -330,7 +331,7 @@ func (s *Server) ResignLeader(nextLeader string) error { var leaderIDs []uint64 res, err := etcdutil.ListEtcdMembers(s.client) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } for _, member := range res.Members { if (nextLeader == "" && member.ID != s.id) || (nextLeader != "" && member.Name == nextLeader) { @@ -343,7 +344,7 @@ func (s *Server) ResignLeader(nextLeader string) error { nextLeaderID := leaderIDs[rand.Intn(len(leaderIDs))] log.Infof("%s ready to resign leader, next leader: %v", s.Name(), nextLeaderID) err = s.etcd.Server.MoveLeader(s.serverLoopCtx, s.ID(), nextLeaderID) - return errors.Trace(err) + return errors.WithStack(err) } func (s *Server) deleteLeaderKey() error { @@ -351,7 +352,7 @@ func (s *Server) deleteLeaderKey() error { leaderKey := s.getLeaderPath() resp, err := s.leaderTxn().Then(clientv3.OpDelete(leaderKey)).Commit() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if !resp.Succeeded { return errors.New("resign leader failed, we are not leader already") diff --git a/server/namespace/classifier.go b/server/namespace/classifier.go index 988c140fe3a..fb5cb99fa3d 100644 --- a/server/namespace/classifier.go +++ b/server/namespace/classifier.go @@ -16,8 +16,8 @@ package namespace import ( "fmt" - "github.com/juju/errors" "github.com/pingcap/pd/server/core" + "github.com/pkg/errors" ) // DefaultNamespace is the namespace all the store and region belong to by diff --git a/server/option.go b/server/option.go index 6c11fa7a90e..1068134ba4a 100644 --- a/server/option.go +++ b/server/option.go @@ -19,10 +19,10 @@ import ( "time" "github.com/coreos/go-semver/semver" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/pd/server/core" "github.com/pingcap/pd/server/schedule" + "github.com/pkg/errors" ) // scheduleOption is a wrapper to access the configuration safely. @@ -205,7 +205,7 @@ func (o *scheduleOption) RemoveSchedulerCfg(name string) error { // To create a temporary scheduler is just used to get scheduler's name tmp, err := schedule.CreateScheduler(schedulerCfg.Type, schedule.NewLimiter(), schedulerCfg.Args...) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if tmp.GetName() == name { if IsDefaultScheduler(tmp.GetType()) { @@ -273,7 +273,7 @@ func (o *scheduleOption) persist(kv *core.KV) error { ClusterVersion: o.loadClusterVersion(), } err := kv.SaveConfig(cfg) - return errors.Trace(err) + return errors.WithStack(err) } func (o *scheduleOption) reload(kv *core.KV) error { @@ -290,7 +290,7 @@ func (o *scheduleOption) reload(kv *core.KV) error { } isExist, err := kv.LoadConfig(cfg) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } o.adjustScheduleCfg(cfg) if isExist { diff --git a/server/schedule/basic_cluster.go b/server/schedule/basic_cluster.go index b7c45791d6c..c910dbdc640 100644 --- a/server/schedule/basic_cluster.go +++ b/server/schedule/basic_cluster.go @@ -14,8 +14,8 @@ package schedule import ( - "github.com/juju/errors" "github.com/pingcap/pd/server/core" + "github.com/pkg/errors" ) var ( @@ -161,7 +161,7 @@ func (bc *BasicCluster) GetAdjacentRegions(region *core.RegionInfo) (*core.Regio // BlockStore stops balancer from selecting the store. func (bc *BasicCluster) BlockStore(storeID uint64) error { - return errors.Trace(bc.Stores.BlockStore(storeID)) + return errors.WithStack(bc.Stores.BlockStore(storeID)) } // UnblockStore allows balancer to select the store. diff --git a/server/schedule/mockcluster.go b/server/schedule/mockcluster.go index c7447991857..e9d4dda7057 100644 --- a/server/schedule/mockcluster.go +++ b/server/schedule/mockcluster.go @@ -17,11 +17,11 @@ import ( "fmt" "time" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/server/core" "github.com/pingcap/pd/server/namespace" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -77,7 +77,7 @@ func (mc *MockCluster) AllocPeer(storeID uint64) (*metapb.Peer, error) { peerID, err := mc.allocID() if err != nil { log.Errorf("failed to alloc peer: %v", err) - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } peer := &metapb.Peer{ Id: peerID, diff --git a/server/schedule/operator.go b/server/schedule/operator.go index aaaee5e7b95..171df9f237b 100644 --- a/server/schedule/operator.go +++ b/server/schedule/operator.go @@ -20,9 +20,9 @@ import ( "sync/atomic" "time" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" "github.com/pingcap/pd/server/core" @@ -465,7 +465,7 @@ func removePeerSteps(cluster Cluster, region *core.RegionInfo, storeID uint64) ( func CreateMergeRegionOperator(desc string, cluster Cluster, source *core.RegionInfo, target *core.RegionInfo, kind OperatorKind) (*Operator, *Operator, error) { steps, kinds, err := matchPeerSteps(cluster, source, target) if err != nil { - return nil, nil, errors.Trace(err) + return nil, nil, errors.WithStack(err) } steps = append(steps, MergeRegion{ @@ -505,7 +505,7 @@ func matchPeerSteps(cluster Cluster, source *core.RegionInfo, target *core.Regio peer, err := cluster.AllocPeer(id) if err != nil { log.Debugf("peer alloc failed: %v", err) - return nil, kind, errors.Trace(err) + return nil, kind, errors.WithStack(err) } if cluster.IsRaftLearnerEnabled() { steps = append(steps, diff --git a/server/schedule/operator_kind.go b/server/schedule/operator_kind.go index eff213d0f4c..010717a2cf2 100644 --- a/server/schedule/operator_kind.go +++ b/server/schedule/operator_kind.go @@ -16,7 +16,7 @@ package schedule import ( "strings" - "github.com/juju/errors" + "github.com/pkg/errors" ) // OperatorKind is a bit field to identify operator types. diff --git a/server/schedule/scheduler.go b/server/schedule/scheduler.go index c84fba7d126..24bc34ff47a 100644 --- a/server/schedule/scheduler.go +++ b/server/schedule/scheduler.go @@ -17,9 +17,9 @@ import ( "sync" "time" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/pd/server/core" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) diff --git a/server/schedulers/adjacent_region.go b/server/schedulers/adjacent_region.go index 1c76bdc2a95..283e48b2f0e 100644 --- a/server/schedulers/adjacent_region.go +++ b/server/schedulers/adjacent_region.go @@ -18,9 +18,9 @@ import ( "strconv" "time" - "github.com/juju/errors" "github.com/pingcap/pd/server/core" "github.com/pingcap/pd/server/schedule" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -37,11 +37,11 @@ func init() { if len(args) == 2 { leaderLimit, err := strconv.ParseUint(args[0], 10, 64) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } peerLimit, err := strconv.ParseUint(args[1], 10, 64) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return newBalanceAdjacentRegionScheduler(limiter, leaderLimit, peerLimit), nil } diff --git a/server/schedulers/evict_leader.go b/server/schedulers/evict_leader.go index 2f3bc19a8dd..0f9260e73f6 100644 --- a/server/schedulers/evict_leader.go +++ b/server/schedulers/evict_leader.go @@ -17,9 +17,9 @@ import ( "fmt" "strconv" - "github.com/juju/errors" "github.com/pingcap/pd/server/core" "github.com/pingcap/pd/server/schedule" + "github.com/pkg/errors" ) func init() { @@ -29,7 +29,7 @@ func init() { } id, err := strconv.ParseUint(args[0], 10, 64) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return newEvictLeaderScheduler(limiter, id), nil }) @@ -64,7 +64,7 @@ func (s *evictLeaderScheduler) GetType() string { } func (s *evictLeaderScheduler) Prepare(cluster schedule.Cluster) error { - return errors.Trace(cluster.BlockStore(s.storeID)) + return errors.WithStack(cluster.BlockStore(s.storeID)) } func (s *evictLeaderScheduler) Cleanup(cluster schedule.Cluster) { diff --git a/server/schedulers/grant_leader.go b/server/schedulers/grant_leader.go index ddc6f8a3ad7..c49b6559164 100644 --- a/server/schedulers/grant_leader.go +++ b/server/schedulers/grant_leader.go @@ -17,9 +17,9 @@ import ( "fmt" "strconv" - "github.com/juju/errors" "github.com/pingcap/pd/server/core" "github.com/pingcap/pd/server/schedule" + "github.com/pkg/errors" ) func init() { @@ -29,7 +29,7 @@ func init() { } id, err := strconv.ParseUint(args[0], 10, 64) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return newGrantLeaderScheduler(limiter, id), nil }) @@ -61,7 +61,7 @@ func (s *grantLeaderScheduler) GetType() string { return "grant-leader" } func (s *grantLeaderScheduler) Prepare(cluster schedule.Cluster) error { - return errors.Trace(cluster.BlockStore(s.storeID)) + return errors.WithStack(cluster.BlockStore(s.storeID)) } func (s *grantLeaderScheduler) Cleanup(cluster schedule.Cluster) { diff --git a/server/schedulers/scatter_range.go b/server/schedulers/scatter_range.go index e5cb39e27ad..0288789317c 100644 --- a/server/schedulers/scatter_range.go +++ b/server/schedulers/scatter_range.go @@ -18,8 +18,8 @@ import ( "net/url" "strings" - "github.com/juju/errors" "github.com/pingcap/pd/server/schedule" + "github.com/pkg/errors" ) func init() { diff --git a/server/server.go b/server/server.go index 4bd3d9dfb29..ec60c2c59a6 100644 --- a/server/server.go +++ b/server/server.go @@ -29,13 +29,13 @@ import ( "github.com/coreos/etcd/embed" "github.com/coreos/etcd/pkg/types" "github.com/coreos/go-semver/semver" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/pkg/etcdutil" "github.com/pingcap/pd/pkg/logutil" "github.com/pingcap/pd/server/core" "github.com/pingcap/pd/server/namespace" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" "google.golang.org/grpc" ) @@ -112,7 +112,7 @@ func CreateServer(cfg *Config, apiRegister func(*Server) http.Handler) (*Server, // Adjust etcd config. etcdCfg, err := s.cfg.genEmbedEtcdConfig() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } if apiRegister != nil { etcdCfg.UserHandlers = map[string]http.Handler{ @@ -135,20 +135,20 @@ func (s *Server) startEtcd(ctx context.Context) error { log.Info("start embed etcd") etcd, err := embed.StartEtcd(s.etcdCfg) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } // Check cluster ID urlmap, err := types.NewURLsMap(s.cfg.InitialCluster) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } tlsConfig, err := s.cfg.Security.ToTLSConfig() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if err = etcdutil.CheckClusterID(etcd.Server.Cluster().ID(), urlmap, tlsConfig); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } select { @@ -167,7 +167,7 @@ func (s *Server) startEtcd(ctx context.Context) error { TLS: tlsConfig, }) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } etcdServerID := uint64(etcd.Server.ID()) @@ -175,7 +175,7 @@ func (s *Server) startEtcd(ctx context.Context) error { // update advertise peer urls. etcdMembers, err := etcdutil.ListEtcdMembers(client) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } for _, m := range etcdMembers.Members { if etcdServerID == m.ID { @@ -196,7 +196,7 @@ func (s *Server) startEtcd(ctx context.Context) error { func (s *Server) startServer() error { var err error if err = s.initClusterID(); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } log.Infof("init cluster id %v", s.clusterID) // It may lose accuracy if use float64 to store uint64. So we store the @@ -212,7 +212,7 @@ func (s *Server) startServer() error { s.cluster = newRaftCluster(s, s.clusterID) s.hbStreams = newHeartbeatStreams(s.clusterID) if s.classifier, err = namespace.CreateClassifier(s.cfg.NamespaceClassifier, s.kv, s.idAlloc); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } // Server has started. @@ -224,16 +224,16 @@ func (s *Server) initClusterID() error { // Get any cluster key to parse the cluster ID. resp, err := kvGet(s.client, pdClusterIDPath) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } // If no key exist, generate a random cluster ID. if len(resp.Kvs) == 0 { s.clusterID, err = initOrGetClusterID(s.client, pdClusterIDPath) - return errors.Trace(err) + return errors.WithStack(err) } s.clusterID, err = bytesToUint64(resp.Kvs[0].Value) - return errors.Trace(err) + return errors.WithStack(err) } // Close closes the server. @@ -279,11 +279,11 @@ func (s *Server) Run(ctx context.Context) error { }) if err := s.startEtcd(ctx); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if err := s.startServer(); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } s.startServerLoop() @@ -333,7 +333,7 @@ func (s *Server) bootstrapCluster(req *pdpb.BootstrapRequest) (*pdpb.BootstrapRe log.Infof("try to bootstrap raft cluster %d with %v", clusterID, req) if err := checkBootstrapRequest(clusterID, req); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } clusterMeta := metapb.Cluster{ @@ -344,7 +344,7 @@ func (s *Server) bootstrapCluster(req *pdpb.BootstrapRequest) (*pdpb.BootstrapRe // Set cluster meta clusterValue, err := clusterMeta.Marshal() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } clusterRootPath := s.getClusterRootPath() @@ -363,13 +363,13 @@ func (s *Server) bootstrapCluster(req *pdpb.BootstrapRequest) (*pdpb.BootstrapRe storePath := makeStoreKey(clusterRootPath, storeMeta.GetId()) storeValue, err := storeMeta.Marshal() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } ops = append(ops, clientv3.OpPut(storePath, string(storeValue))) regionValue, err := req.GetRegion().Marshal() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } // Set region meta with region id. @@ -380,7 +380,7 @@ func (s *Server) bootstrapCluster(req *pdpb.BootstrapRequest) (*pdpb.BootstrapRe bootstrapCmp := clientv3.Compare(clientv3.CreateRevision(clusterRootPath), "=", 0) resp, err := s.txn().If(bootstrapCmp).Then(ops...).Commit() if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } if !resp.Succeeded { log.Warnf("cluster %d already bootstrapped", clusterID) @@ -390,7 +390,7 @@ func (s *Server) bootstrapCluster(req *pdpb.BootstrapRequest) (*pdpb.BootstrapRe log.Infof("bootstrap cluster %d ok", clusterID) if err := s.cluster.start(); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } return &pdpb.BootstrapResponse{}, nil @@ -480,12 +480,12 @@ func (s *Server) GetScheduleConfig() *ScheduleConfig { // SetScheduleConfig sets the balance config information. func (s *Server) SetScheduleConfig(cfg ScheduleConfig) error { if err := cfg.validate(); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } old := s.scheduleOpt.load() s.scheduleOpt.store(&cfg) if err := s.scheduleOpt.persist(s.kv); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } log.Infof("schedule config is updated: %+v, old: %+v", cfg, old) return nil @@ -501,13 +501,13 @@ func (s *Server) GetReplicationConfig() *ReplicationConfig { // SetReplicationConfig sets the replication config. func (s *Server) SetReplicationConfig(cfg ReplicationConfig) error { if err := cfg.validate(); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } old := s.scheduleOpt.rep.load() s.scheduleOpt.rep.store(&cfg) s.scheduleOpt.persist(s.kv) if err := s.scheduleOpt.persist(s.kv); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } log.Infof("replication config is updated: %+v, old: %+v", cfg, old) return nil @@ -565,7 +565,7 @@ func (s *Server) SetLabelProperty(typ, labelKey, labelValue string) error { s.scheduleOpt.SetLabelProperty(typ, labelKey, labelValue) err := s.scheduleOpt.persist(s.kv) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } log.Infof("label property config is updated: %+v", s.scheduleOpt.loadLabelPropertyConfig()) return nil @@ -576,7 +576,7 @@ func (s *Server) DeleteLabelProperty(typ, labelKey, labelValue string) error { s.scheduleOpt.DeleteLabelProperty(typ, labelKey, labelValue) err := s.scheduleOpt.persist(s.kv) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } log.Infof("label property config is updated: %+v", s.scheduleOpt.loadLabelPropertyConfig()) return nil @@ -591,12 +591,12 @@ func (s *Server) GetLabelProperty() LabelPropertyConfig { func (s *Server) SetClusterVersion(v string) error { version, err := ParseVersion(v) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } s.scheduleOpt.SetClusterVersion(*version) err = s.scheduleOpt.persist(s.kv) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } log.Infof("cluster version is updated to %s", v) return nil @@ -658,7 +658,7 @@ func (s *Server) SetMemberLeaderPriority(id uint64, priority int) error { key := s.getMemberLeaderPriorityPath(id) res, err := s.leaderTxn().Then(clientv3.OpPut(key, strconv.Itoa(priority))).Commit() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if !res.Succeeded { return errors.New("save leader priority failed, maybe not leader") @@ -671,7 +671,7 @@ func (s *Server) DeleteMemberLeaderPriority(id uint64) error { key := s.getMemberLeaderPriorityPath(id) res, err := s.leaderTxn().Then(clientv3.OpDelete(key)).Commit() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if !res.Succeeded { return errors.New("delete leader priority failed, maybe not leader") @@ -684,14 +684,14 @@ func (s *Server) GetMemberLeaderPriority(id uint64) (int, error) { key := s.getMemberLeaderPriorityPath(id) res, err := kvGet(s.client, key) if err != nil { - return 0, errors.Trace(err) + return 0, errors.WithStack(err) } if len(res.Kvs) == 0 { return 0, nil } priority, err := strconv.ParseInt(string(res.Kvs[0].Value), 10, 32) if err != nil { - return 0, errors.Trace(err) + return 0, errors.WithStack(err) } return int(priority), nil } diff --git a/server/testutil.go b/server/testutil.go index 858187ba456..f1ef640bdda 100644 --- a/server/testutil.go +++ b/server/testutil.go @@ -22,10 +22,10 @@ import ( "time" "github.com/coreos/etcd/embed" - "github.com/juju/errors" "github.com/pingcap/pd/pkg/tempurl" "github.com/pingcap/pd/pkg/typeutil" "github.com/pingcap/pd/server/schedule" + "github.com/pkg/errors" // Register namespace classifiers. _ "github.com/pingcap/pd/table" @@ -44,10 +44,10 @@ func NewTestServer() (*Config, *Server, CleanupFunc, error) { cfg := NewTestSingleConfig() s, err := CreateServer(cfg, nil) if err != nil { - return nil, nil, nil, errors.Trace(err) + return nil, nil, nil, errors.WithStack(err) } if err = s.Run(context.TODO()); err != nil { - return nil, nil, nil, errors.Trace(err) + return nil, nil, nil, errors.WithStack(err) } cleanup := func() { diff --git a/server/tso.go b/server/tso.go index 41b6ca9fbdc..39dfebae309 100644 --- a/server/tso.go +++ b/server/tso.go @@ -19,8 +19,8 @@ import ( "time" "github.com/coreos/etcd/clientv3" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/pdpb" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -47,7 +47,7 @@ func (s *Server) getTimestampPath() string { func (s *Server) loadTimestamp() (time.Time, error) { data, err := getValue(s.client, s.getTimestampPath()) if err != nil { - return zeroTime, errors.Trace(err) + return zeroTime, errors.WithStack(err) } if len(data) == 0 { return zeroTime, nil @@ -63,7 +63,7 @@ func (s *Server) saveTimestamp(ts time.Time) error { resp, err := s.leaderTxn().Then(clientv3.OpPut(key, string(data))).Commit() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } if !resp.Succeeded { return errors.New("save timestamp failed, maybe we lost leader") @@ -79,7 +79,7 @@ func (s *Server) syncTimestamp() error { last, err := s.loadTimestamp() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } next := time.Now() @@ -97,7 +97,7 @@ func (s *Server) syncTimestamp() error { save := next.Add(s.cfg.TsoSaveInterval.Duration) if err = s.saveTimestamp(save); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } tsoCounter.WithLabelValues("sync_ok").Inc() @@ -163,7 +163,7 @@ func (s *Server) updateTimestamp() error { if subTimeByWallClock(s.lastSavedTime, next) <= updateTimestampGuard { save := next.Add(s.cfg.TsoSaveInterval.Duration) if err := s.saveTimestamp(save); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } } diff --git a/server/util.go b/server/util.go index 5c49c28c0fb..6090accb79c 100644 --- a/server/util.go +++ b/server/util.go @@ -24,10 +24,10 @@ import ( "github.com/coreos/etcd/clientv3" "github.com/golang/protobuf/proto" - "github.com/juju/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/pd/pkg/etcdutil" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -85,7 +85,7 @@ func CheckPDVersion(opt *scheduleOption) { func getValue(c *clientv3.Client, key string, opts ...clientv3.OpOption) ([]byte, error) { resp, err := kvGet(c, key, opts...) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } if n := len(resp.Kvs); n == 0 { @@ -102,14 +102,14 @@ func getValue(c *clientv3.Client, key string, opts ...clientv3.OpOption) ([]byte func getProtoMsg(c *clientv3.Client, key string, msg proto.Message, opts ...clientv3.OpOption) (bool, error) { value, err := getValue(c, key, opts...) if err != nil { - return false, errors.Trace(err) + return false, errors.WithStack(err) } if value == nil { return false, nil } if err = proto.Unmarshal(value, msg); err != nil { - return false, errors.Trace(err) + return false, errors.WithStack(err) } return true, nil @@ -133,7 +133,7 @@ func initOrGetClusterID(c *clientv3.Client, key string) (uint64, error) { Else(clientv3.OpGet(key)). Commit() if err != nil { - return 0, errors.Trace(err) + return 0, errors.WithStack(err) } // Txn commits ok, return the generated cluster ID. @@ -213,14 +213,14 @@ func (t *slowLogTxn) Commit() (*clientv3.TxnResponse, error) { txnCounter.WithLabelValues(label).Inc() txnDuration.WithLabelValues(label).Observe(cost.Seconds()) - return resp, errors.Trace(err) + return resp, errors.WithStack(err) } // GetMembers return a slice of Members. func GetMembers(etcdClient *clientv3.Client) ([]*pdpb.Member, error) { listResp, err := etcdutil.ListEtcdMembers(etcdClient) if err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } members := make([]*pdpb.Member, 0, len(listResp.Members)) @@ -240,7 +240,7 @@ func GetMembers(etcdClient *clientv3.Client) ([]*pdpb.Member, error) { func parseTimestamp(data []byte) (time.Time, error) { nano, err := bytesToUint64(data) if err != nil { - return zeroTime, errors.Trace(err) + return zeroTime, errors.WithStack(err) } return time.Unix(0, int64(nano)), nil @@ -254,7 +254,7 @@ func subTimeByWallClock(after time.Time, before time.Time) time.Duration { func InitHTTPClient(svr *Server) error { tlsConfig, err := svr.GetSecurityConfig().ToTLSConfig() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } DialClient = &http.Client{Transport: &http.Transport{ diff --git a/table/codec.go b/table/codec.go index 2ce38ebd8f9..8868bde9e1f 100644 --- a/table/codec.go +++ b/table/codec.go @@ -17,7 +17,7 @@ import ( "bytes" "encoding/binary" - "github.com/juju/errors" + "github.com/pkg/errors" ) var ( diff --git a/table/namespace_classifier.go b/table/namespace_classifier.go index 7afbbbe00ff..a88b0b65e49 100644 --- a/table/namespace_classifier.go +++ b/table/namespace_classifier.go @@ -23,9 +23,9 @@ import ( "sync" "time" - "github.com/juju/errors" "github.com/pingcap/pd/server/core" "github.com/pingcap/pd/server/namespace" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) @@ -103,7 +103,7 @@ const kvRangeLimit = 1000 func NewTableNamespaceClassifier(kv *core.KV, idAlloc core.IDAllocator) (namespace.Classifier, error) { nsInfo := newNamespacesInfo() if err := nsInfo.loadNamespaces(kv, kvRangeLimit); err != nil { - return nil, errors.Trace(err) + return nil, errors.WithStack(err) } c := &tableNamespaceClassifier{ nsInfo: nsInfo, @@ -197,12 +197,12 @@ func (c *tableNamespaceClassifier) CreateNamespace(name string) error { id, err := c.idAlloc.Alloc() if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } ns := NewNamespace(id, name) err = c.putNamespaceLocked(ns) - return errors.Trace(err) + return errors.WithStack(err) } // AddNamespaceTableID adds table ID to namespace. @@ -317,7 +317,7 @@ func (c *tableNamespaceClassifier) ReloadNamespaces() error { defer c.Unlock() if err := nsInfo.loadNamespaces(c.kv, kvRangeLimit); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } c.nsInfo = nsInfo @@ -327,7 +327,7 @@ func (c *tableNamespaceClassifier) ReloadNamespaces() error { func (c *tableNamespaceClassifier) putNamespaceLocked(ns *Namespace) error { if c.kv != nil { if err := c.nsInfo.saveNamespace(c.kv, ns); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } } c.nsInfo.setNamespace(ns) @@ -407,10 +407,10 @@ func (namespaceInfo *namespacesInfo) namespacePath(nsID uint64) string { func (namespaceInfo *namespacesInfo) saveNamespace(kv *core.KV, ns *Namespace) error { value, err := json.Marshal(ns) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } err = kv.Save(namespaceInfo.namespacePath(ns.GetID()), string(value)) - return errors.Trace(err) + return errors.WithStack(err) } func (namespaceInfo *namespacesInfo) loadNamespaces(kv *core.KV, rangeLimit int) error { @@ -423,12 +423,12 @@ func (namespaceInfo *namespacesInfo) loadNamespaces(kv *core.KV, rangeLimit int) key := namespaceInfo.namespacePath(nextID) res, err := kv.LoadRange(key, endKey, rangeLimit) if err != nil { - return errors.Trace(err) + return errors.WithStack(err) } for _, s := range res { ns := &Namespace{} if err := json.Unmarshal([]byte(s), ns); err != nil { - return errors.Trace(err) + return errors.WithStack(err) } nextID = ns.GetID() + 1 namespaceInfo.setNamespace(ns) diff --git a/table/namespace_handler.go b/table/namespace_handler.go index 00d4ec7e7ee..c1384b620d3 100644 --- a/table/namespace_handler.go +++ b/table/namespace_handler.go @@ -19,8 +19,8 @@ import ( "strconv" "github.com/gorilla/mux" - "github.com/juju/errors" "github.com/pingcap/pd/pkg/apiutil" + "github.com/pkg/errors" "github.com/unrolled/render" ) From 4c70debb3b4a1fd8e0a9a918c2fa01c1aaf1a86c Mon Sep 17 00:00:00 2001 From: Greg Weber Date: Wed, 22 Aug 2018 17:57:03 -0700 Subject: [PATCH 2/2] Gopkg changes for juju/errors -> pkg/errors --- Gopkg.lock | 18 +- Gopkg.toml | 4 + vendor/github.com/juju/errors/LICENSE | 191 ----------- vendor/github.com/juju/errors/doc.go | 81 ----- vendor/github.com/juju/errors/error.go | 172 ---------- vendor/github.com/juju/errors/errortypes.go | 309 ------------------ vendor/github.com/juju/errors/functions.go | 330 -------------------- vendor/github.com/juju/errors/path.go | 38 --- vendor/github.com/pkg/errors/LICENSE | 23 ++ vendor/github.com/pkg/errors/errors.go | 269 ++++++++++++++++ vendor/github.com/pkg/errors/stack.go | 178 +++++++++++ 11 files changed, 483 insertions(+), 1130 deletions(-) delete mode 100644 vendor/github.com/juju/errors/LICENSE delete mode 100644 vendor/github.com/juju/errors/doc.go delete mode 100644 vendor/github.com/juju/errors/error.go delete mode 100644 vendor/github.com/juju/errors/errortypes.go delete mode 100644 vendor/github.com/juju/errors/functions.go delete mode 100644 vendor/github.com/juju/errors/path.go create mode 100644 vendor/github.com/pkg/errors/LICENSE create mode 100644 vendor/github.com/pkg/errors/errors.go create mode 100644 vendor/github.com/pkg/errors/stack.go diff --git a/Gopkg.lock b/Gopkg.lock index 85471fc1cc0..735576589d9 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -263,14 +263,6 @@ revision = "2eee05ed794112d45db504eb05aa693efd2b8b09" version = "v0.1.0" -[[projects]] - branch = "master" - digest = "1:0550b06297ebdd7dde9a20c5129f941abfdba6e47f8111bfdd0f1830c58dc800" - name = "github.com/juju/errors" - packages = ["."] - pruneopts = "NUT" - revision = "c7d06af17c68cd34c835053720b21f6549d9b0ee" - [[projects]] digest = "1:d0164259ed17929689df11205194d80288e8ae25351778f7a3421a24774c36f8" name = "github.com/mattn/go-shellwords" @@ -334,6 +326,14 @@ pruneopts = "NUT" revision = "279515615485b0f2d12f1421cc412fe2784e0190" +[[projects]] + digest = "1:5cf3f025cbee5951a4ee961de067c8a89fc95a5adabead774f82822efabab121" + name = "github.com/pkg/errors" + packages = ["."] + pruneopts = "NUT" + revision = "645ef00459ed84a119197bfb8d8205042c6df63d" + version = "v0.8.0" + [[projects]] digest = "1:8d8f554bbb62fb7aecf661b85b25e227f6ab6cfe2b4395ea65ef478bfc174940" name = "github.com/prometheus/client_golang" @@ -637,7 +637,6 @@ "github.com/google/btree", "github.com/gorilla/mux", "github.com/grpc-ecosystem/go-grpc-prometheus", - "github.com/juju/errors", "github.com/mattn/go-shellwords", "github.com/montanaflynn/stats", "github.com/opentracing/opentracing-go", @@ -645,6 +644,7 @@ "github.com/pingcap/kvproto/pkg/eraftpb", "github.com/pingcap/kvproto/pkg/metapb", "github.com/pingcap/kvproto/pkg/pdpb", + "github.com/pkg/errors", "github.com/prometheus/client_golang/prometheus", "github.com/prometheus/client_golang/prometheus/push", "github.com/sirupsen/logrus", diff --git a/Gopkg.toml b/Gopkg.toml index 1ff28a85da4..b56494b4163 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -35,3 +35,7 @@ [[constraint]] name = "github.com/etcd-io/gofail" branch = "master" + +[[constraint]] + name = "github.com/pkg/errors" + version = "0.8.0" diff --git a/vendor/github.com/juju/errors/LICENSE b/vendor/github.com/juju/errors/LICENSE deleted file mode 100644 index ade9307b390..00000000000 --- a/vendor/github.com/juju/errors/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ -All files in this repository are licensed as follows. If you contribute -to this repository, it is assumed that you license your contribution -under the same license unless you state otherwise. - -All files Copyright (C) 2015 Canonical Ltd. unless otherwise specified in the file. - -This software is licensed under the LGPLv3, included below. - -As a special exception to the GNU Lesser General Public License version 3 -("LGPL3"), the copyright holders of this Library give you permission to -convey to a third party a Combined Work that links statically or dynamically -to this Library without providing any Minimal Corresponding Source or -Minimal Application Code as set out in 4d or providing the installation -information set out in section 4e, provided that you comply with the other -provisions of LGPL3 and provided that you meet, for the Application the -terms and conditions of the license(s) which apply to the Application. - -Except as stated in this special exception, the provisions of LGPL3 will -continue to comply in full to this Library. If you modify this Library, you -may apply this exception to your version of this Library, but you are not -obliged to do so. If you do not wish to do so, delete this exception -statement from your version. This exception does not (and cannot) modify any -license terms which apply to the Application, with which you must still -comply. - - - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/vendor/github.com/juju/errors/doc.go b/vendor/github.com/juju/errors/doc.go deleted file mode 100644 index 35b119aa345..00000000000 --- a/vendor/github.com/juju/errors/doc.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2013, 2014 Canonical Ltd. -// Licensed under the LGPLv3, see LICENCE file for details. - -/* -[godoc-link-here] - -The juju/errors provides an easy way to annotate errors without losing the -orginal error context. - -The exported `New` and `Errorf` functions are designed to replace the -`errors.New` and `fmt.Errorf` functions respectively. The same underlying -error is there, but the package also records the location at which the error -was created. - -A primary use case for this library is to add extra context any time an -error is returned from a function. - - if err := SomeFunc(); err != nil { - return err - } - -This instead becomes: - - if err := SomeFunc(); err != nil { - return errors.Trace(err) - } - -which just records the file and line number of the Trace call, or - - if err := SomeFunc(); err != nil { - return errors.Annotate(err, "more context") - } - -which also adds an annotation to the error. - -When you want to check to see if an error is of a particular type, a helper -function is normally exported by the package that returned the error, like the -`os` package does. The underlying cause of the error is available using the -`Cause` function. - - os.IsNotExist(errors.Cause(err)) - -The result of the `Error()` call on an annotated error is the annotations joined -with colons, then the result of the `Error()` method for the underlying error -that was the cause. - - err := errors.Errorf("original") - err = errors.Annotatef(err, "context") - err = errors.Annotatef(err, "more context") - err.Error() -> "more context: context: original" - -Obviously recording the file, line and functions is not very useful if you -cannot get them back out again. - - errors.ErrorStack(err) - -will return something like: - - first error - github.com/juju/errors/annotation_test.go:193: - github.com/juju/errors/annotation_test.go:194: annotation - github.com/juju/errors/annotation_test.go:195: - github.com/juju/errors/annotation_test.go:196: more context - github.com/juju/errors/annotation_test.go:197: - -The first error was generated by an external system, so there was no location -associated. The second, fourth, and last lines were generated with Trace calls, -and the other two through Annotate. - -Sometimes when responding to an error you want to return a more specific error -for the situation. - - if err := FindField(field); err != nil { - return errors.Wrap(err, errors.NotFoundf(field)) - } - -This returns an error where the complete error stack is still available, and -`errors.Cause()` will return the `NotFound` error. - -*/ -package errors diff --git a/vendor/github.com/juju/errors/error.go b/vendor/github.com/juju/errors/error.go deleted file mode 100644 index b7df73589e6..00000000000 --- a/vendor/github.com/juju/errors/error.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2014 Canonical Ltd. -// Licensed under the LGPLv3, see LICENCE file for details. - -package errors - -import ( - "fmt" - "reflect" - "runtime" -) - -// Err holds a description of an error along with information about -// where the error was created. -// -// It may be embedded in custom error types to add extra information that -// this errors package can understand. -type Err struct { - // message holds an annotation of the error. - message string - - // cause holds the cause of the error as returned - // by the Cause method. - cause error - - // previous holds the previous error in the error stack, if any. - previous error - - // file and line hold the source code location where the error was - // created. - file string - line int -} - -// NewErr is used to return an Err for the purpose of embedding in other -// structures. The location is not specified, and needs to be set with a call -// to SetLocation. -// -// For example: -// type FooError struct { -// errors.Err -// code int -// } -// -// func NewFooError(code int) error { -// err := &FooError{errors.NewErr("foo"), code} -// err.SetLocation(1) -// return err -// } -func NewErr(format string, args ...interface{}) Err { - return Err{ - message: fmt.Sprintf(format, args...), - } -} - -// NewErrWithCause is used to return an Err with case by other error for the purpose of embedding in other -// structures. The location is not specified, and needs to be set with a call -// to SetLocation. -// -// For example: -// type FooError struct { -// errors.Err -// code int -// } -// -// func (e *FooError) Annotate(format string, args ...interface{}) error { -// err := &FooError{errors.NewErrWithCause(e.Err, format, args...), e.code} -// err.SetLocation(1) -// return err -// }) -func NewErrWithCause(other error, format string, args ...interface{}) Err { - return Err{ - message: fmt.Sprintf(format, args...), - cause: Cause(other), - previous: other, - } -} - -// Location is the file and line of where the error was most recently -// created or annotated. -func (e *Err) Location() (filename string, line int) { - return e.file, e.line -} - -// Underlying returns the previous error in the error stack, if any. A client -// should not ever really call this method. It is used to build the error -// stack and should not be introspected by client calls. Or more -// specifically, clients should not depend on anything but the `Cause` of an -// error. -func (e *Err) Underlying() error { - return e.previous -} - -// The Cause of an error is the most recent error in the error stack that -// meets one of these criteria: the original error that was raised; the new -// error that was passed into the Wrap function; the most recently masked -// error; or nil if the error itself is considered the Cause. Normally this -// method is not invoked directly, but instead through the Cause stand alone -// function. -func (e *Err) Cause() error { - return e.cause -} - -// Message returns the message stored with the most recent location. This is -// the empty string if the most recent call was Trace, or the message stored -// with Annotate or Mask. -func (e *Err) Message() string { - return e.message -} - -// Error implements error.Error. -func (e *Err) Error() string { - // We want to walk up the stack of errors showing the annotations - // as long as the cause is the same. - err := e.previous - if !sameError(Cause(err), e.cause) && e.cause != nil { - err = e.cause - } - switch { - case err == nil: - return e.message - case e.message == "": - return err.Error() - } - return fmt.Sprintf("%s: %v", e.message, err) -} - -// Format implements fmt.Formatter -// When printing errors with %+v it also prints the stack trace. -// %#v unsurprisingly will print the real underlying type. -func (e *Err) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case s.Flag('+'): - fmt.Fprintf(s, "%s", ErrorStack(e)) - return - case s.Flag('#'): - // avoid infinite recursion by wrapping e into a type - // that doesn't implement Formatter. - fmt.Fprintf(s, "%#v", (*unformatter)(e)) - return - } - fallthrough - case 's': - fmt.Fprintf(s, "%s", e.Error()) - } -} - -// helper for Format -type unformatter Err - -func (unformatter) Format() { /* break the fmt.Formatter interface */ } - -// SetLocation records the source location of the error at callDepth stack -// frames above the call. -func (e *Err) SetLocation(callDepth int) { - _, file, line, _ := runtime.Caller(callDepth + 1) - e.file = trimGoPath(file) - e.line = line -} - -// StackTrace returns one string for each location recorded in the stack of -// errors. The first value is the originating error, with a line for each -// other annotation or tracing of the error. -func (e *Err) StackTrace() []string { - return errorStack(e) -} - -// Ideally we'd have a way to check identity, but deep equals will do. -func sameError(e1, e2 error) bool { - return reflect.DeepEqual(e1, e2) -} diff --git a/vendor/github.com/juju/errors/errortypes.go b/vendor/github.com/juju/errors/errortypes.go deleted file mode 100644 index 9b731c44c3d..00000000000 --- a/vendor/github.com/juju/errors/errortypes.go +++ /dev/null @@ -1,309 +0,0 @@ -// Copyright 2014 Canonical Ltd. -// Licensed under the LGPLv3, see LICENCE file for details. - -package errors - -import ( - "fmt" -) - -// wrap is a helper to construct an *wrapper. -func wrap(err error, format, suffix string, args ...interface{}) Err { - newErr := Err{ - message: fmt.Sprintf(format+suffix, args...), - previous: err, - } - newErr.SetLocation(2) - return newErr -} - -// notFound represents an error when something has not been found. -type notFound struct { - Err -} - -// NotFoundf returns an error which satisfies IsNotFound(). -func NotFoundf(format string, args ...interface{}) error { - return ¬Found{wrap(nil, format, " not found", args...)} -} - -// NewNotFound returns an error which wraps err that satisfies -// IsNotFound(). -func NewNotFound(err error, msg string) error { - return ¬Found{wrap(err, msg, "")} -} - -// IsNotFound reports whether err was created with NotFoundf() or -// NewNotFound(). -func IsNotFound(err error) bool { - err = Cause(err) - _, ok := err.(*notFound) - return ok -} - -// userNotFound represents an error when an inexistent user is looked up. -type userNotFound struct { - Err -} - -// UserNotFoundf returns an error which satisfies IsUserNotFound(). -func UserNotFoundf(format string, args ...interface{}) error { - return &userNotFound{wrap(nil, format, " user not found", args...)} -} - -// NewUserNotFound returns an error which wraps err and satisfies -// IsUserNotFound(). -func NewUserNotFound(err error, msg string) error { - return &userNotFound{wrap(err, msg, "")} -} - -// IsUserNotFound reports whether err was created with UserNotFoundf() or -// NewUserNotFound(). -func IsUserNotFound(err error) bool { - err = Cause(err) - _, ok := err.(*userNotFound) - return ok -} - -// unauthorized represents an error when an operation is unauthorized. -type unauthorized struct { - Err -} - -// Unauthorizedf returns an error which satisfies IsUnauthorized(). -func Unauthorizedf(format string, args ...interface{}) error { - return &unauthorized{wrap(nil, format, "", args...)} -} - -// NewUnauthorized returns an error which wraps err and satisfies -// IsUnauthorized(). -func NewUnauthorized(err error, msg string) error { - return &unauthorized{wrap(err, msg, "")} -} - -// IsUnauthorized reports whether err was created with Unauthorizedf() or -// NewUnauthorized(). -func IsUnauthorized(err error) bool { - err = Cause(err) - _, ok := err.(*unauthorized) - return ok -} - -// notImplemented represents an error when something is not -// implemented. -type notImplemented struct { - Err -} - -// NotImplementedf returns an error which satisfies IsNotImplemented(). -func NotImplementedf(format string, args ...interface{}) error { - return ¬Implemented{wrap(nil, format, " not implemented", args...)} -} - -// NewNotImplemented returns an error which wraps err and satisfies -// IsNotImplemented(). -func NewNotImplemented(err error, msg string) error { - return ¬Implemented{wrap(err, msg, "")} -} - -// IsNotImplemented reports whether err was created with -// NotImplementedf() or NewNotImplemented(). -func IsNotImplemented(err error) bool { - err = Cause(err) - _, ok := err.(*notImplemented) - return ok -} - -// alreadyExists represents and error when something already exists. -type alreadyExists struct { - Err -} - -// AlreadyExistsf returns an error which satisfies IsAlreadyExists(). -func AlreadyExistsf(format string, args ...interface{}) error { - return &alreadyExists{wrap(nil, format, " already exists", args...)} -} - -// NewAlreadyExists returns an error which wraps err and satisfies -// IsAlreadyExists(). -func NewAlreadyExists(err error, msg string) error { - return &alreadyExists{wrap(err, msg, "")} -} - -// IsAlreadyExists reports whether the error was created with -// AlreadyExistsf() or NewAlreadyExists(). -func IsAlreadyExists(err error) bool { - err = Cause(err) - _, ok := err.(*alreadyExists) - return ok -} - -// notSupported represents an error when something is not supported. -type notSupported struct { - Err -} - -// NotSupportedf returns an error which satisfies IsNotSupported(). -func NotSupportedf(format string, args ...interface{}) error { - return ¬Supported{wrap(nil, format, " not supported", args...)} -} - -// NewNotSupported returns an error which wraps err and satisfies -// IsNotSupported(). -func NewNotSupported(err error, msg string) error { - return ¬Supported{wrap(err, msg, "")} -} - -// IsNotSupported reports whether the error was created with -// NotSupportedf() or NewNotSupported(). -func IsNotSupported(err error) bool { - err = Cause(err) - _, ok := err.(*notSupported) - return ok -} - -// notValid represents an error when something is not valid. -type notValid struct { - Err -} - -// NotValidf returns an error which satisfies IsNotValid(). -func NotValidf(format string, args ...interface{}) error { - return ¬Valid{wrap(nil, format, " not valid", args...)} -} - -// NewNotValid returns an error which wraps err and satisfies IsNotValid(). -func NewNotValid(err error, msg string) error { - return ¬Valid{wrap(err, msg, "")} -} - -// IsNotValid reports whether the error was created with NotValidf() or -// NewNotValid(). -func IsNotValid(err error) bool { - err = Cause(err) - _, ok := err.(*notValid) - return ok -} - -// notProvisioned represents an error when something is not yet provisioned. -type notProvisioned struct { - Err -} - -// NotProvisionedf returns an error which satisfies IsNotProvisioned(). -func NotProvisionedf(format string, args ...interface{}) error { - return ¬Provisioned{wrap(nil, format, " not provisioned", args...)} -} - -// NewNotProvisioned returns an error which wraps err that satisfies -// IsNotProvisioned(). -func NewNotProvisioned(err error, msg string) error { - return ¬Provisioned{wrap(err, msg, "")} -} - -// IsNotProvisioned reports whether err was created with NotProvisionedf() or -// NewNotProvisioned(). -func IsNotProvisioned(err error) bool { - err = Cause(err) - _, ok := err.(*notProvisioned) - return ok -} - -// notAssigned represents an error when something is not yet assigned to -// something else. -type notAssigned struct { - Err -} - -// NotAssignedf returns an error which satisfies IsNotAssigned(). -func NotAssignedf(format string, args ...interface{}) error { - return ¬Assigned{wrap(nil, format, " not assigned", args...)} -} - -// NewNotAssigned returns an error which wraps err that satisfies -// IsNotAssigned(). -func NewNotAssigned(err error, msg string) error { - return ¬Assigned{wrap(err, msg, "")} -} - -// IsNotAssigned reports whether err was created with NotAssignedf() or -// NewNotAssigned(). -func IsNotAssigned(err error) bool { - err = Cause(err) - _, ok := err.(*notAssigned) - return ok -} - -// badRequest represents an error when a request has bad parameters. -type badRequest struct { - Err -} - -// BadRequestf returns an error which satisfies IsBadRequest(). -func BadRequestf(format string, args ...interface{}) error { - return &badRequest{wrap(nil, format, "", args...)} -} - -// NewBadRequest returns an error which wraps err that satisfies -// IsBadRequest(). -func NewBadRequest(err error, msg string) error { - return &badRequest{wrap(err, msg, "")} -} - -// IsBadRequest reports whether err was created with BadRequestf() or -// NewBadRequest(). -func IsBadRequest(err error) bool { - err = Cause(err) - _, ok := err.(*badRequest) - return ok -} - -// methodNotAllowed represents an error when an HTTP request -// is made with an inappropriate method. -type methodNotAllowed struct { - Err -} - -// MethodNotAllowedf returns an error which satisfies IsMethodNotAllowed(). -func MethodNotAllowedf(format string, args ...interface{}) error { - return &methodNotAllowed{wrap(nil, format, "", args...)} -} - -// NewMethodNotAllowed returns an error which wraps err that satisfies -// IsMethodNotAllowed(). -func NewMethodNotAllowed(err error, msg string) error { - return &methodNotAllowed{wrap(err, msg, "")} -} - -// IsMethodNotAllowed reports whether err was created with MethodNotAllowedf() or -// NewMethodNotAllowed(). -func IsMethodNotAllowed(err error) bool { - err = Cause(err) - _, ok := err.(*methodNotAllowed) - return ok -} - -// forbidden represents an error when a request cannot be completed because of -// missing privileges -type forbidden struct { - Err -} - -// Forbiddenf returns an error which satistifes IsForbidden() -func Forbiddenf(format string, args ...interface{}) error { - return &forbidden{wrap(nil, format, "", args...)} -} - -// NewForbidden returns an error which wraps err that satisfies -// IsForbidden(). -func NewForbidden(err error, msg string) error { - return &forbidden{wrap(err, msg, "")} -} - -// IsForbidden reports whether err was created with Forbiddenf() or -// NewForbidden(). -func IsForbidden(err error) bool { - err = Cause(err) - _, ok := err.(*forbidden) - return ok -} diff --git a/vendor/github.com/juju/errors/functions.go b/vendor/github.com/juju/errors/functions.go deleted file mode 100644 index f86b09b2dba..00000000000 --- a/vendor/github.com/juju/errors/functions.go +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright 2014 Canonical Ltd. -// Licensed under the LGPLv3, see LICENCE file for details. - -package errors - -import ( - "fmt" - "strings" -) - -// New is a drop in replacement for the standard library errors module that records -// the location that the error is created. -// -// For example: -// return errors.New("validation failed") -// -func New(message string) error { - err := &Err{message: message} - err.SetLocation(1) - return err -} - -// Errorf creates a new annotated error and records the location that the -// error is created. This should be a drop in replacement for fmt.Errorf. -// -// For example: -// return errors.Errorf("validation failed: %s", message) -// -func Errorf(format string, args ...interface{}) error { - err := &Err{message: fmt.Sprintf(format, args...)} - err.SetLocation(1) - return err -} - -// Trace adds the location of the Trace call to the stack. The Cause of the -// resulting error is the same as the error parameter. If the other error is -// nil, the result will be nil. -// -// For example: -// if err := SomeFunc(); err != nil { -// return errors.Trace(err) -// } -// -func Trace(other error) error { - if other == nil { - return nil - } - err := &Err{previous: other, cause: Cause(other)} - err.SetLocation(1) - return err -} - -// Annotate is used to add extra context to an existing error. The location of -// the Annotate call is recorded with the annotations. The file, line and -// function are also recorded. -// -// For example: -// if err := SomeFunc(); err != nil { -// return errors.Annotate(err, "failed to frombulate") -// } -// -func Annotate(other error, message string) error { - if other == nil { - return nil - } - err := &Err{ - previous: other, - cause: Cause(other), - message: message, - } - err.SetLocation(1) - return err -} - -// Annotatef is used to add extra context to an existing error. The location of -// the Annotate call is recorded with the annotations. The file, line and -// function are also recorded. -// -// For example: -// if err := SomeFunc(); err != nil { -// return errors.Annotatef(err, "failed to frombulate the %s", arg) -// } -// -func Annotatef(other error, format string, args ...interface{}) error { - if other == nil { - return nil - } - err := &Err{ - previous: other, - cause: Cause(other), - message: fmt.Sprintf(format, args...), - } - err.SetLocation(1) - return err -} - -// DeferredAnnotatef annotates the given error (when it is not nil) with the given -// format string and arguments (like fmt.Sprintf). If *err is nil, DeferredAnnotatef -// does nothing. This method is used in a defer statement in order to annotate any -// resulting error with the same message. -// -// For example: -// -// defer DeferredAnnotatef(&err, "failed to frombulate the %s", arg) -// -func DeferredAnnotatef(err *error, format string, args ...interface{}) { - if *err == nil { - return - } - newErr := &Err{ - message: fmt.Sprintf(format, args...), - cause: Cause(*err), - previous: *err, - } - newErr.SetLocation(1) - *err = newErr -} - -// Wrap changes the Cause of the error. The location of the Wrap call is also -// stored in the error stack. -// -// For example: -// if err := SomeFunc(); err != nil { -// newErr := &packageError{"more context", private_value} -// return errors.Wrap(err, newErr) -// } -// -func Wrap(other, newDescriptive error) error { - err := &Err{ - previous: other, - cause: newDescriptive, - } - err.SetLocation(1) - return err -} - -// Wrapf changes the Cause of the error, and adds an annotation. The location -// of the Wrap call is also stored in the error stack. -// -// For example: -// if err := SomeFunc(); err != nil { -// return errors.Wrapf(err, simpleErrorType, "invalid value %q", value) -// } -// -func Wrapf(other, newDescriptive error, format string, args ...interface{}) error { - err := &Err{ - message: fmt.Sprintf(format, args...), - previous: other, - cause: newDescriptive, - } - err.SetLocation(1) - return err -} - -// Mask masks the given error with the given format string and arguments (like -// fmt.Sprintf), returning a new error that maintains the error stack, but -// hides the underlying error type. The error string still contains the full -// annotations. If you want to hide the annotations, call Wrap. -func Maskf(other error, format string, args ...interface{}) error { - if other == nil { - return nil - } - err := &Err{ - message: fmt.Sprintf(format, args...), - previous: other, - } - err.SetLocation(1) - return err -} - -// Mask hides the underlying error type, and records the location of the masking. -func Mask(other error) error { - if other == nil { - return nil - } - err := &Err{ - previous: other, - } - err.SetLocation(1) - return err -} - -// Cause returns the cause of the given error. This will be either the -// original error, or the result of a Wrap or Mask call. -// -// Cause is the usual way to diagnose errors that may have been wrapped by -// the other errors functions. -func Cause(err error) error { - var diag error - if err, ok := err.(causer); ok { - diag = err.Cause() - } - if diag != nil { - return diag - } - return err -} - -type causer interface { - Cause() error -} - -type wrapper interface { - // Message returns the top level error message, - // not including the message from the Previous - // error. - Message() string - - // Underlying returns the Previous error, or nil - // if there is none. - Underlying() error -} - -type locationer interface { - Location() (string, int) -} - -var ( - _ wrapper = (*Err)(nil) - _ locationer = (*Err)(nil) - _ causer = (*Err)(nil) -) - -// Details returns information about the stack of errors wrapped by err, in -// the format: -// -// [{filename:99: error one} {otherfile:55: cause of error one}] -// -// This is a terse alternative to ErrorStack as it returns a single line. -func Details(err error) string { - if err == nil { - return "[]" - } - var s []byte - s = append(s, '[') - for { - s = append(s, '{') - if err, ok := err.(locationer); ok { - file, line := err.Location() - if file != "" { - s = append(s, fmt.Sprintf("%s:%d", file, line)...) - s = append(s, ": "...) - } - } - if cerr, ok := err.(wrapper); ok { - s = append(s, cerr.Message()...) - err = cerr.Underlying() - } else { - s = append(s, err.Error()...) - err = nil - } - s = append(s, '}') - if err == nil { - break - } - s = append(s, ' ') - } - s = append(s, ']') - return string(s) -} - -// ErrorStack returns a string representation of the annotated error. If the -// error passed as the parameter is not an annotated error, the result is -// simply the result of the Error() method on that error. -// -// If the error is an annotated error, a multi-line string is returned where -// each line represents one entry in the annotation stack. The full filename -// from the call stack is used in the output. -// -// first error -// github.com/juju/errors/annotation_test.go:193: -// github.com/juju/errors/annotation_test.go:194: annotation -// github.com/juju/errors/annotation_test.go:195: -// github.com/juju/errors/annotation_test.go:196: more context -// github.com/juju/errors/annotation_test.go:197: -func ErrorStack(err error) string { - return strings.Join(errorStack(err), "\n") -} - -func errorStack(err error) []string { - if err == nil { - return nil - } - - // We want the first error first - var lines []string - for { - var buff []byte - if err, ok := err.(locationer); ok { - file, line := err.Location() - // Strip off the leading GOPATH/src path elements. - file = trimGoPath(file) - if file != "" { - buff = append(buff, fmt.Sprintf("%s:%d", file, line)...) - buff = append(buff, ": "...) - } - } - if cerr, ok := err.(wrapper); ok { - message := cerr.Message() - buff = append(buff, message...) - // If there is a cause for this error, and it is different to the cause - // of the underlying error, then output the error string in the stack trace. - var cause error - if err1, ok := err.(causer); ok { - cause = err1.Cause() - } - err = cerr.Underlying() - if cause != nil && !sameError(Cause(err), cause) { - if message != "" { - buff = append(buff, ": "...) - } - buff = append(buff, cause.Error()...) - } - } else { - buff = append(buff, err.Error()...) - err = nil - } - lines = append(lines, string(buff)) - if err == nil { - break - } - } - // reverse the lines to get the original error, which was at the end of - // the list, back to the start. - var result []string - for i := len(lines); i > 0; i-- { - result = append(result, lines[i-1]) - } - return result -} diff --git a/vendor/github.com/juju/errors/path.go b/vendor/github.com/juju/errors/path.go deleted file mode 100644 index a7b726ab094..00000000000 --- a/vendor/github.com/juju/errors/path.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2013, 2014 Canonical Ltd. -// Licensed under the LGPLv3, see LICENCE file for details. - -package errors - -import ( - "runtime" - "strings" -) - -// prefixSize is used internally to trim the user specific path from the -// front of the returned filenames from the runtime call stack. -var prefixSize int - -// goPath is the deduced path based on the location of this file as compiled. -var goPath string - -func init() { - _, file, _, ok := runtime.Caller(0) - if file == "?" { - return - } - if ok { - // We know that the end of the file should be: - // github.com/juju/errors/path.go - size := len(file) - suffix := len("github.com/juju/errors/path.go") - goPath = file[:size-suffix] - prefixSize = len(goPath) - } -} - -func trimGoPath(filename string) string { - if strings.HasPrefix(filename, goPath) { - return filename[prefixSize:] - } - return filename -} diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE new file mode 100644 index 00000000000..835ba3e755c --- /dev/null +++ b/vendor/github.com/pkg/errors/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2015, Dave Cheney +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go new file mode 100644 index 00000000000..842ee80456d --- /dev/null +++ b/vendor/github.com/pkg/errors/errors.go @@ -0,0 +1,269 @@ +// Package errors provides simple error handling primitives. +// +// The traditional error handling idiom in Go is roughly akin to +// +// if err != nil { +// return err +// } +// +// which applied recursively up the call stack results in error reports +// without context or debugging information. The errors package allows +// programmers to add context to the failure path in their code in a way +// that does not destroy the original value of the error. +// +// Adding context to an error +// +// The errors.Wrap function returns a new error that adds context to the +// original error by recording a stack trace at the point Wrap is called, +// and the supplied message. For example +// +// _, err := ioutil.ReadAll(r) +// if err != nil { +// return errors.Wrap(err, "read failed") +// } +// +// If additional control is required the errors.WithStack and errors.WithMessage +// functions destructure errors.Wrap into its component operations of annotating +// an error with a stack trace and an a message, respectively. +// +// Retrieving the cause of an error +// +// Using errors.Wrap constructs a stack of errors, adding context to the +// preceding error. Depending on the nature of the error it may be necessary +// to reverse the operation of errors.Wrap to retrieve the original error +// for inspection. Any error value which implements this interface +// +// type causer interface { +// Cause() error +// } +// +// can be inspected by errors.Cause. errors.Cause will recursively retrieve +// the topmost error which does not implement causer, which is assumed to be +// the original cause. For example: +// +// switch err := errors.Cause(err).(type) { +// case *MyError: +// // handle specifically +// default: +// // unknown error +// } +// +// causer interface is not exported by this package, but is considered a part +// of stable public API. +// +// Formatted printing of errors +// +// All error values returned from this package implement fmt.Formatter and can +// be formatted by the fmt package. The following verbs are supported +// +// %s print the error. If the error has a Cause it will be +// printed recursively +// %v see %s +// %+v extended format. Each Frame of the error's StackTrace will +// be printed in detail. +// +// Retrieving the stack trace of an error or wrapper +// +// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are +// invoked. This information can be retrieved with the following interface. +// +// type stackTracer interface { +// StackTrace() errors.StackTrace +// } +// +// Where errors.StackTrace is defined as +// +// type StackTrace []Frame +// +// The Frame type represents a call site in the stack trace. Frame supports +// the fmt.Formatter interface that can be used for printing information about +// the stack trace of this error. For example: +// +// if err, ok := err.(stackTracer); ok { +// for _, f := range err.StackTrace() { +// fmt.Printf("%+s:%d", f) +// } +// } +// +// stackTracer interface is not exported by this package, but is considered a part +// of stable public API. +// +// See the documentation for Frame.Format for more details. +package errors + +import ( + "fmt" + "io" +) + +// New returns an error with the supplied message. +// New also records the stack trace at the point it was called. +func New(message string) error { + return &fundamental{ + msg: message, + stack: callers(), + } +} + +// Errorf formats according to a format specifier and returns the string +// as a value that satisfies error. +// Errorf also records the stack trace at the point it was called. +func Errorf(format string, args ...interface{}) error { + return &fundamental{ + msg: fmt.Sprintf(format, args...), + stack: callers(), + } +} + +// fundamental is an error that has a message and a stack, but no caller. +type fundamental struct { + msg string + *stack +} + +func (f *fundamental) Error() string { return f.msg } + +func (f *fundamental) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + io.WriteString(s, f.msg) + f.stack.Format(s, verb) + return + } + fallthrough + case 's': + io.WriteString(s, f.msg) + case 'q': + fmt.Fprintf(s, "%q", f.msg) + } +} + +// WithStack annotates err with a stack trace at the point WithStack was called. +// If err is nil, WithStack returns nil. +func WithStack(err error) error { + if err == nil { + return nil + } + return &withStack{ + err, + callers(), + } +} + +type withStack struct { + error + *stack +} + +func (w *withStack) Cause() error { return w.error } + +func (w *withStack) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + fmt.Fprintf(s, "%+v", w.Cause()) + w.stack.Format(s, verb) + return + } + fallthrough + case 's': + io.WriteString(s, w.Error()) + case 'q': + fmt.Fprintf(s, "%q", w.Error()) + } +} + +// Wrap returns an error annotating err with a stack trace +// at the point Wrap is called, and the supplied message. +// If err is nil, Wrap returns nil. +func Wrap(err error, message string) error { + if err == nil { + return nil + } + err = &withMessage{ + cause: err, + msg: message, + } + return &withStack{ + err, + callers(), + } +} + +// Wrapf returns an error annotating err with a stack trace +// at the point Wrapf is call, and the format specifier. +// If err is nil, Wrapf returns nil. +func Wrapf(err error, format string, args ...interface{}) error { + if err == nil { + return nil + } + err = &withMessage{ + cause: err, + msg: fmt.Sprintf(format, args...), + } + return &withStack{ + err, + callers(), + } +} + +// WithMessage annotates err with a new message. +// If err is nil, WithMessage returns nil. +func WithMessage(err error, message string) error { + if err == nil { + return nil + } + return &withMessage{ + cause: err, + msg: message, + } +} + +type withMessage struct { + cause error + msg string +} + +func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } +func (w *withMessage) Cause() error { return w.cause } + +func (w *withMessage) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + fmt.Fprintf(s, "%+v\n", w.Cause()) + io.WriteString(s, w.msg) + return + } + fallthrough + case 's', 'q': + io.WriteString(s, w.Error()) + } +} + +// Cause returns the underlying cause of the error, if possible. +// An error value has a cause if it implements the following +// interface: +// +// type causer interface { +// Cause() error +// } +// +// If the error does not implement Cause, the original error will +// be returned. If the error is nil, nil will be returned without further +// investigation. +func Cause(err error) error { + type causer interface { + Cause() error + } + + for err != nil { + cause, ok := err.(causer) + if !ok { + break + } + err = cause.Cause() + } + return err +} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go new file mode 100644 index 00000000000..6b1f2891a5a --- /dev/null +++ b/vendor/github.com/pkg/errors/stack.go @@ -0,0 +1,178 @@ +package errors + +import ( + "fmt" + "io" + "path" + "runtime" + "strings" +) + +// Frame represents a program counter inside a stack frame. +type Frame uintptr + +// pc returns the program counter for this frame; +// multiple frames may have the same PC value. +func (f Frame) pc() uintptr { return uintptr(f) - 1 } + +// file returns the full path to the file that contains the +// function for this Frame's pc. +func (f Frame) file() string { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return "unknown" + } + file, _ := fn.FileLine(f.pc()) + return file +} + +// line returns the line number of source code of the +// function for this Frame's pc. +func (f Frame) line() int { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return 0 + } + _, line := fn.FileLine(f.pc()) + return line +} + +// Format formats the frame according to the fmt.Formatter interface. +// +// %s source file +// %d source line +// %n function name +// %v equivalent to %s:%d +// +// Format accepts flags that alter the printing of some verbs, as follows: +// +// %+s path of source file relative to the compile time GOPATH +// %+v equivalent to %+s:%d +func (f Frame) Format(s fmt.State, verb rune) { + switch verb { + case 's': + switch { + case s.Flag('+'): + pc := f.pc() + fn := runtime.FuncForPC(pc) + if fn == nil { + io.WriteString(s, "unknown") + } else { + file, _ := fn.FileLine(pc) + fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file) + } + default: + io.WriteString(s, path.Base(f.file())) + } + case 'd': + fmt.Fprintf(s, "%d", f.line()) + case 'n': + name := runtime.FuncForPC(f.pc()).Name() + io.WriteString(s, funcname(name)) + case 'v': + f.Format(s, 's') + io.WriteString(s, ":") + f.Format(s, 'd') + } +} + +// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). +type StackTrace []Frame + +func (st StackTrace) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + switch { + case s.Flag('+'): + for _, f := range st { + fmt.Fprintf(s, "\n%+v", f) + } + case s.Flag('#'): + fmt.Fprintf(s, "%#v", []Frame(st)) + default: + fmt.Fprintf(s, "%v", []Frame(st)) + } + case 's': + fmt.Fprintf(s, "%s", []Frame(st)) + } +} + +// stack represents a stack of program counters. +type stack []uintptr + +func (s *stack) Format(st fmt.State, verb rune) { + switch verb { + case 'v': + switch { + case st.Flag('+'): + for _, pc := range *s { + f := Frame(pc) + fmt.Fprintf(st, "\n%+v", f) + } + } + } +} + +func (s *stack) StackTrace() StackTrace { + f := make([]Frame, len(*s)) + for i := 0; i < len(f); i++ { + f[i] = Frame((*s)[i]) + } + return f +} + +func callers() *stack { + const depth = 32 + var pcs [depth]uintptr + n := runtime.Callers(3, pcs[:]) + var st stack = pcs[0:n] + return &st +} + +// funcname removes the path prefix component of a function's name reported by func.Name(). +func funcname(name string) string { + i := strings.LastIndex(name, "/") + name = name[i+1:] + i = strings.Index(name, ".") + return name[i+1:] +} + +func trimGOPATH(name, file string) string { + // Here we want to get the source file path relative to the compile time + // GOPATH. As of Go 1.6.x there is no direct way to know the compiled + // GOPATH at runtime, but we can infer the number of path segments in the + // GOPATH. We note that fn.Name() returns the function name qualified by + // the import path, which does not include the GOPATH. Thus we can trim + // segments from the beginning of the file path until the number of path + // separators remaining is one more than the number of path separators in + // the function name. For example, given: + // + // GOPATH /home/user + // file /home/user/src/pkg/sub/file.go + // fn.Name() pkg/sub.Type.Method + // + // We want to produce: + // + // pkg/sub/file.go + // + // From this we can easily see that fn.Name() has one less path separator + // than our desired output. We count separators from the end of the file + // path until it finds two more than in the function name and then move + // one character forward to preserve the initial path segment without a + // leading separator. + const sep = "/" + goal := strings.Count(name, sep) + 2 + i := len(file) + for n := 0; n < goal; n++ { + i = strings.LastIndex(file[:i], sep) + if i == -1 { + // not enough separators found, set i so that the slice expression + // below leaves file unmodified + i = -len(sep) + break + } + } + // get back to 0 or trim the leading separator + file = file[i+len(sep):] + return file +}