Skip to content

Commit

Permalink
refactor: Replaced calls to errors.Wrap and errors.Wrapf
Browse files Browse the repository at this point in the history
Also added back in a nil check in `collectGarbageSQL` in `orc8r/clound/go/syncstore/store_writer.go`

Signed-off-by: Moritz Huebner <moritz.huebner@tngtech.com>
  • Loading branch information
MoritzThomasHuebner committed May 12, 2022
1 parent b003269 commit f632b0c
Show file tree
Hide file tree
Showing 135 changed files with 705 additions and 742 deletions.
5 changes: 2 additions & 3 deletions cwf/cloud/go/services/cwf/obsidian/handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"net/http"

"github.com/labstack/echo"
"github.com/pkg/errors"

"magma/cwf/cloud/go/cwf"
"magma/cwf/cloud/go/serdes"
Expand Down Expand Up @@ -151,7 +150,7 @@ func getGateway(c echo.Context) error {
serdes.Entity,
)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, errors.Wrap(err, "failed to load cwf gateway"))
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Errorf("failed to load cwf gateway: %w", err))
}

ret := &cwfModels.CwfGateway{
Expand Down Expand Up @@ -417,7 +416,7 @@ func updateHAPairHandler(c echo.Context) error {
// 404 if pair doesn't exist
exists, err := configurator.DoesEntityExist(reqCtx, networkID, cwf.CwfHAPairType, haPairID)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, errors.Wrap(err, "Failed to check if ha pair exists"))
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Errorf("Failed to check if ha pair exists: %w", err))
}
if !exists {
return echo.ErrNotFound
Expand Down
78 changes: 40 additions & 38 deletions cwf/gateway/integ_tests/test_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,19 +175,19 @@ func (tr *TestRunner) ConfigUEsPerInstance(IMSIs []string, pcrfInstance, ocsInst

err = uesim.AddUE(ue)
if err != nil {
return nil, errors.Wrap(err, "Error adding UE to UESimServer")
return nil, fmt.Errorf("Error adding UE to UESimServer: %w", err)
}
err = addSubscriberToHSS(sub)
if err != nil {
return nil, errors.Wrap(err, "Error adding Subscriber to HSS")
return nil, fmt.Errorf("Error adding Subscriber to HSS: %w", err)
}
err = addSubscriberToPCRFPerInstance(pcrfInstance, sub.GetSid())
if err != nil {
return nil, errors.Wrap(err, "Error adding Subscriber to PCRF")
return nil, fmt.Errorf("Error adding Subscriber to PCRF: %w", err)
}
err = addSubscriberToOCSPerInstance(ocsInstance, sub.GetSid())
if err != nil {
return nil, errors.Wrap(err, "Error adding Subscriber to OCS")
return nil, fmt.Errorf("Error adding Subscriber to OCS: %w", err)
}

ues = append(ues, ue)
Expand All @@ -211,7 +211,7 @@ func (tr *TestRunner) Authenticate(imsi, calledStationID string) (*radius.Packet
encoded := res.GetRadiusPacket()
radiusP, err := radius.Parse(encoded, []byte(Secret))
if err != nil {
err = errors.Wrap(err, "Error while parsing encoded Radius packet")
err = fmt.Errorf("Error while parsing encoded Radius packet: %w", err)
fmt.Println(err)
return &radius.Packet{}, err
}
Expand All @@ -230,7 +230,7 @@ func (tr *TestRunner) Disconnect(imsi, calledStationID string) (*radius.Packet,
encoded := res.GetRadiusPacket()
radiusP, err := radius.Parse(encoded, []byte(Secret))
if err != nil {
err = errors.Wrap(err, "Error while parsing encoded Radius packet")
err = fmt.Errorf("Error while parsing encoded Radius packet: %w", err)
fmt.Println(err)
return &radius.Packet{}, err
}
Expand Down Expand Up @@ -281,14 +281,14 @@ func (tr *TestRunner) GenULTrafficBasedOnPolicyUsage(req *cwfprotos.GenTrafficRe
for start := time.Now(); time.Since(start) < waitFor; {
startGenTrafficTime := time.Now()
res, err = uesim.GenTrafficWithReatempts(req)
if err != nil{
if err != nil {
return res, fmt.Errorf("GenULTrafficBasedOnPolicyUsage failed during GenTraffic: %s", err)
}
completeCycle := time.Now().Sub(startGenTrafficTime)%time.Second
if waitNeeded {
completeCycle := time.Now().Sub(startGenTrafficTime) % time.Second
if waitNeeded {
// this wait makes sure the time passes is exact in seconds. This way
// we make sure policies had time to sync
time.Sleep(completeCycle + 200 * time.Millisecond)
time.Sleep(completeCycle + 200*time.Millisecond)
waitNeeded = false
}
time.Sleep(2200 * time.Millisecond)
Expand All @@ -306,19 +306,21 @@ func (tr *TestRunner) GenULTrafficBasedOnPolicyUsage(req *cwfprotos.GenTrafficRe
req.Bitrate = &wrappers.StringValue{Value: "10M"}
if remaining > 100*KiloBytes {
newVolume = uint64(float64(remaining) * 0.95)
if newVolume > 5 * MegaBytes {
if newVolume > 5*MegaBytes {
newVolume = 5 * MegaBytes
}
// only add wait for the bigger chunks
waitNeeded = true
}
if newVolume < 1000 {newVolume = 1000}
if newVolume < 1000 {
newVolume = 1000
}
newVolumeStr := fmt.Sprintf("%dK", newVolume/1000)

req.Volume = &wrappers.StringValue{Value: newVolumeStr}
fmt.Printf("- not enough traffic genereted, sending %dKB more. Will be around %d%% of volume requested\n",
newVolume/1000,
100 * (record.BytesTx+newVolume)/totalVolume,
100*(record.BytesTx+newVolume)/totalVolume,
)
}
return res, fmt.Errorf("error: not enough traffic generated to fullfil GenULTrafficBasedOnPolicyUsage requieriment: %s", err)
Expand Down Expand Up @@ -477,32 +479,32 @@ func (tr *TestRunner) WaitForEnforcementStatsForRuleGreaterThanOrDoesNotExist(im
}
}

func (tr *TestRunner) WaitForEnforcementStatsForRuleGreaterThanOrDoesNotExistFunc (imsi, ruleID string, min uint64)(*lteprotos.RuleRecord, bool) {
fmt.Printf("\tWaiting until %s, %s has more than %d bytes in enforcement stats or rule does not exist ...\n", imsi, ruleID, min)
records, err := tr.GetPolicyUsage()
if err != nil {
return nil, false
}
imsi = prependIMSIPrefix(imsi)
if records[imsi] == nil {
// Session is gone
fmt.Printf("\tSession for %s, does not exist...\n", imsi)
return nil, true
}
record := records[imsi][ruleID]
if record == nil {
// Session is gone
fmt.Printf("\tRule %s for %s, does not exist...\n", ruleID, imsi)
return nil, true
}
txBytes := record.BytesTx
if record.BytesTx < min {
return record, false
}
fmt.Printf("\t\u2713 %s, %s now passed %d > %d in enforcement stats!(%d%%)\n",
imsi, ruleID, txBytes, min, 100* txBytes/min)
return record, true
func (tr *TestRunner) WaitForEnforcementStatsForRuleGreaterThanOrDoesNotExistFunc(imsi, ruleID string, min uint64) (*lteprotos.RuleRecord, bool) {
fmt.Printf("\tWaiting until %s, %s has more than %d bytes in enforcement stats or rule does not exist ...\n", imsi, ruleID, min)
records, err := tr.GetPolicyUsage()
if err != nil {
return nil, false
}
imsi = prependIMSIPrefix(imsi)
if records[imsi] == nil {
// Session is gone
fmt.Printf("\tSession for %s, does not exist...\n", imsi)
return nil, true
}
record := records[imsi][ruleID]
if record == nil {
// Session is gone
fmt.Printf("\tRule %s for %s, does not exist...\n", ruleID, imsi)
return nil, true
}
txBytes := record.BytesTx
if record.BytesTx < min {
return record, false
}
fmt.Printf("\t\u2713 %s, %s now passed %d > %d in enforcement stats!(%d%%)\n",
imsi, ruleID, txBytes, min, 100*txBytes/min)
return record, true
}

//WaitForPolicyReAuthToProcess returns a method which checks for reauth answer and
// if it has sessionID which contains the IMSI
Expand Down
4 changes: 2 additions & 2 deletions cwf/gateway/services/uesim/servicers/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ package servicers

import (
"encoding/hex"
"fmt"
"net"

"magma/cwf/gateway/registry"
"magma/orc8r/lib/go/service/config"

"github.com/golang/glog"
"github.com/pkg/errors"
)

const (
Expand All @@ -41,7 +41,7 @@ var (
func GetUESimConfig() (*UESimConfig, error) {
uecfg, err := config.GetServiceConfig("", registry.UeSim)
if err != nil {
glog.Error(errors.Wrap(err, "No service config found, using default config"))
glog.Error(fmt.Errorf("No service config found, using default config: %w", err))
return getDefaultUESimConfig(), nil
}
authAddr, err := uecfg.GetString("radius_auth_address")
Expand Down
4 changes: 3 additions & 1 deletion cwf/gateway/services/uesim/servicers/eap.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
package servicers

import (
"fmt"

cwfprotos "magma/cwf/cloud/go/protos"
fegprotos "magma/feg/gateway/services/aaa/protos"
"magma/feg/gateway/services/eap"
Expand All @@ -30,7 +32,7 @@ const (
func (srv *UESimServer) HandleEap(ue *cwfprotos.UEConfig, req eap.Packet) (eap.Packet, error) {
err := req.Validate()
if err != nil {
return nil, errors.Wrap(err, "Error validating EAP packet")
return nil, fmt.Errorf("Error validating EAP packet: %w", err)
}

switch fegprotos.EapType(req.Type()) {
Expand Down
22 changes: 11 additions & 11 deletions cwf/gateway/services/uesim/servicers/eap_aka.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func (srv *UESimServer) handleEapAka(ue *protos.UEConfig, req eap.Packet) (eap.P
func (srv *UESimServer) eapAkaIdentityRequest(ue *protos.UEConfig, req eap.Packet) (eap.Packet, error) {
scanner, err := eap.NewAttributeScanner(req)
if err != nil {
return nil, errors.Wrap(err, "Error creating new attribute scanner")
return nil, fmt.Errorf("Error creating new attribute scanner: %w", err)
}

var a eap.Attribute
Expand Down Expand Up @@ -90,14 +90,14 @@ func (srv *UESimServer) eapAkaIdentityRequest(ue *protos.UEConfig, req eap.Packe
),
)
if err != nil {
return nil, errors.Wrap(err, "Error appending attribute to packet")
return nil, fmt.Errorf("Error appending attribute to packet: %w", err)
}
return p, nil
default:
glog.Info(fmt.Sprintf("Unexpected EAP-AKA Identity Request Attribute type %d", a.Type()))
}
}
return nil, errors.Wrap(err, "Error while processing EAP-AKA Identity Request")
return nil, fmt.Errorf("Error while processing EAP-AKA Identity Request: %w", err)
}

type challengeAttributes struct {
Expand All @@ -110,7 +110,7 @@ type challengeAttributes struct {
func (srv *UESimServer) eapAkaChallengeRequest(ue *protos.UEConfig, req eap.Packet) (eap.Packet, error) {
attrs, err := parseChallengeAttributes(req)
if err != io.EOF {
return nil, errors.Wrap(err, "Error while parsing attributes of request packet")
return nil, fmt.Errorf("Error while parsing attributes of request packet: %w", err)
}
if attrs.rand == nil || attrs.autn == nil || attrs.mac == nil {
return nil, errors.Errorf("Missing one or more expected attributes\nRAND: %s\nAUTN: %s\nMAC: %s\n", attrs.rand, attrs.autn, attrs.mac)
Expand Down Expand Up @@ -139,18 +139,18 @@ func (srv *UESimServer) eapAkaChallengeRequest(ue *protos.UEConfig, req eap.Pack
// Calculate RES and other keys.
milenage, err := crypto.NewMilenageCipher(srv.cfg.amf)
if err != nil {
return nil, errors.Wrap(err, "Error creating milenage cipher")
return nil, fmt.Errorf("Error creating milenage cipher: %w", err)
}
intermediateVec, err := milenage.GenerateSIPAuthVectorWithRand(rand, key, opc[:], sqn)
if err != nil {
return nil, errors.Wrap(err, "Error calculating authentication vector")
return nil, fmt.Errorf("Error calculating authentication vector: %w", err)
}
// Make copy of packet and zero out MAC value.
copyReq := make([]byte, len(req))
copy(copyReq, req)
copyAttrs, err := parseChallengeAttributes(eap.Packet(copyReq))
if err != io.EOF {
return nil, errors.Wrap(err, "Error while parsing attributes of copied request packet")
return nil, fmt.Errorf("Error while parsing attributes of copied request packet: %w", err)
}
copyMacBytes := copyAttrs.mac.Marshaled()
for i := aka.ATT_HDR_LEN; i < len(copyMacBytes); i++ {
Expand All @@ -168,7 +168,7 @@ func (srv *UESimServer) eapAkaChallengeRequest(ue *protos.UEConfig, req eap.Pack
receivedSqn := extractSqnFromAutn(expectedAutn, intermediateVec.AnonymityKey[:])
resultVec, err := milenage.GenerateSIPAuthVectorWithRand(rand, key, opc[:], receivedSqn)
if err != nil {
return nil, errors.Wrap(err, "Error calculating authentication vector")
return nil, fmt.Errorf("Error calculating authentication vector: %w", err)
}
if !reflect.DeepEqual(expectedAutn[MacAStart:], resultVec.Autn[MacAStart:]) {
return nil, fmt.Errorf("Invalid MacA in AUTN: Received MacA %x; Calculated MacA: %x",
Expand Down Expand Up @@ -205,7 +205,7 @@ func (srv *UESimServer) eapAkaChallengeRequest(ue *protos.UEConfig, req eap.Pack
),
)
if err != nil {
return nil, errors.Wrap(err, "Error appending attribute to packet")
return nil, fmt.Errorf("Error appending attribute to packet: %w", err)
}

// Add the CHECKCODE attribute.
Expand All @@ -226,7 +226,7 @@ func (srv *UESimServer) eapAkaChallengeRequest(ue *protos.UEConfig, req eap.Pack
),
)
if err != nil {
return nil, errors.Wrap(err, "Error appending attribute to packet")
return nil, fmt.Errorf("Error appending attribute to packet: %w", err)
}

// Calculate and Copy MAC into packet.
Expand All @@ -242,7 +242,7 @@ func parseChallengeAttributes(req eap.Packet) (challengeAttributes, error) {

scanner, err := eap.NewAttributeScanner(req)
if err != nil {
return attrs, errors.Wrap(err, "Error creating new attribute scanner")
return attrs, fmt.Errorf("Error creating new attribute scanner: %w", err)
}
var a eap.Attribute
for a, err = scanner.Next(); err == nil; a, err = scanner.Next() {
Expand Down
8 changes: 3 additions & 5 deletions cwf/gateway/services/uesim/servicers/radius.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ import (
"fbc/lib/go/radius/rfc2866"
"fbc/lib/go/radius/rfc2869"
"magma/feg/gateway/services/eap"

"github.com/pkg/errors"
)

// todo Replace constants with configurable fields
Expand All @@ -41,12 +39,12 @@ func (srv *UESimServer) HandleRadius(imsi string, calledStationID string, p *rad
// Extract EAP packet.
eapMessage, err := packet.NewPacketFromRadius(p)
if err != nil {
err = errors.Wrap(err, "Error extracting EAP message from Radius packet")
err = fmt.Errorf("Error extracting EAP message from Radius packet: %w", err)
return nil, err
}
eapBytes, err := eapMessage.Bytes()
if err != nil {
err = errors.Wrap(err, "Error converting EAP packet to bytes")
err = fmt.Errorf("Error converting EAP packet to bytes: %w", err)
return nil, err
}

Expand Down Expand Up @@ -97,7 +95,7 @@ func (srv *UESimServer) EapToRadius(eapP eap.Packet, imsi string, calledStationI

encoded, err := radiusP.Encode()
if err != nil {
return nil, errors.Wrap(err, "Error encoding Radius packet")
return nil, fmt.Errorf("Error encoding Radius packet: %w", err)
}

// Add Message-Authenticator Attribute.
Expand Down
10 changes: 5 additions & 5 deletions cwf/gateway/services/uesim/servicers/ue_store_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,31 @@
package servicers

import (
"fmt"

cwfprotos "magma/cwf/cloud/go/protos"
"magma/orc8r/cloud/go/blobstore"
"magma/orc8r/lib/go/protos"

"github.com/pkg/errors"
)

func addUeToStore(srvstore blobstore.StoreFactory, ue *cwfprotos.UEConfig) {
blob, err := ueToBlob(ue)
store, err := srvstore.StartTransaction(nil)
if err != nil {
err = errors.Wrap(err, "Error while starting transaction")
err = fmt.Errorf("Error while starting transaction: %w", err)
err = ConvertStorageErrorToGrpcStatus(err)
return
}
defer func() {
switch err {
case nil:
if commitErr := store.Commit(); commitErr != nil {
err = errors.Wrap(err, "Error while committing transaction")
err = fmt.Errorf("Error while committing transaction: %w", err)
err = ConvertStorageErrorToGrpcStatus(err)
}
default:
if rollbackErr := store.Rollback(); rollbackErr != nil {
err = errors.Wrap(err, "Error while rolling back transaction")
err = fmt.Errorf("Error while rolling back transaction: %w", err)
err = ConvertStorageErrorToGrpcStatus(err)
}
}
Expand Down

0 comments on commit f632b0c

Please sign in to comment.