diff --git a/chunker/chunk.go b/chunker/chunk.go index 53a299bf39a..e33a298e30a 100644 --- a/chunker/chunk.go +++ b/chunker/chunk.go @@ -21,7 +21,6 @@ import ( "bytes" "compress/gzip" encjson "encoding/json" - "fmt" "io" "net/http" "os" @@ -155,7 +154,7 @@ func (jsonChunker) Begin(r *bufio.Reader) error { return err } if ch != '[' { - return fmt.Errorf("JSON file must contain array. Found: %v", ch) + return errors.Errorf("JSON file must contain array. Found: %v", ch) } return nil } @@ -178,7 +177,7 @@ func (jsonChunker) Chunk(r *bufio.Reader) (*bytes.Buffer, error) { // Handle loading an empty JSON array ("[]") without error. return nil, io.EOF } else if ch != '{' { - return nil, fmt.Errorf("Expected JSON map start. Found: %v", string(ch)) + return nil, errors.Errorf("Expected JSON map start. Found: %v", string(ch)) } x.Check2(out.WriteRune(ch)) diff --git a/chunker/json/parse.go b/chunker/json/parse.go index 034d36a2452..0947d32a2f3 100644 --- a/chunker/json/parse.go +++ b/chunker/json/parse.go @@ -420,7 +420,7 @@ func Parse(b []byte, op int) ([]*api.NQuad, error) { } if len(list) == 0 && len(ms) == 0 { - return nil, fmt.Errorf("Couldn't parse json as a map or an array") + return nil, errors.Errorf("Couldn't parse json as a map or an array") } var idx int diff --git a/compose/compose.go b/compose/compose.go index b46e7c96f2d..7022bd79694 100644 --- a/compose/compose.go +++ b/compose/compose.go @@ -371,26 +371,26 @@ func main() { // Do some sanity checks. if opts.NumZeros < 1 || opts.NumZeros > 99 { - fatal(fmt.Errorf("number of zeros must be 1-99")) + fatal(errors.Errorf("number of zeros must be 1-99")) } if opts.NumAlphas < 1 || opts.NumAlphas > 99 { - fatal(fmt.Errorf("number of alphas must be 1-99")) + fatal(errors.Errorf("number of alphas must be 1-99")) } if opts.NumReplicas%2 == 0 { - fatal(fmt.Errorf("number of replicas must be odd")) + fatal(errors.Errorf("number of replicas must be odd")) } if opts.LruSizeMB < 1024 { - fatal(fmt.Errorf("LRU cache size must be >= 1024 MB")) + fatal(errors.Errorf("LRU cache size must be >= 1024 MB")) } if opts.AclSecret != "" && !opts.Enterprise { warning("adding --enterprise because it is required by ACL feature") opts.Enterprise = true } if opts.DataVol && opts.DataDir != "" { - fatal(fmt.Errorf("only one of --data_vol and --data_dir may be used at a time")) + fatal(errors.Errorf("only one of --data_vol and --data_dir may be used at a time")) } if opts.UserOwnership && opts.DataDir == "" { - fatal(fmt.Errorf("--user option requires --data_dir=")) + fatal(errors.Errorf("--user option requires --data_dir=")) } services := make(map[string]service) @@ -437,7 +437,7 @@ func main() { _, _ = fmt.Fprintf(os.Stderr, "Writing file: %s\n", opts.OutFile) err = ioutil.WriteFile(opts.OutFile, []byte(doc), 0644) if err != nil { - fatal(fmt.Errorf("unable to write file: %v", err)) + fatal(errors.Errorf("unable to write file: %v", err)) } } } diff --git a/conn/pool.go b/conn/pool.go index dcaeaa743fa..c7cfb410a79 100644 --- a/conn/pool.go +++ b/conn/pool.go @@ -18,7 +18,6 @@ package conn import ( "context" - "fmt" "sync" "time" @@ -27,6 +26,7 @@ import ( "github.com/dgraph-io/dgraph/protos/pb" "github.com/dgraph-io/dgraph/x" "github.com/golang/glog" + "github.com/pkg/errors" "go.opencensus.io/plugin/ocgrpc" "google.golang.org/grpc" @@ -34,9 +34,9 @@ import ( var ( // ErrNoConnection indicates no connection exists to a node. - ErrNoConnection = fmt.Errorf("No connection exists") + ErrNoConnection = errors.New("No connection exists") // ErrUnhealthyConnection indicates the connection to a node is unhealthy. - ErrUnhealthyConnection = fmt.Errorf("Unhealthy connection") + ErrUnhealthyConnection = errors.New("Unhealthy connection") echoDuration = 500 * time.Millisecond ) diff --git a/contrib/embargo/main.go b/contrib/embargo/main.go index c285f224d21..ac15da0635b 100644 --- a/contrib/embargo/main.go +++ b/contrib/embargo/main.go @@ -10,6 +10,8 @@ import ( "os/exec" "strings" "time" + + "github.com/pkg/errors" ) var ctxb = context.Background() @@ -56,7 +58,7 @@ func increment(atLeast int, args string) error { } } if ok < atLeast { - return fmt.Errorf("Increment with atLeast=%d failed. OK: %d", atLeast, ok) + return errors.Errorf("Increment with atLeast=%d failed. OK: %d", atLeast, ok) } dur := time.Since(start).Round(time.Millisecond) fmt.Printf("\n[%v] ===> TIME taken to converge %d alphas: %s\n\n", @@ -76,7 +78,7 @@ func getStatus(zero string) error { output := out.String() if strings.Contains(output, "errors") { fmt.Printf("ERROR. Status at %s. Output:\n%s\n", zero, output) - return fmt.Errorf(output) + return errors.Errorf(output) } // var m map[string]interface{} // if err := json.Unmarshal([]byte(output), &m); err != nil { diff --git a/dgraph/cmd/alpha/http.go b/dgraph/cmd/alpha/http.go index 5f3ec5839de..080ff55d9be 100644 --- a/dgraph/cmd/alpha/http.go +++ b/dgraph/cmd/alpha/http.go @@ -21,7 +21,6 @@ import ( "compress/gzip" "context" "encoding/json" - "fmt" "io" "io/ioutil" "net/http" @@ -106,7 +105,7 @@ func parseUint64(r *http.Request, name string) (uint64, error) { uintVal, err := strconv.ParseUint(value, 0, 64) if err != nil { - return 0, fmt.Errorf("Error: %+v while parsing %s as uint64", err, name) + return 0, errors.Wrapf(err, "while parsing %s as uint64", name) } return uintVal, nil @@ -122,7 +121,7 @@ func parseBool(r *http.Request, name string) (bool, error) { boolval, err := strconv.ParseBool(value) if err != nil { - return false, fmt.Errorf("Error: %+v while parsing %s as bool", err, name) + return false, errors.Wrapf(err, "while parsing %s as bool", name) } return boolval, nil @@ -138,7 +137,7 @@ func parseDuration(r *http.Request, name string) (time.Duration, error) { durationValue, err := time.ParseDuration(value) if err != nil { - return 0, fmt.Errorf("Error: %+v while parsing %s as time.Duration", err, name) + return 0, errors.Wrapf(err, "while parsing %s as time.Duration", name) } return durationValue, nil diff --git a/dgraph/cmd/alpha/http_test.go b/dgraph/cmd/alpha/http_test.go index c11c3791a4e..a9a2808eb3c 100644 --- a/dgraph/cmd/alpha/http_test.go +++ b/dgraph/cmd/alpha/http_test.go @@ -20,7 +20,6 @@ import ( "bytes" "compress/gzip" "encoding/json" - "errors" "fmt" "io/ioutil" "net/http" @@ -31,6 +30,7 @@ import ( "testing" "time" + "github.com/pkg/errors" "github.com/stretchr/testify/require" "github.com/dgraph-io/dgraph/query" @@ -97,7 +97,7 @@ func queryWithGz(queryText, contentType, debug, timeout string, gzReq, gzResp bo return "", nil, err } if status := resp.StatusCode; status != http.StatusOK { - return "", nil, fmt.Errorf("Unexpected status code: %v", status) + return "", nil, errors.Errorf("Unexpected status code: %v", status) } defer resp.Body.Close() @@ -110,7 +110,7 @@ func queryWithGz(queryText, contentType, debug, timeout string, gzReq, gzResp bo } defer rd.Close() } else { - return "", resp, fmt.Errorf("Response not compressed") + return "", resp, errors.Errorf("Response not compressed") } } body, err := ioutil.ReadAll(rd) @@ -233,13 +233,13 @@ func runRequest(req *http.Request) (*x.QueryResWithData, []byte, error) { return nil, nil, err } if status := resp.StatusCode; status != http.StatusOK { - return nil, nil, fmt.Errorf("Unexpected status code: %v", status) + return nil, nil, errors.Errorf("Unexpected status code: %v", status) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { - return nil, nil, fmt.Errorf("unable to read from body: %v", err) + return nil, nil, errors.Errorf("unable to read from body: %v", err) } qr := new(x.QueryResWithData) diff --git a/dgraph/cmd/alpha/run.go b/dgraph/cmd/alpha/run.go index 5ec5b442cd6..872c8fc8a7e 100644 --- a/dgraph/cmd/alpha/run.go +++ b/dgraph/cmd/alpha/run.go @@ -43,6 +43,7 @@ import ( "github.com/dgraph-io/dgraph/x" "github.com/golang/glog" + "github.com/pkg/errors" "github.com/spf13/cast" "github.com/spf13/cobra" "go.opencensus.io/plugin/ocgrpc" @@ -219,7 +220,7 @@ func getIPsFromString(str string) ([]x.IPRange, error) { } else { ipAddrs, err := net.LookupIP(s) if err != nil { - return nil, fmt.Errorf("invalid IP address or hostname: %s", s) + return nil, errors.Errorf("invalid IP address or hostname: %s", s) } for _, addr := range ipAddrs { @@ -230,7 +231,7 @@ func getIPsFromString(str string) ([]x.IPRange, error) { // string is CIDR block like 192.168.0.0/16 or fd03:b188:0f3c:9ec4::/64 rangeLo, network, err := net.ParseCIDR(s) if err != nil { - return nil, fmt.Errorf("invalid CIDR block: %s", s) + return nil, errors.Errorf("invalid CIDR block: %s", s) } addrLen, maskLen := len(rangeLo), len(network.Mask) @@ -247,15 +248,15 @@ func getIPsFromString(str string) ([]x.IPRange, error) { rangeLo := net.ParseIP(tuple[0]) rangeHi := net.ParseIP(tuple[1]) if rangeLo == nil { - return nil, fmt.Errorf("invalid IP address: %s", tuple[0]) + return nil, errors.Errorf("invalid IP address: %s", tuple[0]) } else if rangeHi == nil { - return nil, fmt.Errorf("invalid IP address: %s", tuple[1]) + return nil, errors.Errorf("invalid IP address: %s", tuple[1]) } else if bytes.Compare(rangeLo, rangeHi) > 0 { - return nil, fmt.Errorf("inverted IP address range: %s", s) + return nil, errors.Errorf("inverted IP address range: %s", s) } ipRanges = append(ipRanges, x.IPRange{Lower: rangeLo, Upper: rangeHi}) default: - return nil, fmt.Errorf("invalid IP address range: %s", s) + return nil, errors.Errorf("invalid IP address range: %s", s) } } diff --git a/dgraph/cmd/alpha/run_test.go b/dgraph/cmd/alpha/run_test.go index f19b4dfe66e..10f8a25fd7d 100644 --- a/dgraph/cmd/alpha/run_test.go +++ b/dgraph/cmd/alpha/run_test.go @@ -37,6 +37,7 @@ import ( "github.com/dgraph-io/dgraph/schema" "github.com/dgraph-io/dgraph/x" "github.com/dgraph-io/dgraph/z" + "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" @@ -144,7 +145,7 @@ func runJSONMutation(m string) error { func alterSchema(s string) error { _, _, err := runWithRetries("PUT", "", addr+"/alter", s) if err != nil { - return fmt.Errorf("error while running request with retries: %v", err) + return errors.Wrapf(err, "while running request with retries") } return nil } diff --git a/dgraph/cmd/cert/cert.go b/dgraph/cmd/cert/cert.go index 66404c3329a..bb78a08da74 100644 --- a/dgraph/cmd/cert/cert.go +++ b/dgraph/cmd/cert/cert.go @@ -23,12 +23,13 @@ import ( "crypto/x509/pkix" "encoding/hex" "encoding/pem" - "fmt" "math" "math/big" "net" "os" "time" + + "github.com/pkg/errors" ) const ( @@ -109,7 +110,7 @@ func (c *certConfig) generatePair(keyFile, certFile string) error { if c.parent == nil { c.parent = template } else if template.NotAfter.After(c.parent.NotAfter) { - return fmt.Errorf("--duration: certificate expiration date '%s' exceeds parent '%s'", + return errors.Errorf("--duration: certificate expiration date '%s' exceeds parent '%s'", template.NotAfter, c.parent.NotAfter) } @@ -173,7 +174,7 @@ func (c *certConfig) verifyCert(certFile string) error { _, err = cert.Verify(opts) if err != nil { - return fmt.Errorf("%s: verification failed: %s", certFile, err) + return errors.Wrapf(err, "%s: verification failed", certFile) } return nil diff --git a/dgraph/cmd/cert/create.go b/dgraph/cmd/cert/create.go index d68ee579a02..6ffbc1d7789 100644 --- a/dgraph/cmd/cert/create.go +++ b/dgraph/cmd/cert/create.go @@ -109,13 +109,13 @@ func readKey(keyFile string) (crypto.PrivateKey, error) { block, _ := pem.Decode(b) switch { case block == nil: - return nil, fmt.Errorf("Failed to read key block") + return nil, errors.Errorf("Failed to read key block") case block.Type == "EC PRIVATE KEY": return x509.ParseECPrivateKey(block.Bytes) case block.Type == "RSA PRIVATE KEY": return x509.ParsePKCS1PrivateKey(block.Bytes) } - return nil, fmt.Errorf("Unknown PEM type: %s", block.Type) + return nil, errors.Errorf("Unknown PEM type: %s", block.Type) } // readCert tries to read and decode the contents of a signed cert file. @@ -129,9 +129,9 @@ func readCert(certFile string) (*x509.Certificate, error) { block, _ := pem.Decode(b) switch { case block == nil: - return nil, fmt.Errorf("Failed to read cert block") + return nil, errors.Errorf("Failed to read cert block") case block.Type != "CERTIFICATE": - return nil, fmt.Errorf("Unknown PEM type: %s", block.Type) + return nil, errors.Errorf("Unknown PEM type: %s", block.Type) } return x509.ParseCertificate(block.Bytes) diff --git a/dgraph/cmd/cert/info.go b/dgraph/cmd/cert/info.go index a21cb831bc0..6be085e5190 100644 --- a/dgraph/cmd/cert/info.go +++ b/dgraph/cmd/cert/info.go @@ -75,7 +75,7 @@ func getFileInfo(file string) *certInfo { dnCommonNamePrefix, cert.Subject.CommonName) default: - info.err = fmt.Errorf("Unsupported certificate") + info.err = errors.Errorf("Unsupported certificate") return &info } @@ -91,7 +91,7 @@ func getFileInfo(file string) *certInfo { if file != defaultCACert { parent, err := readCert(defaultCACert) if err != nil { - info.err = fmt.Errorf("Could not read parent cert: %s", err) + info.err = errors.Wrapf(err, "could not read parent cert") return &info } if err := cert.CheckSignatureFrom(parent); err != nil { @@ -112,7 +112,7 @@ func getFileInfo(file string) *certInfo { info.commonName = dnCommonNamePrefix + " Client key" default: - info.err = fmt.Errorf("Unsupported key") + info.err = errors.Errorf("Unsupported key") return &info } @@ -136,7 +136,7 @@ func getFileInfo(file string) *certInfo { } default: - info.err = fmt.Errorf("Unsupported file") + info.err = errors.Errorf("Unsupported file") } return &info diff --git a/dgraph/cmd/counter/increment.go b/dgraph/cmd/counter/increment.go index 5fc5caf7420..a20c127c168 100644 --- a/dgraph/cmd/counter/increment.go +++ b/dgraph/cmd/counter/increment.go @@ -28,6 +28,7 @@ import ( "github.com/dgraph-io/dgo" "github.com/dgraph-io/dgo/protos/api" "github.com/dgraph-io/dgraph/x" + "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -80,7 +81,7 @@ func queryCounter(txn *dgo.Txn, pred string) (Counter, error) { query := fmt.Sprintf("{ q(func: has(%s)) { uid, val: %s }}", pred, pred) resp, err := txn.Query(ctx, query) if err != nil { - return counter, fmt.Errorf("Query error: %v", err) + return counter, errors.Wrapf(err, "while doing query") } // Total query latency is sum of encoding, parsing and processing latencies. diff --git a/dgraph/cmd/live/run.go b/dgraph/cmd/live/run.go index 251b064a2a0..1e8e500f9e9 100644 --- a/dgraph/cmd/live/run.go +++ b/dgraph/cmd/live/run.go @@ -22,7 +22,6 @@ import ( "compress/gzip" "context" "crypto/tls" - "errors" "fmt" "io" "io/ioutil" @@ -47,6 +46,7 @@ import ( "github.com/dgraph-io/dgraph/xidmap" "github.com/golang/glog" + "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -174,7 +174,7 @@ func (l *loader) processFile(ctx context.Context, filename string) error { if isJson { loadType = chunker.JsonFormat } else { - return fmt.Errorf("need --format=rdf or --format=json to load %s", filename) + return errors.Errorf("need --format=rdf or --format=json to load %s", filename) } } } @@ -333,7 +333,7 @@ func run() error { filesList := x.FindDataFiles(opt.dataFiles, []string{".rdf", ".rdf.gz", ".json", ".json.gz"}) totalFiles := len(filesList) if totalFiles == 0 { - return fmt.Errorf("No data files found in %s", opt.dataFiles) + return errors.Errorf("No data files found in %s", opt.dataFiles) } fmt.Printf("Found %d data file(s) to process\n", totalFiles) diff --git a/dgraph/cmd/migrate/dump.go b/dgraph/cmd/migrate/dump.go index d62a3cc66ed..9377c78ed81 100644 --- a/dgraph/cmd/migrate/dump.go +++ b/dgraph/cmd/migrate/dump.go @@ -21,6 +21,8 @@ import ( "database/sql" "fmt" "strings" + + "github.com/pkg/errors" ) // dumpMeta serves as the global knowledge oracle that stores @@ -55,7 +57,7 @@ func (m *dumpMeta) dumpSchema() error { for _, index := range createDgraphSchema(tableInfo) { _, err := m.schemaWriter.WriteString(index) if err != nil { - return fmt.Errorf("error while writing schema: %v", err) + return errors.Wrapf(err, "while writing schema") } } } @@ -69,14 +71,14 @@ func (m *dumpMeta) dumpTables() error { for table := range m.tableInfos { fmt.Printf("Dumping table %s\n", table) if err := m.dumpTable(table); err != nil { - return fmt.Errorf("error while dumping table %s: %v", table, err) + return errors.Wrapf(err, "while dumping table %s", table) } } for table := range m.tableInfos { fmt.Printf("Dumping table constraints %s\n", table) if err := m.dumpTableConstraints(table); err != nil { - return fmt.Errorf("error while dumping table %s: %v", table, err) + return errors.Wrapf(err, "while dumping table %s", table) } } @@ -215,7 +217,8 @@ func (m *dumpMeta) outputConstraints(row *sqlRow, tableInfo *sqlTable) { } foreignBlankNode := m.tableGuides[foreignTableName].valuesRecorder.getBlankNode(refLabel) m.outputPlainCell(row.blankNodeLabel, - getPredFromConstraint(tableInfo.tableName, separator, constraint), uidType, foreignBlankNode) + getPredFromConstraint(tableInfo.tableName, separator, constraint), uidType, + foreignBlankNode) } } diff --git a/dgraph/cmd/migrate/run.go b/dgraph/cmd/migrate/run.go index 63b6817a441..3d0128295f1 100644 --- a/dgraph/cmd/migrate/run.go +++ b/dgraph/cmd/migrate/run.go @@ -24,6 +24,7 @@ import ( "strings" "github.com/dgraph-io/dgraph/x" + "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -137,7 +138,7 @@ func checkFile(file string) error { text = strings.TrimSpace(text) if len(text) == 0 || strings.ToLower(text) == "n" { - return fmt.Errorf("not allowed to overwrite %s", file) + return errors.Errorf("not allowed to overwrite %s", file) } if strings.ToLower(text) == "y" { return nil @@ -169,10 +170,10 @@ func generateSchemaAndData(dumpMeta *dumpMeta, schemaOutput string, dataOutput s dumpMeta.schemaWriter = schemaWriter if err := dumpMeta.dumpSchema(); err != nil { - return fmt.Errorf("error while writing schema file: %v", err) + return errors.Wrapf(err, "while writing schema file") } if err := dumpMeta.dumpTables(); err != nil { - return fmt.Errorf("error while writing data file: %v", err) + return errors.Wrapf(err, "while writing data file") } return nil } diff --git a/dgraph/cmd/migrate/table_guide.go b/dgraph/cmd/migrate/table_guide.go index f59ca202932..464ab4546a2 100644 --- a/dgraph/cmd/migrate/table_guide.go +++ b/dgraph/cmd/migrate/table_guide.go @@ -22,6 +22,7 @@ import ( "strings" "github.com/go-sql-driver/mysql" + "github.com/pkg/errors" ) var separator = "." @@ -160,7 +161,7 @@ func getCstColumns(cst *fkConstraint) map[string]interface{} { func getValue(dataType dataType, value interface{}) (string, error) { if value == nil { - return "", fmt.Errorf("nil value found") + return "", errors.Errorf("nil value found") } switch dataType { @@ -168,19 +169,19 @@ func getValue(dataType dataType, value interface{}) (string, error) { return fmt.Sprintf("%s", value), nil case intType: if !value.(sql.NullInt64).Valid { - return "", fmt.Errorf("found invalid nullint") + return "", errors.Errorf("found invalid nullint") } intVal, _ := value.(sql.NullInt64).Value() return fmt.Sprintf("%v", intVal), nil case datetimeType: if !value.(mysql.NullTime).Valid { - return "", fmt.Errorf("found invalid nulltime") + return "", errors.Errorf("found invalid nulltime") } dateVal, _ := value.(mysql.NullTime).Value() return fmt.Sprintf("%v", dateVal), nil case floatType: if !value.(sql.NullFloat64).Valid { - return "", fmt.Errorf("found invalid nullfloat") + return "", errors.Errorf("found invalid nullfloat") } floatVal, _ := value.(sql.NullFloat64).Value() return fmt.Sprintf("%v", floatVal), nil diff --git a/dgraph/cmd/migrate/table_info.go b/dgraph/cmd/migrate/table_info.go index 3c1c042941a..d7053d7bdc9 100644 --- a/dgraph/cmd/migrate/table_info.go +++ b/dgraph/cmd/migrate/table_info.go @@ -22,6 +22,7 @@ import ( "strings" "github.com/dgraph-io/dgraph/x" + "github.com/pkg/errors" ) type keyType int @@ -131,8 +132,8 @@ COLUMNS where TABLE_NAME = "%s" AND TABLE_SCHEMA="%s" ORDER BY COLUMN_NAME`, tab */ var fieldName, dbType string if err := columns.Scan(&fieldName, &dbType); err != nil { - return nil, fmt.Errorf("unable to scan table description result for table %s: %v", - tableName, err) + return nil, errors.Wrapf(err, "unable to scan table description result for table %s", + tableName) } // TODO, should store the column data types into the table info as an array @@ -154,7 +155,7 @@ COLUMNS where TABLE_NAME = "%s" AND TABLE_SCHEMA="%s" ORDER BY COLUMN_NAME`, tab var indexName, columnName string err := indices.Scan(&indexName, &columnName) if err != nil { - return nil, fmt.Errorf("unable to scan index info for table %s: %v", tableName, err) + return nil, errors.Wrapf(err, "unable to scan index info for table %s", tableName) } switch indexName { case "PRIMARY": @@ -186,7 +187,7 @@ COLUMNS where TABLE_NAME = "%s" AND TABLE_SCHEMA="%s" ORDER BY COLUMN_NAME`, tab */ var col, constraintName, dstTable, dstCol string if err := fkeys.Scan(&col, &constraintName, &dstTable, &dstCol); err != nil { - return nil, fmt.Errorf("unable to scan usage info for table %s: %v", tableName, err) + return nil, errors.Wrapf(err, "unable to scan usage info for table %s", tableName) } table.dstTables[dstTable] = struct{}{} diff --git a/dgraph/cmd/migrate/utils.go b/dgraph/cmd/migrate/utils.go index 0fb08185b50..56480f6d859 100644 --- a/dgraph/cmd/migrate/utils.go +++ b/dgraph/cmd/migrate/utils.go @@ -25,6 +25,7 @@ import ( "strings" "github.com/go-sql-driver/mysql" + "github.com/pkg/errors" ) func getPool(user string, db string, password string) (*sql.DB, @@ -53,7 +54,7 @@ func showTables(pool *sql.DB, tableNames string) ([]string, error) { for rows.Next() { var table string if err := rows.Scan(&table); err != nil { - return nil, fmt.Errorf("error while scanning table name: %v", err) + return nil, errors.Wrapf(err, "while scanning table name") } tables = append(tables, table) } @@ -123,7 +124,7 @@ func getColumnValues(columns []string, dataTypes []dataType, } } if err := rows.Scan(valuePtrs...); err != nil { - return nil, fmt.Errorf("error while scanning column values: %v", err) + return nil, errors.Wrapf(err, "while scanning column values") } colValues := ptrToValues(valuePtrs) return colValues, nil diff --git a/dgraph/cmd/zero/tablet.go b/dgraph/cmd/zero/tablet.go index 3ccdad1d896..48ed324a208 100644 --- a/dgraph/cmd/zero/tablet.go +++ b/dgraph/cmd/zero/tablet.go @@ -134,7 +134,7 @@ func (s *Server) movePredicate(predicate string, srcGroup, dstGroup uint32) erro span.Annotatef(nil, "Starting move: %+v", in) glog.Infof("Starting move: %+v", in) if _, err := wc.MovePredicate(ctx, in); err != nil { - return fmt.Errorf("While calling MovePredicate: %+v\n", err) + return errors.Wrapf(err, "while calling MovePredicate") } p := &pb.ZeroProposal{} diff --git a/edgraph/access_ee.go b/edgraph/access_ee.go index 93784f2422d..59a9587774d 100644 --- a/edgraph/access_ee.go +++ b/edgraph/access_ee.go @@ -57,7 +57,7 @@ func (s *Server) Login(ctx context.Context, if err != nil { errMsg := fmt.Sprintf("Authentication from address %s failed: %v", addr, err) glog.Errorf(errMsg) - return nil, fmt.Errorf(errMsg) + return nil, errors.Errorf(errMsg) } resp := &api.Response{} @@ -66,14 +66,14 @@ func (s *Server) Login(ctx context.Context, errMsg := fmt.Sprintf("unable to get access jwt (userid=%s,addr=%s):%v", user.UserID, addr, err) glog.Errorf(errMsg) - return nil, fmt.Errorf(errMsg) + return nil, errors.Errorf(errMsg) } refreshJwt, err := getRefreshJwt(user.UserID) if err != nil { errMsg := fmt.Sprintf("unable to get refresh jwt (userid=%s,addr=%s):%v", user.UserID, addr, err) glog.Errorf(errMsg) - return nil, fmt.Errorf(errMsg) + return nil, errors.Errorf(errMsg) } loginJwt := api.Jwt{ @@ -86,7 +86,7 @@ func (s *Server) Login(ctx context.Context, errMsg := fmt.Sprintf("unable to marshal jwt (userid=%s,addr=%s):%v", user.UserID, addr, err) glog.Errorf(errMsg) - return nil, fmt.Errorf(errMsg) + return nil, errors.Errorf(errMsg) } resp.Json = jwtBytes return resp, nil @@ -98,25 +98,25 @@ func (s *Server) Login(ctx context.Context, func (s *Server) authenticateLogin(ctx context.Context, request *api.LoginRequest) (*acl.User, error) { if err := validateLoginRequest(request); err != nil { - return nil, fmt.Errorf("invalid login request: %v", err) + return nil, errors.Wrapf(err, "invalid login request") } var user *acl.User if len(request.RefreshToken) > 0 { userData, err := validateToken(request.RefreshToken) if err != nil { - return nil, fmt.Errorf("unable to authenticate the refresh token %v: %v", - request.RefreshToken, err) + return nil, errors.Wrapf(err, "unable to authenticate the refresh token %v", + request.RefreshToken) } userId := userData[0] user, err = authorizeUser(ctx, userId, "") if err != nil { - return nil, fmt.Errorf("error while querying user with id %v: %v", userId, err) + return nil, errors.Wrapf(err, "while querying user with id %v", userId) } if user == nil { - return nil, fmt.Errorf("unable to authenticate through refresh token: "+ + return nil, errors.Errorf("unable to authenticate through refresh token: "+ "user not found for id %v", userId) } @@ -128,16 +128,16 @@ func (s *Server) authenticateLogin(ctx context.Context, request *api.LoginReques var err error user, err = authorizeUser(ctx, request.Userid, request.Password) if err != nil { - return nil, fmt.Errorf("error while querying user with id %v: %v", - request.Userid, err) + return nil, errors.Wrapf(err, "while querying user with id %v", + request.Userid) } if user == nil { - return nil, fmt.Errorf("unable to authenticate through password: "+ + return nil, errors.Errorf("unable to authenticate through password: "+ "user not found for id %v", request.Userid) } if !user.PasswordMatch { - return nil, fmt.Errorf("password mismatch for user: %v", request.Userid) + return nil, errors.Errorf("password mismatch for user: %v", request.Userid) } return user, nil } @@ -148,30 +148,30 @@ func (s *Server) authenticateLogin(ctx context.Context, request *api.LoginReques func validateToken(jwtStr string) ([]string, error) { token, err := jwt.Parse(jwtStr, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { - return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + return nil, errors.Errorf("unexpected signing method: %v", token.Header["alg"]) } return Config.HmacSecret, nil }) if err != nil { - return nil, fmt.Errorf("unable to parse jwt token:%v", err) + return nil, errors.Errorf("unable to parse jwt token:%v", err) } claims, ok := token.Claims.(jwt.MapClaims) if !ok || !token.Valid { - return nil, fmt.Errorf("claims in jwt token is not map claims") + return nil, errors.Errorf("claims in jwt token is not map claims") } // by default, the MapClaims.Valid will return true if the exp field is not set // here we enforce the checking to make sure that the refresh token has not expired now := time.Now().Unix() if !claims.VerifyExpiresAt(now, true) { - return nil, fmt.Errorf("Token is expired") // the same error msg that's used inside jwt-go + return nil, errors.Errorf("Token is expired") // the same error msg that's used inside jwt-go } userId, ok := claims["userid"].(string) if !ok { - return nil, fmt.Errorf("userid in claims is not a string:%v", userId) + return nil, errors.Errorf("userid in claims is not a string:%v", userId) } groups, ok := claims["groups"].([]interface{}) @@ -182,7 +182,7 @@ func validateToken(jwtStr string) ([]string, error) { groupId, ok := group.(string) if !ok { // This shouldn't happen. So, no need to make the client try to refresh the tokens. - return nil, fmt.Errorf("unable to convert group to string:%v", group) + return nil, errors.Errorf("unable to convert group to string:%v", group) } groupIds = append(groupIds, groupId) @@ -195,7 +195,7 @@ func validateToken(jwtStr string) ([]string, error) { // pair func validateLoginRequest(request *api.LoginRequest) error { if request == nil { - return fmt.Errorf("the request should not be nil") + return errors.Errorf("the request should not be nil") } // we will use the refresh token for authentication if it's set if len(request.RefreshToken) > 0 { @@ -204,10 +204,10 @@ func validateLoginRequest(request *api.LoginRequest) error { // otherwise make sure both userid and password are set if len(request.Userid) == 0 { - return fmt.Errorf("the userid should not be empty") + return errors.Errorf("the userid should not be empty") } if len(request.Password) == 0 { - return fmt.Errorf("the password should not be empty") + return errors.Errorf("the password should not be empty") } return nil } @@ -224,7 +224,7 @@ func getAccessJwt(userId string, groups []acl.Group) (string, error) { jwtString, err := token.SignedString(Config.HmacSecret) if err != nil { - return "", fmt.Errorf("unable to encode jwt to string: %v", err) + return "", errors.Errorf("unable to encode jwt to string: %v", err) } return jwtString, nil } @@ -239,7 +239,7 @@ func getRefreshJwt(userId string) (string, error) { jwtString, err := token.SignedString(Config.HmacSecret) if err != nil { - return "", fmt.Errorf("unable to encode jwt to string: %v", err) + return "", errors.Errorf("unable to encode jwt to string: %v", err) } return jwtString, nil } @@ -306,7 +306,7 @@ func RefreshAcls(closer *y.Closer) { var err error queryResp, err := (&Server{}).doQuery(ctx, &queryRequest) if err != nil { - return fmt.Errorf("unable to retrieve acls: %v", err) + return errors.Errorf("unable to retrieve acls: %v", err) } groups, err := acl.UnmarshalGroups(queryResp.GetJson(), "allAcls") if err != nil { @@ -358,13 +358,13 @@ func ResetAcl() { queryResp, err := (&Server{}).doQuery(ctx, &queryRequest) if err != nil { - return fmt.Errorf("error while querying user with id %s: %v", x.GrootId, err) + return errors.Wrapf(err, "while querying user with id %s", x.GrootId) } startTs := queryResp.GetTxn().StartTs rootUser, err := acl.UnmarshalUser(queryResp, "user") if err != nil { - return fmt.Errorf("error while unmarshaling the root user: %v", err) + return errors.Wrapf(err, "while unmarshaling the root user") } if rootUser != nil { glog.Infof("The groot account already exists, no need to insert again") @@ -465,8 +465,8 @@ func authorizeAlter(ctx context.Context, op *api.Operation) error { // if we get here, we know the user is not Groot. if isDropAll(op) || op.DropOp == api.Operation_DATA { - return fmt.Errorf("only Groot is allowed to drop all data, but the current user is %s", - userId) + return errors.Errorf( + "only Groot is allowed to drop all data, but the current user is %s", userId) } for _, pred := range preds { @@ -565,7 +565,7 @@ func authorizeMutation(ctx context.Context, gmu *gql.Mutation) error { if userId == x.GrootId { // groot is allowed to mutate anything except the permission of the acl predicates if isAclPredMutation(gmu.Set) { - return fmt.Errorf("the permission of ACL predicates can not be changed") + return errors.Errorf("the permission of ACL predicates can not be changed") } return nil } diff --git a/edgraph/acl_cache.go b/edgraph/acl_cache.go index d166399868e..2a7633862a4 100644 --- a/edgraph/acl_cache.go +++ b/edgraph/acl_cache.go @@ -14,13 +14,13 @@ package edgraph import ( "encoding/json" - "fmt" "regexp" "sync" "github.com/dgraph-io/dgraph/ee/acl" "github.com/dgraph-io/dgraph/x" "github.com/golang/glog" + "github.com/pkg/errors" ) type predRegexRule struct { @@ -117,7 +117,7 @@ func (cache *aclCache) update(groups []acl.Group) { func (cache *aclCache) authorizePredicate(groups []string, predicate string, operation *acl.Operation) error { if x.IsAclPredicate(predicate) { - return fmt.Errorf("only groot is allowed to access the ACL predicate: %s", predicate) + return errors.Errorf("only groot is allowed to access the ACL predicate: %s", predicate) } aclCachePtr.RLock() @@ -145,7 +145,7 @@ func (cache *aclCache) authorizePredicate(groups []string, predicate string, if singlePredMatch || predRegexMatch { // there is an ACL rule defined that can match the predicate // and the operation has not been allowed - return fmt.Errorf("unauthorized to do %s on predicate %s", + return errors.Errorf("unauthorized to do %s on predicate %s", operation.Name, predicate) } diff --git a/edgraph/server.go b/edgraph/server.go index 4910c7d0d64..7d23a04ae52 100644 --- a/edgraph/server.go +++ b/edgraph/server.go @@ -318,7 +318,7 @@ func (s *Server) Alter(ctx context.Context, op *api.Operation) (*api.Payload, er m := &pb.Mutations{StartTs: State.getTimestamp(false)} if isDropAll(op) { if len(op.DropValue) > 0 { - return empty, fmt.Errorf("If DropOp is set to ALL, DropValue must be empty") + return empty, errors.Errorf("If DropOp is set to ALL, DropValue must be empty") } m.DropOp = pb.Mutations_ALL @@ -331,7 +331,7 @@ func (s *Server) Alter(ctx context.Context, op *api.Operation) (*api.Payload, er if op.DropOp == api.Operation_DATA { if len(op.DropValue) > 0 { - return empty, fmt.Errorf("If DropOp is set to DATA, DropValue must be empty") + return empty, errors.Errorf("If DropOp is set to DATA, DropValue must be empty") } m.DropOp = pb.Mutations_DATA @@ -344,7 +344,7 @@ func (s *Server) Alter(ctx context.Context, op *api.Operation) (*api.Payload, er if len(op.DropAttr) > 0 || op.DropOp == api.Operation_ATTR { if op.DropOp == api.Operation_ATTR && len(op.DropValue) == 0 { - return empty, fmt.Errorf("If DropOp is set to ATTR, DropValue must not be empty") + return empty, errors.Errorf("If DropOp is set to ATTR, DropValue must not be empty") } var attr string @@ -356,7 +356,7 @@ func (s *Server) Alter(ctx context.Context, op *api.Operation) (*api.Payload, er // Reserved predicates cannot be dropped. if x.IsReservedPredicate(attr) { - err := fmt.Errorf("predicate %s is reserved and is not allowed to be dropped", + err := errors.Errorf("predicate %s is reserved and is not allowed to be dropped", attr) return empty, err } @@ -379,7 +379,7 @@ func (s *Server) Alter(ctx context.Context, op *api.Operation) (*api.Payload, er if op.DropOp == api.Operation_TYPE { if len(op.DropValue) == 0 { - return empty, fmt.Errorf("If DropOp is set to TYPE, DropValue must not be empty") + return empty, errors.Errorf("If DropOp is set to TYPE, DropValue must not be empty") } m.DropOp = pb.Mutations_TYPE @@ -397,7 +397,7 @@ func (s *Server) Alter(ctx context.Context, op *api.Operation) (*api.Payload, er // Reserved predicates cannot be altered but let the update go through // if the update is equal to the existing one. if schema.IsReservedPredicateChanged(update.Predicate, update) { - err := fmt.Errorf("predicate %s is reserved and is not allowed to be modified", + err := errors.Errorf("predicate %s is reserved and is not allowed to be modified", update.Predicate) return nil, err } @@ -490,7 +490,7 @@ func (s *Server) doMutate(ctx context.Context, mu *api.Mutation, authorize bool) if len(gmu.Set) == 0 && len(gmu.Del) == 0 { span.Annotate(nil, "Empty mutation") - return resp, fmt.Errorf("Empty mutation") + return resp, errors.Errorf("Empty mutation") } if mu.StartTs == 0 { @@ -596,7 +596,7 @@ func doQueryInUpsert(ctx context.Context, mu *api.Mutation, gmu *gql.Mutation) ( } if len(qr.Vars) <= 0 { - return nil, fmt.Errorf("upsert query block has no variables") + return nil, errors.Errorf("upsert query block has no variables") } // TODO(Aman): allow multiple values for each variable. @@ -607,7 +607,7 @@ func doQueryInUpsert(ctx context.Context, mu *api.Mutation, gmu *gql.Mutation) ( continue } if len(v.Uids.Uids) > 1 { - return nil, fmt.Errorf("more than one values found for var (%s)", name) + return nil, errors.Errorf("more than one values found for var (%s)", name) } else if len(v.Uids.Uids) == 1 { varToUID[name] = fmt.Sprintf("%d", v.Uids.Uids[0]) } @@ -731,7 +731,7 @@ func (s *Server) doQuery(ctx context.Context, req *api.Request) (resp *api.Respo resp = &api.Response{} if len(req.Query) == 0 { span.Annotate(nil, "Empty query") - return resp, fmt.Errorf("Empty query") + return resp, errors.Errorf("Empty query") } var l query.Latency @@ -834,7 +834,7 @@ func (s *Server) CommitOrAbort(ctx context.Context, tc *api.TxnContext) (*api.Tx tctx := &api.TxnContext{} if tc.StartTs == 0 { - return &api.TxnContext{}, fmt.Errorf( + return &api.TxnContext{}, errors.Errorf( "StartTs cannot be zero while committing a transaction") } annotateStartTs(span, tc.StartTs) @@ -1065,7 +1065,7 @@ func validateQuery(queries []*gql.GraphQuery) error { func validatePredName(name string) error { if len(name) > math.MaxUint16 { - return fmt.Errorf("Predicate name length cannot be bigger than 2^16. Predicate: %v", + return errors.Errorf("Predicate name length cannot be bigger than 2^16. Predicate: %v", name[:80]) } return nil diff --git a/ee/acl/acl.go b/ee/acl/acl.go index 54c062ab214..6715ceff8a5 100644 --- a/ee/acl/acl.go +++ b/ee/acl/acl.go @@ -24,6 +24,7 @@ import ( "github.com/dgraph-io/dgo/protos/api" "github.com/dgraph-io/dgraph/x" "github.com/golang/glog" + "github.com/pkg/errors" "github.com/spf13/viper" ) @@ -32,7 +33,7 @@ func getUserAndGroup(conf *viper.Viper) (userId string, groupId string, err erro groupId = conf.GetString("group") if (len(userId) == 0 && len(groupId) == 0) || (len(userId) != 0 && len(groupId) != 0) { - return "", "", fmt.Errorf("one of the --user or --group must be specified, but not both") + return "", "", errors.Errorf("one of the --user or --group must be specified, but not both") } return userId, groupId, nil } @@ -53,10 +54,10 @@ func checkForbiddenOpts(conf *viper.Viper, forbiddenOpts []string) error { case bool: isSet = conf.GetBool(opt) default: - return fmt.Errorf("unexpected option type for %s", opt) + return errors.Errorf("unexpected option type for %s", opt) } if isSet { - return fmt.Errorf("the option --%s should not be set", opt) + return errors.Errorf("the option --%s should not be set", opt) } } @@ -83,7 +84,7 @@ func add(conf *viper.Viper) error { func userAdd(conf *viper.Viper, userid string, password string) error { dc, cancel, err := getClientWithAdminCtx(conf) if err != nil { - return fmt.Errorf("unable to get admin context:%v", err) + return errors.Wrapf(err, "unable to get admin context") } defer cancel() @@ -106,10 +107,10 @@ func userAdd(conf *viper.Viper, userid string, password string) error { user, err := queryUser(ctx, txn, userid) if err != nil { - return fmt.Errorf("error while querying user:%v", err) + return errors.Wrapf(err, "while querying user") } if user != nil { - return fmt.Errorf("unable to create user because of conflict: %v", userid) + return errors.Errorf("unable to create user because of conflict: %v", userid) } createUserNQuads := CreateUserNQuads(userid, password) @@ -120,7 +121,7 @@ func userAdd(conf *viper.Viper, userid string, password string) error { } if _, err := txn.Mutate(ctx, mu); err != nil { - return fmt.Errorf("unable to create user: %v", err) + return errors.Wrapf(err, "unable to create user") } fmt.Printf("Created new user with id %v\n", userid) @@ -130,7 +131,7 @@ func userAdd(conf *viper.Viper, userid string, password string) error { func groupAdd(conf *viper.Viper, groupId string) error { dc, cancel, err := getClientWithAdminCtx(conf) if err != nil { - return fmt.Errorf("unable to get admin context: %v", err) + return errors.Wrapf(err, "unable to get admin context") } defer cancel() @@ -145,10 +146,10 @@ func groupAdd(conf *viper.Viper, groupId string) error { group, err := queryGroup(ctx, txn, groupId) if err != nil { - return fmt.Errorf("error while querying group: %v", err) + return errors.Wrapf(err, "while querying group") } if group != nil { - return fmt.Errorf("group %q already exists", groupId) + return errors.Errorf("group %q already exists", groupId) } createGroupNQuads := []*api.NQuad{ @@ -169,7 +170,7 @@ func groupAdd(conf *viper.Viper, groupId string) error { Set: createGroupNQuads, } if _, err = txn.Mutate(ctx, mu); err != nil { - return fmt.Errorf("unable to create group: %v", err) + return errors.Wrapf(err, "unable to create group") } fmt.Printf("Created new group with id %v\n", groupId) @@ -208,7 +209,7 @@ func userOrGroupDel(conf *viper.Viper, userOrGroupId string, queryFn func(context.Context, *dgo.Txn, string) (AclEntity, error)) error { dc, cancel, err := getClientWithAdminCtx(conf) if err != nil { - return fmt.Errorf("unable to get admin context:%v", err) + return errors.Wrapf(err, "unable to get admin context") } defer cancel() @@ -226,7 +227,7 @@ func userOrGroupDel(conf *viper.Viper, userOrGroupId string, return err } if len(entity.GetUid()) == 0 { - return fmt.Errorf("unable to delete %q since it does not exist", + return errors.Errorf("unable to delete %q since it does not exist", userOrGroupId) } @@ -243,7 +244,7 @@ func userOrGroupDel(conf *viper.Viper, userOrGroupId string, } if _, err = txn.Mutate(ctx, mu); err != nil { - return fmt.Errorf("unable to delete %q: %v", userOrGroupId, err) + return errors.Wrapf(err, "unable to delete %q", userOrGroupId) } fmt.Printf("Successfully deleted %q\n", userOrGroupId) @@ -266,7 +267,8 @@ func mod(conf *viper.Viper) error { groupList := conf.GetString("group_list") if (newPassword && groupList != defaultGroupList) || (!newPassword && groupList == defaultGroupList) { - return fmt.Errorf("one of --new_password or --group_list must be provided, but not both") + return errors.Errorf( + "one of --new_password or --group_list must be provided, but not both") } if newPassword { @@ -288,7 +290,7 @@ func changePassword(conf *viper.Viper, userId string) error { // 1. get the dgo client with appropriate access JWT dc, cancel, err := getClientWithAdminCtx(conf) if err != nil { - return fmt.Errorf("unable to get dgo client:%v", err) + return errors.Wrapf(err, "unable to get dgo client") } defer cancel() @@ -310,10 +312,10 @@ func changePassword(conf *viper.Viper, userId string) error { // 3. query the user's current uid user, err := queryUser(ctx, txn, userId) if err != nil { - return fmt.Errorf("error while querying user:%v", err) + return errors.Wrapf(err, "while querying user") } if user == nil { - return fmt.Errorf("user %q does not exist", userId) + return errors.Errorf("user %q does not exist", userId) } // 4. mutate the user's password @@ -328,7 +330,7 @@ func changePassword(conf *viper.Viper, userId string) error { Set: chPdNQuads, } if _, err := txn.Mutate(ctx, mu); err != nil { - return fmt.Errorf("unable to change password for user %v: %v", userId, err) + return errors.Wrapf(err, "unable to change password for user %v", userId) } fmt.Printf("Successfully changed password for %v\n", userId) return nil @@ -337,7 +339,7 @@ func changePassword(conf *viper.Viper, userId string) error { func userMod(conf *viper.Viper, userId string, groups string) error { dc, cancel, err := getClientWithAdminCtx(conf) if err != nil { - return fmt.Errorf("unable to get admin context:%v", err) + return errors.Wrapf(err, "unable to get admin context") } defer cancel() @@ -352,10 +354,10 @@ func userMod(conf *viper.Viper, userId string, groups string) error { user, err := queryUser(ctx, txn, userId) if err != nil { - return fmt.Errorf("error while querying user: %v", err) + return errors.Wrapf(err, "while querying user") } if user == nil { - return fmt.Errorf("user %q does not exist", userId) + return errors.Errorf("user %q does not exist", userId) } targetGroupsMap := make(map[string]struct{}) @@ -400,7 +402,7 @@ func userMod(conf *viper.Viper, userId string, groups string) error { } if _, err := txn.Mutate(ctx, mu); err != nil { - return fmt.Errorf("error while mutating the group: %+v", err) + return errors.Wrapf(err, "while mutating the group") } fmt.Printf("Successfully modified groups for user %v.\n", userId) fmt.Println("The latest info is:") @@ -414,25 +416,25 @@ func chMod(conf *viper.Viper) error { perm := conf.GetInt("perm") switch { case len(groupId) == 0: - return fmt.Errorf("the groupid must not be empty") + return errors.Errorf("the groupid must not be empty") case len(predicate) > 0 && len(predRegex) > 0: - return fmt.Errorf("one of --pred or --pred_regex must be specified, but not both") + return errors.Errorf("one of --pred or --pred_regex must be specified, but not both") case len(predicate) == 0 && len(predRegex) == 0: - return fmt.Errorf("one of --pred or --pred_regex must be specified, but not both") + return errors.Errorf("one of --pred or --pred_regex must be specified, but not both") case perm > 7: - return fmt.Errorf("the perm value must be less than or equal to 7, "+ + return errors.Errorf("the perm value must be less than or equal to 7, "+ "the provided value is %d", perm) case len(predRegex) > 0: // make sure the predRegex can be compiled as a regex if _, err := regexp.Compile(predRegex); err != nil { - return fmt.Errorf("unable to compile %v as a regular expression: %v", - predRegex, err) + return errors.Wrapf(err, "unable to compile %v as a regular expression", + predRegex) } } dc, cancel, err := getClientWithAdminCtx(conf) if err != nil { - return fmt.Errorf("unable to get admin context: %v", err) + return errors.Wrapf(err, "unable to get admin context") } defer cancel() @@ -447,18 +449,18 @@ func chMod(conf *viper.Viper) error { group, err := queryGroup(ctx, txn, groupId, "dgraph.group.acl") if err != nil { - return fmt.Errorf("error while querying group: %v\n", err) + return errors.Wrapf(err, "while querying group") } if group == nil || len(group.Uid) == 0 { - return fmt.Errorf("unable to change permission for group because it does not exist: %v", + return errors.Errorf("unable to change permission for group because it does not exist: %v", groupId) } var currentAcls []Acl if len(group.Acls) != 0 { if err := json.Unmarshal([]byte(group.Acls), ¤tAcls); err != nil { - return fmt.Errorf("unable to unmarshal the acls associated with the group %v: %v", - groupId, err) + return errors.Wrapf(err, "unable to unmarshal the acls associated with the group %v", + groupId) } } @@ -482,7 +484,7 @@ func chMod(conf *viper.Viper) error { newAclBytes, err := json.Marshal(newAcls) if err != nil { - return fmt.Errorf("unable to marshal the updated acls: %v", err) + return errors.Wrapf(err, "unable to marshal the updated acls") } chModNQuads := &api.NQuad{ @@ -496,8 +498,8 @@ func chMod(conf *viper.Viper) error { } if _, err = txn.Mutate(ctx, mu); err != nil { - return fmt.Errorf("unable to change mutations for the group %v on predicate %v: %v", - groupId, predicate, err) + return errors.Wrapf(err, "unable to change mutations for the group %v on predicate %v", + groupId, predicate) } fmt.Printf("Successfully changed permission for group %v on predicate %v to %v\n", groupId, predicate, perm) @@ -523,7 +525,7 @@ func queryUser(ctx context.Context, txn *dgo.Txn, userid string) (user *User, er queryResp, err := txn.QueryWithVars(ctx, query, queryVars) if err != nil { - return nil, fmt.Errorf("error while query user with id %s: %v", userid, err) + return nil, errors.Wrapf(err, "hile query user with id %s", userid) } user, err = UnmarshalUser(queryResp, "user") if err != nil { @@ -539,7 +541,7 @@ func getUserModNQuad(ctx context.Context, txn *dgo.Txn, userId string, return nil, err } if group == nil { - return nil, fmt.Errorf("group %q does not exist", groupId) + return nil, errors.Errorf("group %q does not exist", groupId) } createUserGroupNQuads := &api.NQuad{ @@ -610,7 +612,7 @@ func queryAndPrintUser(ctx context.Context, txn *dgo.Txn, userId string) error { return err } if user == nil { - return fmt.Errorf("The user %q does not exist.\n", userId) + return errors.Errorf("The user %q does not exist.\n", userId) } fmt.Printf("User : %s\n", userId) @@ -628,7 +630,7 @@ func queryAndPrintGroup(ctx context.Context, txn *dgo.Txn, groupId string) error return err } if group == nil { - return fmt.Errorf("The group %q does not exist.\n", groupId) + return errors.Errorf("The group %q does not exist.\n", groupId) } fmt.Printf("Group: %s\n", groupId) fmt.Printf("UID : %s\n", group.Uid) @@ -643,8 +645,8 @@ func queryAndPrintGroup(ctx context.Context, txn *dgo.Txn, groupId string) error var acls []Acl if len(group.Acls) != 0 { if err := json.Unmarshal([]byte(group.Acls), &acls); err != nil { - return fmt.Errorf("unable to unmarshal the acls associated with the group %v: %v", - groupId, err) + return errors.Wrapf(err, "unable to unmarshal the acls associated with the group %v", + groupId) } for _, acl := range acls { @@ -663,7 +665,7 @@ func info(conf *viper.Viper) error { dc, cancel, err := getClientWithAdminCtx(conf) defer cancel() if err != nil { - return fmt.Errorf("unable to get admin context: %v\n", err) + return errors.Wrapf(err, "unable to get admin context") } ctx, ctxCancel := context.WithTimeout(context.Background(), 10*time.Second) diff --git a/ee/acl/utils.go b/ee/acl/utils.go index f39e3b9fa6d..fd412cca11a 100644 --- a/ee/acl/utils.go +++ b/ee/acl/utils.go @@ -14,7 +14,6 @@ package acl import ( "encoding/json" - "fmt" "github.com/dgraph-io/dgo" "github.com/dgraph-io/dgo/protos/api" @@ -137,7 +136,7 @@ func UnmarshalGroup(input []byte, groupKey string) (group *Group, err error) { return nil, nil } if len(groups) > 1 { - return nil, fmt.Errorf("found multiple groups: %s", input) + return nil, errors.Errorf("found multiple groups: %s", input) } return &groups[0], nil diff --git a/gql/mutation.go b/gql/mutation.go index 49c2395e335..a2044831999 100644 --- a/gql/mutation.go +++ b/gql/mutation.go @@ -17,7 +17,6 @@ package gql import ( - "fmt" "strconv" "github.com/dgraph-io/dgo/protos/api" @@ -168,7 +167,7 @@ func (nq NQuad) ToEdgeUsing(newToUid map[string]uint64) (*pb.DirectedEdge, error } if sUid == 0 { - return nil, fmt.Errorf("Subject should be > 0 for nquad: %+v", nq) + return nil, errors.Errorf("Subject should be > 0 for nquad: %+v", nq) } switch nq.valueType() { @@ -178,7 +177,7 @@ func (nq NQuad) ToEdgeUsing(newToUid map[string]uint64) (*pb.DirectedEdge, error return nil, err } if oUid == 0 { - return nil, fmt.Errorf("ObjectId should be > 0 for nquad: %+v", nq) + return nil, errors.Errorf("ObjectId should be > 0 for nquad: %+v", nq) } edge = nq.CreateUidEdge(sUid, oUid) case x.ValuePlain, x.ValueMulti: diff --git a/lex/iri.go b/lex/iri.go index 091a980ab5f..b8874635576 100644 --- a/lex/iri.go +++ b/lex/iri.go @@ -17,8 +17,7 @@ package lex import ( - "errors" - "fmt" + "github.com/pkg/errors" ) func IRIRef(l *Lexer, styp ItemType) error { @@ -30,7 +29,7 @@ func IRIRef(l *Lexer, styp ItemType) error { return errors.New("Unexpected end of IRI") } if r != '>' { - return fmt.Errorf("Unexpected character %q while parsing IRI", r) + return errors.Errorf("Unexpected character %q while parsing IRI", r) } l.Ignore() // ignore '>' return nil diff --git a/lex/lexer.go b/lex/lexer.go index 95cc8c14528..e92223499b7 100644 --- a/lex/lexer.go +++ b/lex/lexer.go @@ -47,7 +47,7 @@ type Item struct { } func (i Item) Errorf(format string, args ...interface{}) error { - return fmt.Errorf("line %d column %d: "+format, + return errors.Errorf("line %d column %d: "+format, append([]interface{}{i.line, i.column}, args...)...) } diff --git a/posting/index.go b/posting/index.go index 81b95859666..6b62235f3b9 100644 --- a/posting/index.go +++ b/posting/index.go @@ -20,7 +20,6 @@ import ( "bytes" "context" "encoding/hex" - "fmt" "math" "time" @@ -427,7 +426,7 @@ func deleteTokensFor(attr, tokenizerName string) error { prefix := pk.IndexPrefix() tokenizer, ok := tok.GetTokenizer(tokenizerName) if !ok { - return fmt.Errorf("Could not find valid tokenizer for %s", tokenizerName) + return errors.Errorf("Could not find valid tokenizer for %s", tokenizerName) } prefix = append(prefix, tokenizer.Identifier()) if err := pstore.DropPrefix(prefix); err != nil { @@ -896,7 +895,7 @@ func (rb *IndexRebuild) needsListTypeRebuild() (bool, error) { return true, nil } if rb.OldSchema.List && !rb.CurrentSchema.List { - return false, fmt.Errorf("Type can't be changed from list to scalar for attr: [%s]"+ + return false, errors.Errorf("Type can't be changed from list to scalar for attr: [%s]"+ " without dropping it first.", rb.CurrentSchema.Predicate) } diff --git a/posting/list.go b/posting/list.go index 4864d1221bb..f5a47f677e7 100644 --- a/posting/list.go +++ b/posting/list.go @@ -42,9 +42,9 @@ import ( var ( // ErrRetry can be triggered if the posting list got deleted from memory due to a hard commit. // In such a case, retry. - ErrRetry = fmt.Errorf("Temporary error. Please retry") + ErrRetry = errors.New("Temporary error. Please retry") // ErrNoValue would be returned if no value was found in the posting list. - ErrNoValue = fmt.Errorf("No value found") + ErrNoValue = errors.New("No value found") errStopIteration = errors.New("Stop iteration") emptyPosting = &pb.Posting{} maxListSize = mb / 2 @@ -102,7 +102,7 @@ type pIterator struct { func (it *pIterator) init(l *List, afterUid, deleteBelowTs uint64) error { if deleteBelowTs > 0 && deleteBelowTs <= l.minTs { - return fmt.Errorf("deleteBelowTs (%d) must be greater than the minTs in the list (%d)", + return errors.Errorf("deleteBelowTs (%d) must be greater than the minTs in the list (%d)", deleteBelowTs, l.minTs) } @@ -377,7 +377,7 @@ func (l *List) canMutateUid(txn *Txn, edge *pb.DirectedEdge) error { return l.iterate(txn.StartTs, 0, func(obj *pb.Posting) error { if obj.Uid != edge.GetValueId() { - return fmt.Errorf( + return errors.Errorf( "cannot add value with uid %x to predicate %s because one of the existing "+ "values does not match this uid, either delete the existing values first or "+ "modify the schema to '%s: [uid]'", diff --git a/query/query.go b/query/query.go index 628d0f943c9..0d05b03ccc7 100644 --- a/query/query.go +++ b/query/query.go @@ -986,7 +986,7 @@ func newGraph(ctx context.Context, gq *gql.GraphQuery) (*SubGraph, error) { } } if err := args.fill(gq); err != nil { - return nil, fmt.Errorf("error while filling args: %v", err) + return nil, errors.Wrapf(err, "while filling args") } sg := &SubGraph{Params: args} @@ -1010,7 +1010,7 @@ func newGraph(ctx context.Context, gq *gql.GraphQuery) (*SubGraph, error) { if isUidFnWithoutVar(gq.Func) && len(gq.UID) > 0 { if err := sg.populate(gq.UID); err != nil { - return nil, fmt.Errorf("error while populating UIDs: %v", err) + return nil, errors.Wrapf(err, "while populating UIDs") } } @@ -1018,14 +1018,14 @@ func newGraph(ctx context.Context, gq *gql.GraphQuery) (*SubGraph, error) { if gq.Filter != nil { sgf := &SubGraph{} if err := filterCopy(sgf, gq.Filter); err != nil { - return nil, fmt.Errorf("error while copying filter: %v", err) + return nil, errors.Wrapf(err, "while copying filter") } sg.Filters = append(sg.Filters, sgf) } if gq.FacetsFilter != nil { facetsFilter, err := toFacetsFilter(gq.FacetsFilter) if err != nil { - return nil, fmt.Errorf("error while converting to facets filter: %v", err) + return nil, errors.Wrapf(err, "while converting to facets filter") } sg.facetsFilter = facetsFilter } @@ -1652,7 +1652,8 @@ func (sg *SubGraph) populateFacetVars(doneVars map[string]varValue, sgPath []*Su } if nVal.Tid != types.IntID && nVal.Tid != types.FloatID { - return errors.Errorf("Repeated id with non int/float value for facet var encountered.") + return errors.Errorf("Repeated id with non int/float value for " + + "facet var encountered.") } ag := aggregator{name: "sum"} ag.Apply(pVal) @@ -1952,7 +1953,8 @@ func expandSubgraph(ctx context.Context, sg *SubGraph) ([]*SubGraph, error) { for _, ch := range sg.Children { if ch.isSimilar(temp) { - return out, errors.Errorf("Repeated subgraph: [%s] while using expand()", ch.Attr) + return out, errors.Errorf("Repeated subgraph: [%s] while using expand()", + ch.Attr) } } out = append(out, temp) @@ -2629,7 +2631,7 @@ func (req *Request) ProcessQuery(ctx context.Context) (err error) { } sg, err := ToSubGraph(ctx, gq) if err != nil { - return fmt.Errorf("error while converting to subgraph: %v", err) + return errors.Wrapf(err, "while converting to subgraph") } sg.recurse(func(sg *SubGraph) { sg.ReadTs = req.ReadTs diff --git a/systest/_customtok/factor/main.go b/systest/_customtok/factor/main.go index 759bf04575a..6a3090775d4 100644 --- a/systest/_customtok/factor/main.go +++ b/systest/_customtok/factor/main.go @@ -18,7 +18,8 @@ package main import ( "encoding/binary" - "fmt" + + "github.com/pkg/errors" ) func Tokenizer() interface{} { return FactorTokenizer{} } @@ -32,7 +33,7 @@ func (FactorTokenizer) Identifier() byte { return 0xfe } func (FactorTokenizer) Tokens(value interface{}) ([]string, error) { x := value.(int64) if x <= 1 { - return nil, fmt.Errorf("Cannot factor int <= 1: %d", x) + return nil, errors.Errorf("Cannot factor int <= 1: %d", x) } var toks []string for p := int64(2); x > 1; p++ { diff --git a/systest/group-delete/group_delete_test.go b/systest/group-delete/group_delete_test.go index d83f0485812..92911b0bdb1 100644 --- a/systest/group-delete/group_delete_test.go +++ b/systest/group-delete/group_delete_test.go @@ -33,6 +33,7 @@ import ( "github.com/dgraph-io/dgo" "github.com/dgraph-io/dgo/protos/api" "github.com/dgraph-io/dgraph/z" + "github.com/pkg/errors" "github.com/stretchr/testify/require" ) @@ -115,10 +116,10 @@ func getError(rc io.ReadCloser) error { defer rc.Close() b, err := ioutil.ReadAll(rc) if err != nil { - return fmt.Errorf("Read failed: %v", err) + return errors.Wrapf(err, "while reading") } if bytes.Contains(b, []byte("Error")) { - return fmt.Errorf("%s", string(b)) + return errors.Errorf("%s", string(b)) } return nil } diff --git a/tlstest/acl/acl_over_tls_test.go b/tlstest/acl/acl_over_tls_test.go index 3bd3a4382ef..828c055a9e4 100644 --- a/tlstest/acl/acl_over_tls_test.go +++ b/tlstest/acl/acl_over_tls_test.go @@ -4,13 +4,13 @@ import ( "context" "crypto/tls" "crypto/x509" - "fmt" "io/ioutil" "github.com/dgraph-io/dgo" "github.com/dgraph-io/dgo/protos/api" "github.com/dgraph-io/dgraph/z" "github.com/golang/glog" + "github.com/pkg/errors" "github.com/spf13/viper" "google.golang.org/grpc" "google.golang.org/grpc/credentials" @@ -33,7 +33,7 @@ func generateCertPool(certPath string, useSystemCA bool) (*x509.CertPool, error) return nil, err } if !pool.AppendCertsFromPEM(caFile) { - return nil, fmt.Errorf("error reading CA file %q", certPath) + return nil, errors.Errorf("error reading CA file %q", certPath) } } diff --git a/tok/tok.go b/tok/tok.go index 21a4912357f..f07505f02cc 100644 --- a/tok/tok.go +++ b/tok/tok.go @@ -18,7 +18,6 @@ package tok import ( "encoding/binary" - "fmt" "plugin" "time" @@ -155,7 +154,7 @@ func GetTokenizers(names []string) ([]Tokenizer, error) { for _, name := range names { t, found := GetTokenizer(name) if !found { - return nil, fmt.Errorf("Invalid tokenizer %s", name) + return nil, errors.Errorf("Invalid tokenizer %s", name) } tokenizers = append(tokenizers, t) } diff --git a/types/conversion.go b/types/conversion.go index 7429e0b2bf1..84351e03596 100644 --- a/types/conversion.go +++ b/types/conversion.go @@ -20,7 +20,6 @@ import ( "bytes" "encoding/binary" "encoding/json" - "fmt" "math" "strconv" "time" @@ -112,7 +111,7 @@ func Convert(from Val, toID TypeID) (Val, error) { return to, err } if math.IsNaN(val) { - return to, fmt.Errorf("Got invalid value: NaN") + return to, errors.Errorf("Got invalid value: NaN") } *res = val case StringID, DefaultID: diff --git a/types/facets/utils.go b/types/facets/utils.go index e410f763d92..f631d3c2817 100644 --- a/types/facets/utils.go +++ b/types/facets/utils.go @@ -17,7 +17,6 @@ package facets import ( - "fmt" "math" "sort" "strconv" @@ -110,7 +109,7 @@ func valAndValType(val string) (interface{}, api.Facet_ValType, error) { if floatVal, err := strconv.ParseFloat(val, 64); err == nil { // We can't store NaN as it is because it serializes into invalid JSON. if math.IsNaN(floatVal) { - return nil, api.Facet_FLOAT, fmt.Errorf("Got invalid value: NaN") + return nil, api.Facet_FLOAT, errors.Errorf("Got invalid value: NaN") } return floatVal, api.Facet_FLOAT, nil @@ -179,7 +178,7 @@ func TypeIDFor(f *api.Facet) (types.TypeID, error) { case api.Facet_STRING: return types.StringID, nil default: - return types.DefaultID, fmt.Errorf("Unrecognized facet type: %v", f.ValType) + return types.DefaultID, errors.Errorf("Unrecognized facet type: %v", f.ValType) } } diff --git a/types/sort.go b/types/sort.go index 6ed772fac4b..bfff2e477bc 100644 --- a/types/sort.go +++ b/types/sort.go @@ -17,7 +17,6 @@ package types import ( - "fmt" "sort" "time" @@ -92,7 +91,7 @@ func SortWithFacet(v [][]Val, ul *pb.List, l []*pb.Facets, desc []bool) error { case DateTimeID, IntID, FloatID, StringID, DefaultID: // Don't do anything, we can sort values of this type. default: - return fmt.Errorf("Value of type: %s isn't sortable", typ.Name()) + return errors.Errorf("Value of type: %s isn't sortable", typ.Name()) } var toBeSorted sort.Interface b := sortBase{v, desc, ul, l} diff --git a/worker/draft.go b/worker/draft.go index 078364381d9..522f0266829 100644 --- a/worker/draft.go +++ b/worker/draft.go @@ -170,7 +170,7 @@ func (n *node) applyMutations(ctx context.Context, proposal *pb.Proposal) (rerr if servesTablet, err := groups().ServesTablet(s.Predicate); err != nil { return err } else if !servesTablet { - return fmt.Errorf("group 1 should always serve reserved predicate %s", + return errors.Errorf("group 1 should always serve reserved predicate %s", s.Predicate) } } @@ -539,9 +539,9 @@ func (n *node) leaderBlocking() (*conn.Pool, error) { // leader election for a group might not have happened when it is called. If we can't // find a leader, get latest state from Zero. if err := UpdateMembershipState(context.Background()); err != nil { - return nil, fmt.Errorf("Error while trying to update membership state: %+v", err) + return nil, errors.Errorf("Error while trying to update membership state: %+v", err) } - return nil, fmt.Errorf("Unable to reach leader in group %d", n.gid) + return nil, errors.Errorf("Unable to reach leader in group %d", n.gid) } return pool, nil } @@ -596,12 +596,12 @@ func (n *node) retrieveSnapshot(snap pb.Snapshot) error { // keep all the pre-writes for a pending transaction, so they will come back to memory, as Raft // logs are replayed. if _, err := n.populateSnapshot(snap, pool); err != nil { - return fmt.Errorf("Cannot retrieve snapshot from peer, error: %v", err) + return errors.Wrapf(err, "cannot retrieve snapshot from peer") } // Populate shard stores the streamed data directly into db, so we need to refresh // schema for current group id if err := schema.LoadFromDb(); err != nil { - return fmt.Errorf("Error while initilizating schema: %+v", err) + return errors.Wrapf(err, "while initializing schema") } groups().triggerMembershipSync() return nil @@ -843,7 +843,7 @@ func (n *node) Run() { timer.Record("disk") if rd.MustSync { if err := n.Store.Sync(); err != nil { - glog.Errorf("Error while calling Store.Sync: %v", err) + glog.Errorf("Error while calling Store.Sync: %+v", err) } timer.Record("sync") } diff --git a/worker/export.go b/worker/export.go index 72f298cb4da..4c6e3ed350e 100644 --- a/worker/export.go +++ b/worker/export.go @@ -111,7 +111,7 @@ var uidFmtStrJson = "\"0x%x\"" func valToStr(v types.Val) (string, error) { v2, err := types.Convert(v, types.StringID) if err != nil { - return "", fmt.Errorf("converting %v to string: %v\n", v2.Value, err) + return "", errors.Wrapf(err, "while converting %v to string", v2.Value) } // Strip terminating null, if any. @@ -122,12 +122,12 @@ func valToStr(v types.Val) (string, error) { func facetToString(fct *api.Facet) (string, error) { v1, err := facets.ValFor(fct) if err != nil { - return "", fmt.Errorf("getting value from facet %#v: %v", fct, err) + return "", errors.Wrapf(err, "getting value from facet %#v", fct) } v2 := &types.Val{Tid: types.StringID} if err = types.Marshal(v1, v2); err != nil { - return "", fmt.Errorf("marshaling facet value %v to string: %v", v1, err) + return "", errors.Wrapf(err, "marshaling facet value %v to string", v1) } return v2.Value.(string), nil @@ -427,7 +427,7 @@ func (writer *fileWriter) Close() error { // export creates a export of data by exporting it as an RDF gzip. func export(ctx context.Context, in *pb.ExportRequest) error { if in.GroupId != groups().groupId() { - return errors.Errorf("Export request group mismatch. Mine: %d. Requested: %d\n", + return errors.Errorf("Export request group mismatch. Mine: %d. Requested: %d", groups().groupId(), in.GroupId) } glog.Infof("Export requested at %d.", in.ReadTs) @@ -670,7 +670,7 @@ func ExportOverNetwork(ctx context.Context, format string) error { for i := 0; i < len(gids); i++ { err := <-ch if err != nil { - rerr := fmt.Errorf("Export failed at readTs %d. Err=%v", readTs, err) + rerr := errors.Wrapf(err, "Export failed at readTs %d", readTs) glog.Errorln(rerr) return rerr } diff --git a/worker/groups.go b/worker/groups.go index c7450445ccb..e41f1102ad1 100644 --- a/worker/groups.go +++ b/worker/groups.go @@ -345,7 +345,7 @@ func (g *groupi) ChecksumsMatch(ctx context.Context) error { return nil } case <-ctx.Done(): - return fmt.Errorf("Group checksum mismatch for id: %d", g.groupId()) + return errors.Errorf("Group checksum mismatch for id: %d", g.groupId()) } } } diff --git a/worker/predicate_move.go b/worker/predicate_move.go index 27dda69d52b..20dc84d02c8 100644 --- a/worker/predicate_move.go +++ b/worker/predicate_move.go @@ -215,7 +215,7 @@ func movePredicateHelper(ctx context.Context, in *pb.MovePredicatePayload) error c := pb.NewWorkerClient(pl.Get()) s, err := c.ReceivePredicate(ctx) if err != nil { - return fmt.Errorf("While calling ReceivePredicate: %+v", err) + return errors.Wrapf(err, "while calling ReceivePredicate") } // This txn is only reading the schema. Doesn't really matter what read timestamp we use, diff --git a/worker/sort.go b/worker/sort.go index 9ea5d581dea..89aba95f9a2 100644 --- a/worker/sort.go +++ b/worker/sort.go @@ -17,7 +17,6 @@ package worker import ( - "fmt" "sort" "strings" "time" @@ -57,7 +56,7 @@ func SortOverNetwork(ctx context.Context, q *pb.SortMessage) (*pb.SortResult, er if err != nil { return &emptySortResult, err } else if gid == 0 { - return &emptySortResult, fmt.Errorf("Cannot sort by unknown attribute %s", q.Order[0].Attr) + return &emptySortResult, errors.Errorf("Cannot sort by unknown attribute %s", q.Order[0].Attr) } if span := otrace.FromContext(ctx); span != nil { diff --git a/worker/task.go b/worker/task.go index bfb386192b8..8606aed4808 100644 --- a/worker/task.go +++ b/worker/task.go @@ -18,7 +18,6 @@ package worker import ( "bytes" - "fmt" "sort" "strconv" "strings" @@ -1651,7 +1650,7 @@ func (w *grpcWorker) ServeTask(ctx context.Context, q *pb.Query) (*pb.Result, er span.Annotatef(nil, "Attribute: %q NumUids: %v groupId: %v ServeTask", q.Attr, numUids, gid) if !groups().ServesGroup(gid) { - return &emptyResult, fmt.Errorf( + return &emptyResult, errors.Errorf( "Temporary error, attr: %q groupId: %v Request sent to wrong server", q.Attr, gid) } diff --git a/x/error.go b/x/error.go index 70f7bdd4538..723f424ba82 100644 --- a/x/error.go +++ b/x/error.go @@ -29,7 +29,6 @@ package x // (3) You want to generate a new error with stack trace info. Use errors.Errorf. import ( - "fmt" "log" "os" @@ -92,7 +91,7 @@ func AssertTruef(b bool, format string, args ...interface{}) { // AssertTruefNoTrace is AssertTruef without a stack trace. func AssertTruefNoTrace(b bool, format string, args ...interface{}) { if !b { - log.Fatalf("%+v", fmt.Errorf(format, args...)) + log.Fatalf("%+v", errors.Errorf(format, args...)) } } diff --git a/x/tls_helper.go b/x/tls_helper.go index 89c6145dc98..b0586c14141 100644 --- a/x/tls_helper.go +++ b/x/tls_helper.go @@ -19,11 +19,11 @@ package x import ( "crypto/tls" "crypto/x509" - "fmt" "io/ioutil" "path" "strings" + "github.com/pkg/errors" "github.com/spf13/pflag" "github.com/spf13/viper" ) @@ -110,7 +110,7 @@ func LoadClientTLSConfig(v *viper.Viper) (*tls.Config, error) { if v.GetString("tls_server_name") != "" || v.GetString("tls_cert") != "" || v.GetString("tls_key") != "" { - return nil, fmt.Errorf("--tls_cacert is required for enabling TLS") + return nil, errors.Errorf("--tls_cacert is required for enabling TLS") } return nil, nil } @@ -132,7 +132,7 @@ func generateCertPool(certPath string, useSystemCA bool) (*x509.CertPool, error) return nil, err } if !pool.AppendCertsFromPEM(caFile) { - return nil, fmt.Errorf("error reading CA file %q", certPath) + return nil, errors.Errorf("error reading CA file %q", certPath) } } @@ -151,7 +151,7 @@ func setupClientAuth(authType string) (tls.ClientAuthType, error) { if v, has := auth[strings.ToUpper(authType)]; has { return v, nil } - return tls.NoClientCert, fmt.Errorf("Invalid client auth. Valid values " + + return tls.NoClientCert, errors.Errorf("Invalid client auth. Valid values " + "[REQUEST, REQUIREANY, VERIFYIFGIVEN, REQUIREANDVERIFY]") } diff --git a/x/x.go b/x/x.go index 0e9cd6d9a5e..3b86a761894 100644 --- a/x/x.go +++ b/x/x.go @@ -40,6 +40,7 @@ import ( "github.com/dgraph-io/dgo" "github.com/dgraph-io/dgo/protos/api" "github.com/golang/glog" + "github.com/pkg/errors" "github.com/spf13/viper" "go.opencensus.io/trace" "google.golang.org/grpc" @@ -50,7 +51,7 @@ import ( // Error constants representing different types of errors. var ( // ErrNotSupported is thrown when an enterprise feature is requested in the open source version. - ErrNotSupported = fmt.Errorf("Feature available only in Dgraph Enterprise Edition") + ErrNotSupported = errors.Errorf("Feature available only in Dgraph Enterprise Edition") ) const ( @@ -629,7 +630,7 @@ func AskUserPassword(userid string, pwdType string, times int) (string, error) { fmt.Printf("%s password for %v:", pwdType, userid) pd, err := terminal.ReadPassword(int(syscall.Stdin)) if err != nil { - return "", fmt.Errorf("error while reading password:%v", err) + return "", errors.Wrapf(err, "while reading password") } fmt.Println() password := string(pd) @@ -638,13 +639,13 @@ func AskUserPassword(userid string, pwdType string, times int) (string, error) { fmt.Printf("Retype %s password for %v:", strings.ToLower(pwdType), userid) pd2, err := terminal.ReadPassword(int(syscall.Stdin)) if err != nil { - return "", fmt.Errorf("error while reading password:%v", err) + return "", errors.Wrapf(err, "while reading password") } fmt.Println() password2 := string(pd2) if password2 != password { - return "", fmt.Errorf("the two typed passwords do not match") + return "", errors.Errorf("the two typed passwords do not match") } } return password, nil @@ -663,7 +664,7 @@ func GetPassAndLogin(dg *dgo.Dgraph, opt *CredOpt) error { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := dg.Login(ctx, opt.UserID, password); err != nil { - return fmt.Errorf("unable to login to the %v account:%v", opt.UserID, err) + return errors.Wrapf(err, "unable to login to the %v account", opt.UserID) } fmt.Println("Login successful.") // update the context so that it has the admin jwt token diff --git a/z/backup.go b/z/backup.go index deae6ea1a27..2cfe7de880d 100644 --- a/z/backup.go +++ b/z/backup.go @@ -31,6 +31,7 @@ import ( "github.com/dgraph-io/dgraph/protos/pb" "github.com/dgraph-io/dgraph/types" "github.com/dgraph-io/dgraph/x" + "github.com/pkg/errors" ) // GetPValues reads the specified p directory and returns the values for the given @@ -100,10 +101,10 @@ func GetPValues(pdir, attr string, readTs uint64) (map[string]string, error) { func GetError(rc io.ReadCloser) error { b, err := ioutil.ReadAll(rc) if err != nil { - return fmt.Errorf("Read failed: %v", err) + return errors.Wrapf(err, "while reading") } if bytes.Contains(b, []byte("Error")) { - return fmt.Errorf("%s", string(b)) + return errors.Errorf("%s", string(b)) } return nil } diff --git a/z/client.go b/z/client.go index 3bfd8dad09c..6e418389aeb 100644 --- a/z/client.go +++ b/z/client.go @@ -33,6 +33,7 @@ import ( "github.com/dgraph-io/dgo" "github.com/dgraph-io/dgo/protos/api" "github.com/dgraph-io/dgraph/x" + "github.com/pkg/errors" "github.com/spf13/viper" "github.com/stretchr/testify/require" "google.golang.org/grpc" @@ -206,24 +207,24 @@ func HttpLogin(params *LoginParams) (string, string, error) { body, err := json.Marshal(&loginPayload) if err != nil { - return "", "", fmt.Errorf("unable to marshal body: %v", err) + return "", "", errors.Wrapf(err, "unable to marshal body") } req, err := http.NewRequest("POST", params.Endpoint, bytes.NewBuffer(body)) if err != nil { - return "", "", fmt.Errorf("unable to create request: %v", err) + return "", "", errors.Wrapf(err, "unable to create request") } client := &http.Client{} resp, err := client.Do(req) if err != nil { - return "", "", fmt.Errorf("login through curl failed: %v", err) + return "", "", errors.Wrapf(err, "login through curl failed") } defer resp.Body.Close() respBody, err := ioutil.ReadAll(resp.Body) if err != nil { - return "", "", fmt.Errorf("unable to read from response: %v", err) + return "", "", errors.Wrapf(err, "unable to read from response") } var outputJson map[string]map[string]string @@ -231,24 +232,24 @@ func HttpLogin(params *LoginParams) (string, string, error) { var errOutputJson map[string]interface{} if err := json.Unmarshal(respBody, &errOutputJson); err == nil { if _, ok := errOutputJson["errors"]; ok { - return "", "", fmt.Errorf("response error: %v", string(respBody)) + return "", "", errors.Errorf("response error: %v", string(respBody)) } } - return "", "", fmt.Errorf("unable to unmarshal the output to get JWTs: %v", err) + return "", "", errors.Wrapf(err, "unable to unmarshal the output to get JWTs") } data, found := outputJson["data"] if !found { - return "", "", fmt.Errorf("data entry found in the output: %v", err) + return "", "", errors.Wrapf(err, "data entry found in the output") } newAccessJwt, found := data["accessJWT"] if !found { - return "", "", fmt.Errorf("no access JWT found in the output") + return "", "", errors.Errorf("no access JWT found in the output") } newRefreshJwt, found := data["refreshJWT"] if !found { - return "", "", fmt.Errorf("no refresh JWT found in the output") + return "", "", errors.Errorf("no refresh JWT found in the output") } return newAccessJwt, newRefreshJwt, nil diff --git a/z/zero.go b/z/zero.go index 1ecad4007c6..33b6604dcec 100644 --- a/z/zero.go +++ b/z/zero.go @@ -27,6 +27,7 @@ import ( "github.com/dgraph-io/dgo" "github.com/dgraph-io/dgo/protos/api" + "github.com/pkg/errors" "google.golang.org/grpc" ) @@ -67,7 +68,7 @@ func GetState() (*StateResponse, error) { } if bytes.Contains(b, []byte("Error")) { - return nil, fmt.Errorf("Failed to get state: %s", string(b)) + return nil, errors.Errorf("Failed to get state: %s", string(b)) } var st StateResponse @@ -86,22 +87,22 @@ func GetClientToGroup(groupID string) (*dgo.Dgraph, error) { group, ok := state.Groups[groupID] if !ok { - return nil, fmt.Errorf("group %s does not exist", groupID) + return nil, errors.Errorf("group %s does not exist", groupID) } if len(group.Members) == 0 { - return nil, fmt.Errorf("the group %s has no members", groupID) + return nil, errors.Errorf("the group %s has no members", groupID) } member := group.Members["1"] parts := strings.Split(member.Addr, ":") if len(parts) != 2 { - return nil, fmt.Errorf("the member has an invalid address: %v", member.Addr) + return nil, errors.Errorf("the member has an invalid address: %v", member.Addr) } // internalPort is used for communication between alpha nodes internalPort, err := strconv.Atoi(parts[1]) if err != nil { - return nil, fmt.Errorf("unable to parse the port number from %s", parts[1]) + return nil, errors.Errorf("unable to parse the port number from %s", parts[1]) } // externalPort is for handling connections from clients