diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index 90d00bb..a00107c 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -67,7 +67,6 @@ jobs: install-go: false lint: - name: lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 diff --git a/VERSION b/VERSION index 8869ce2..26aaba0 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.1.1-dev +1.2.0 diff --git a/drsm/api.go b/drsm/api.go index 5dfc3e4..cb8ae8f 100644 --- a/drsm/api.go +++ b/drsm/api.go @@ -50,7 +50,7 @@ type DrsmInterface interface { } func InitDRSM(sharedPoolName string, myid PodId, db DbInfo, opt *Options) (DrsmInterface, error) { - logger.AppLog.Debugln("CLIENT ID: ", myid) + logger.DrsmLog.Debugln("client id:", myid) d := &Drsm{sharedPoolName: sharedPoolName, clientId: myid, @@ -66,7 +66,7 @@ func (d *Drsm) AllocateInt32ID() (int32, error) { mutex.Lock() defer mutex.Unlock() if d.mode == ResourceDemux { - logger.AppLog.Debugf("demux mode can not allocate Resource index") + logger.DrsmLog.Debugln("demux mode can not allocate Resource index") err := fmt.Errorf("demux mode does not allow Resource Id allocation") return 0, err } @@ -87,7 +87,7 @@ func (d *Drsm) ReleaseInt32ID(id int32) error { mutex.Lock() defer mutex.Unlock() if d.mode == ResourceDemux { - logger.AppLog.Debugf("demux mode can not release Resource index") + logger.DrsmLog.Debugln("demux mode can not release Resource index") err := fmt.Errorf("demux mode does not allow Resource Id allocation") return err } @@ -96,7 +96,7 @@ func (d *Drsm) ReleaseInt32ID(id int32) error { chunk, found := d.localChunkTbl[chunkId] if found { chunk.ReleaseIntID(id) - logger.AppLog.Debugln("ID Released: ", id) + logger.DrsmLog.Debugln("id released:", id) return nil } else { chunk, found := d.scanChunks[chunkId] @@ -124,7 +124,7 @@ func (d *Drsm) FindOwnerInt32ID(id int32) (*PodId, error) { func (d *Drsm) AcquireIp(pool string) (string, error) { if d.mode == ResourceDemux { - logger.AppLog.Debugf("demux mode can not allocate Ip") + logger.DrsmLog.Debugln("demux mode can not allocate Ip") err := fmt.Errorf("demux mode does not allow Resource allocation") return "", err } @@ -133,7 +133,7 @@ func (d *Drsm) AcquireIp(pool string) (string, error) { func (d *Drsm) ReleaseIp(pool, ip string) error { if d.mode == ResourceDemux { - logger.AppLog.Debugf("demux mode can not Release Resource") + logger.DrsmLog.Debugln("demux mode can not Release Resource") err := fmt.Errorf("demux mode does not allow Resource Release") return err } diff --git a/drsm/chunk.go b/drsm/chunk.go index 6fcfdfa..ffc06cc 100644 --- a/drsm/chunk.go +++ b/drsm/chunk.go @@ -6,7 +6,6 @@ package drsm import ( "fmt" - "log" "math/rand" "strconv" "strings" @@ -25,7 +24,7 @@ func (d *Drsm) GetNewChunk() (*chunk, error) { // We got to allocate new Chunk. We should select // probable chunk number - logger.AppLog.Debugf("Allocate new chunk ") + logger.DrsmLog.Debugln("allocate new chunk") // 14 bits --- 1,2,4,8,16 var cn int32 = 1 for { @@ -37,7 +36,7 @@ func (d *Drsm) GetNewChunk() (*chunk, error) { if found { continue } - logger.AppLog.Debugln("Found chunk Id block ", cn) + logger.DrsmLog.Debugln("found chunk Id block", cn) break } // Let's confirm if this gets updated in DB @@ -46,13 +45,13 @@ func (d *Drsm) GetNewChunk() (*chunk, error) { update := bson.M{"_id": docId, "type": "chunk", "chunkId": docId, "podId": d.clientId.PodName, "podInstance": d.clientId.PodInstance, "podIp": d.clientId.PodIp} inserted := d.mongo.RestfulAPIPostOnly(d.sharedPoolName, filter, update) if !inserted { - log.Printf("Adding chunk %v failed. Retry again ", cn) + logger.DrsmLog.Errorf("Adding chunk %v failed. Retry again", cn) continue } break } - log.Printf("Adding chunk %v success ", cn) + logger.DrsmLog.Infof("Adding chunk %v success", cn) c := &chunk{Id: cn} c.AllocIds = make(map[int32]bool) var i int32 @@ -69,7 +68,7 @@ func (d *Drsm) GetNewChunk() (*chunk, error) { func (c *chunk) AllocateIntID() int32 { if len(c.FreeIds) == 0 { - logger.AppLog.Debugf("FreeIds in chunk 0") + logger.DrsmLog.Debugln("freeIds in chunk 0") return 0 } id := c.FreeIds[len(c.FreeIds)-1] @@ -81,7 +80,7 @@ func (c *chunk) ReleaseIntID(id int32) { i := id & 0x3ff for _, freeid := range c.FreeIds { if freeid == i { - log.Printf("ID %v is already freed", freeid) + logger.DrsmLog.Warnf("id %v is already freed", freeid) return } } @@ -98,7 +97,7 @@ func (c *chunk) ReleaseIntID(id int32) { } func getChunIdFromDocId(id string) int32 { - log.Printf("id received: %v value", id) + logger.DrsmLog.Infof("id received: %v value", id) z := strings.Split(id, "-") if len(z) == 2 && z[0] == "chunkid" { cid, _ := strconv.ParseInt(z[1], 10, 32) diff --git a/drsm/claim.go b/drsm/claim.go index 60e5b6f..86ca9b4 100644 --- a/drsm/claim.go +++ b/drsm/claim.go @@ -13,14 +13,14 @@ import ( func (d *Drsm) podDownDetected() { fmt.Println("started Pod Down goroutine") for p := range d.podDown { - logger.AppLog.Infoln("pod Down detected", p) + logger.DrsmLog.Infoln("pod Down detected", p) // Given Pod find out current Chunks owned by this POD pd := d.podMap[p] for k := range pd.podChunks { d.globalChunkTblMutex.Lock() c, found := d.globalChunkTbl[k] d.globalChunkTblMutex.Unlock() - logger.AppLog.Debugf("found: %v chunk: %v", found, c) + logger.DrsmLog.Debugf("found: %v chunk: %v", found, c) if found { go c.claimChunk(d) } @@ -30,22 +30,22 @@ func (d *Drsm) podDownDetected() { func (c *chunk) claimChunk(d *Drsm) { if d.mode != ResourceClient { - logger.AppLog.Infof("claimChunk ignored demux mode ") + logger.DrsmLog.Infoln("claimChunk ignored demux mode") return } // try to claim. If success then notification will update owner. - logger.AppLog.Debugf("claimChunk started") + logger.DrsmLog.Debugln("claimChunk started") docId := fmt.Sprintf("chunkid-%d", c.Id) update := bson.M{"_id": docId, "type": "chunk", "podId": d.clientId.PodName, "podInstance": d.clientId.PodInstance, "podIp": d.clientId.PodIp} filter := bson.M{"_id": docId, "podId": c.Owner.PodName} updated := d.mongo.RestfulAPIPutOnly(d.sharedPoolName, filter, update) if updated == nil { // TODO : don't add to local pool yet. We can add it only if scan is done. - logger.AppLog.Debugf("claimChunk success") + logger.DrsmLog.Debugln("claimChunk success") c.Owner.PodName = d.clientId.PodName c.Owner.PodIp = d.clientId.PodIp go c.scanChunk(d) } else { - logger.AppLog.Debugf("claimChunk failure ") + logger.DrsmLog.Debugln("claimChunk failure") } } diff --git a/drsm/drsm.go b/drsm/drsm.go index 1621468..efc7777 100644 --- a/drsm/drsm.go +++ b/drsm/drsm.go @@ -4,7 +4,6 @@ package drsm import ( - "log" "sync" "time" @@ -64,13 +63,13 @@ type Drsm struct { func (d *Drsm) DeletePod(podInstance string) { filter := bson.M{"type": "keepalive", "podInstance": podInstance} d.mongo.RestfulAPIDeleteMany(d.sharedPoolName, filter) - logger.AppLog.Infoln("Deleted PodId from DB: ", podInstance) + logger.DrsmLog.Infoln("deleted PodId from DB:", podInstance) } func (d *Drsm) ConstuctDrsm(opt *Options) { if opt != nil { d.mode = opt.Mode - logger.AppLog.Debugln("drsm mode set to ", d.mode) + logger.DrsmLog.Debugln("drsm mode set to", d.mode) if opt.ResIdSize > 0 { d.resIdSize = opt.ResIdSize } else { @@ -79,7 +78,7 @@ func (d *Drsm) ConstuctDrsm(opt *Options) { d.resourceValidCb = opt.ResourceValidCb } d.chunkIdRange = 1 << (d.resIdSize - 10) - log.Printf("ChunkId in the range of 0 to %v ", d.chunkIdRange) + logger.DrsmLog.Debugf("chunkId in the range of 0 to %v", d.chunkIdRange) d.localChunkTbl = make(map[int32]*chunk) d.globalChunkTbl = make(map[int32]*chunk) d.podMap = make(map[string]*podData) @@ -90,7 +89,7 @@ func (d *Drsm) ConstuctDrsm(opt *Options) { //connect to DB d.mongo, _ = MongoDBLibrary.NewMongoClient(d.db.Url, d.db.Name) - logger.AppLog.Debugln("MongoClient is created.", d.db.Name) + logger.DrsmLog.Debugln("mongoClient is created", d.db.Name) go d.handleDbUpdates() go d.punchLiveness() diff --git a/drsm/ipam.go b/drsm/ipam.go index 4957e63..7d0ef4b 100644 --- a/drsm/ipam.go +++ b/drsm/ipam.go @@ -15,17 +15,17 @@ import ( // TODO : should have ability to create new instances of ipam func (d *Drsm) initIpam(opt *Options) { if opt != nil { - logger.AppLog.Debugln("ipmodule ", opt) + logger.DrsmLog.Debugln("ipmodule", opt) } dbOptions := &options.ClientOptions{} dbOptions = dbOptions.ApplyURI(d.db.Url) dbConfig := ipam.MongoConfig{DatabaseName: d.db.Name, CollectionName: "ipaddress", MongoClientOptions: dbOptions} mo, err := ipam.NewMongo(context.TODO(), dbConfig) if err != nil { - logger.AppLog.Debugln("ipmodule error. NewMongo error ", err) + logger.DrsmLog.Debugf("ipmodule error. NewMongo error: %v", err) } ipModule := ipam.NewWithStorage(mo) - logger.AppLog.Debugln("ipmodule ", ipModule) + logger.DrsmLog.Debugln("ipmodule", ipModule) d.ipModule = ipModule d.prefix = make(map[string]*ipam.Prefix) @@ -36,7 +36,7 @@ func (d *Drsm) initIpam(opt *Options) { } d.prefix[k] = prefix } - logger.AppLog.Debugln("ip module prefix ", d.prefix) + logger.DrsmLog.Debugln("ip module prefix", d.prefix) } func (d *Drsm) initIpPool(name string, prefix string) error { @@ -70,7 +70,7 @@ func (d *Drsm) acquireIp(name string) (string, error) { err := fmt.Errorf("no address") return "", err } - logger.AppLog.Debugln("Acquired IP ", ip.IP) + logger.DrsmLog.Debugln("acquired IP", ip.IP) return ip.IP.String(), nil } @@ -83,10 +83,10 @@ func (d *Drsm) releaseIp(name, ip string) error { err := d.ipModule.ReleaseIPFromPrefix(context.TODO(), prefix.Cidr, ip) if err != nil { - logger.AppLog.Debugln("Release IP failed - ", ip) + logger.DrsmLog.Debugln("release IP failed - ", ip) err := fmt.Errorf("no address") return err } - logger.AppLog.Debugln("Release IP successful ", ip) + logger.DrsmLog.Debugln("release IP successful", ip) return nil } diff --git a/drsm/scan.go b/drsm/scan.go index bd74090..fce63bd 100644 --- a/drsm/scan.go +++ b/drsm/scan.go @@ -11,12 +11,12 @@ import ( func (c *chunk) scanChunk(d *Drsm) { if d.mode == ResourceDemux { - logger.AppLog.Infof("Don't perform scan task when demux mode is ON") + logger.DrsmLog.Infoln("do not perform scan task when demux mode is ON") return } if c.Owner.PodName != d.clientId.PodName { - logger.AppLog.Infof("Don't perform scan task if Chunk is not owned by us") + logger.DrsmLog.Infoln("do not perform scan task if Chunk is not owned by us") return } c.State = Scanning @@ -31,7 +31,7 @@ func (c *chunk) scanChunk(d *Drsm) { for { select { case <-ticker.C: - logger.AppLog.Debugf("let's scan one by one id for %v , chunk details %v ", c.Id, c) + logger.DrsmLog.Debugf("let's scan one by one id for %v, chunk details %v", c.Id, c) // TODO : find candidate and then scan that Id. // once all Ids are scanned then we can start using this block if c.resourceValidCb != nil { @@ -50,13 +50,13 @@ func (c *chunk) scanChunk(d *Drsm) { c.State = Owned d.localChunkTbl[c.Id] = c delete(d.scanChunks, c.Id) - logger.AppLog.Debugf("scan complete for Chunk %v", c.Id) + logger.DrsmLog.Debugf("scan complete for Chunk %v", c.Id) return } } //no one is writing on stopScan for now. We will use it eventually case <-c.stopScan: - logger.AppLog.Debugf("received Stop Scan. Closing scan for %v", c.Id) + logger.DrsmLog.Debugf("received Stop Scan. Closing scan for %v", c.Id) return } } diff --git a/drsm/updates.go b/drsm/updates.go index f233cb9..ac2b89d 100644 --- a/drsm/updates.go +++ b/drsm/updates.go @@ -5,7 +5,6 @@ package drsm import ( "context" - "log" "time" "github.com/omec-project/util/logger" @@ -114,7 +113,7 @@ func (d *Drsm) handleDbUpdates() { } func iterateChangeStream(d *Drsm, routineCtx context.Context, stream *mongo.ChangeStream) { - logger.AppLog.Debugln("iterate change stream for podData ", d) + logger.DrsmLog.Debugf("iterate change stream for podData: %v", d) // step 1: Get Pod Keepalive triggers and create POD table // case 2: Update Global Chunk Table. @@ -132,26 +131,26 @@ func iterateChangeStream(d *Drsm, routineCtx context.Context, stream *mongo.Chan var s streamDoc bsonBytes, _ := bson.Marshal(data) bson.Unmarshal(bsonBytes, &s) - //logger.AppLog.Debugf("iterate stream : ", data) - //log.Printf("\ndecoded stream bson %+v \n", s) + //logger.DrsmLog.Debugf("iterate stream : ", data) + //logger.DrsmLog.Debugf("\ndecoded stream bson %+v \n", s) switch s.OpType { case "insert": full := &s.Full switch full.Type { case "keepalive": - //logger.AppLog.Debugf("insert keepalive document") + //logger.DrsmLog.Debugf("insert keepalive document") pod, found := d.podMap[full.PodId] if !found { d.addPod(full) } else { - logger.AppLog.Debugln("keepalive insert document : found existing podId ", pod) + logger.DrsmLog.Debugln("keepalive insert document: found existing podId", pod) } case "chunk": - //logger.AppLog.Debugf("insert chunk document") + //logger.DrsmLog.Debugln("insert chunk document") d.addChunk(full) } case "update": - //logger.AppLog.Debugf("update operations") + //logger.DrsmLog.Debugln("update operations") if isChunkDoc(s.DId.Id) { // update on chunkId.. // looks like chunk owner getting change @@ -166,16 +165,16 @@ func iterateChangeStream(d *Drsm, routineCtx context.Context, stream *mongo.Chan cp.Owner.PodInstance = s.Update.UpdFields.PodInstance podD := d.podMap[owner] podD.podChunks[c] = cp // add chunk to pod - logger.AppLog.Infof("Stream(Update): pod to chunk map %v ", podD.podChunks) + logger.DrsmLog.Infof("stream(Update): pod to chunk map %v", podD.podChunks) } case "delete": - logger.AppLog.Debugf("delete operations") + logger.DrsmLog.Debugln("delete operations") if !isChunkDoc(s.DId.Id) { // not chunk type doc. So its POD doc. // delete olnly gets document id pod, found := d.podMap[s.DId.Id] if pod != nil { - logger.AppLog.Infof("Stream(Delete): Pod %v and found %v. Chunks owned by crashed pod = %v ", pod, found, pod.podChunks) + logger.DrsmLog.Infof("Stream(Delete): Pod %v and found %v. Chunks owned by crashed pod = %v", pod, found, pod.podChunks) d.podDown <- s.DId.Id } } @@ -188,16 +187,16 @@ func (d *Drsm) punchLiveness() { ticker := time.NewTicker(5 * time.Second) defer ticker.Stop() - logger.AppLog.Debugf("document expiry enabled") + logger.DrsmLog.Debugln("document expiry enabled") ret := d.mongo.RestfulAPICreateTTLIndex(d.sharedPoolName, 0, "expireAt") if ret { - logger.AppLog.Debugf("TTL Index created for Field: expireAt in Collection") + logger.DrsmLog.Debugln("ttl index created for Field: expireAt in Collection") } else { - logger.AppLog.Debugf("TTL Index exists for Field: expireAt in Collection") + logger.DrsmLog.Debugln("ttl index exists for Field: expireAt in Collection") } for range ticker.C { - //logger.AppLog.Debugf(" update keepalive time") + //logger.DrsmLog.Debugln("update keepalive time") filter := bson.M{"_id": d.clientId.PodName} timein := time.Now().Local().Add(20 * time.Second) @@ -213,7 +212,7 @@ func (d *Drsm) punchLiveness() { _, err := d.mongo.PutOneCustomDataStructure(d.sharedPoolName, filter, update) if err != nil { - logger.AppLog.Errorln("put data failed : ", err) + logger.DrsmLog.Errorf("put data failed: %v", err) // TODO : should we panic ? continue } @@ -230,13 +229,13 @@ func (d *Drsm) checkAllChunks() { for range ticker.C { filter := bson.M{"type": "chunk"} result, err := d.mongo.RestfulAPIGetMany(d.sharedPoolName, filter) - log.Printf("chunk entry: %v", result) + logger.DrsmLog.Debugf("chunk entry: %v", result) if err == nil && result != nil { for _, v := range result { var s FullStream bsonBytes, _ := bson.Marshal(v) bson.Unmarshal(bsonBytes, &s) - logger.AppLog.Infof("individual Chunk bson Element %v", s) + logger.DrsmLog.Infof("individual Chunk bson Element %v", s) d.addChunk(&s) } } @@ -252,7 +251,7 @@ func (d *Drsm) addChunk(full *FullStream) { if did == "" { did = full.ChunkId } - logger.AppLog.Infof("received Chunk Doc: %v", full) + logger.DrsmLog.Infof("received Chunk Doc: %v", full) cid := getChunIdFromDocId(did) o := PodId{PodName: full.PodId, PodInstance: full.PodInstance, PodIp: full.PodIp} c := &chunk{Id: cid, Owner: o} @@ -264,7 +263,7 @@ func (d *Drsm) addChunk(full *FullStream) { d.globalChunkTbl[cid] = c d.globalChunkTblMutex.Unlock() - logger.AppLog.Infof("Chunk id %v, podChunks %v ", cid, pod.podChunks) + logger.DrsmLog.Infof("chunk id %v, podChunks %v", cid, pod.podChunks) } func (d *Drsm) addPod(full *FullStream) *podData { @@ -272,6 +271,6 @@ func (d *Drsm) addPod(full *FullStream) *podData { pod := &podData{PodId: podI} pod.podChunks = make(map[int32]*chunk) d.podMap[full.PodId] = pod - logger.AppLog.Infof("Keepalive insert d.podMaps %+v", d.podMap) + logger.DrsmLog.Infof("keepalive insert d.podMaps %v", d.podMap) return pod } diff --git a/fsm/fsm.go b/fsm/fsm.go index 59bcdf5..c3e0dbb 100644 --- a/fsm/fsm.go +++ b/fsm/fsm.go @@ -9,7 +9,7 @@ import ( "os" "strings" - "github.com/omec-project/util/fsm/logger" + "github.com/omec-project/util/logger" ) type ( diff --git a/fsm/logger/logger.go b/fsm/logger/logger.go deleted file mode 100644 index 487a7ec..0000000 --- a/fsm/logger/logger.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2019 Communication Service/Software Laboratory, National Chiao Tung University (free5gc.org) -// -// SPDX-License-Identifier: Apache-2.0 - -package logger - -import ( - "time" - - formatter "github.com/antonfisher/nested-logrus-formatter" - "github.com/sirupsen/logrus" -) - -var ( - log *logrus.Logger - FsmLog *logrus.Entry -) - -func init() { - log = logrus.New() - log.SetReportCaller(false) - - log.Formatter = &formatter.Formatter{ - TimestampFormat: time.RFC3339, - TrimMessages: true, - NoFieldsSpace: true, - HideKeys: true, - FieldsOrder: []string{"component", "category"}, - } - - FsmLog = log.WithFields(logrus.Fields{"component": "LIB", "category": "FSM"}) -} - -func GetLogger() *logrus.Logger { - return log -} - -func SetLogLevel(level logrus.Level) { - FsmLog.Infoln("set log level :", level) - log.SetLevel(level) -} - -func SetReportCaller(enable bool) { - FsmLog.Infoln("set report call :", enable) - log.SetReportCaller(enable) -} diff --git a/go.mod b/go.mod index bcc4e7a..c1733e5 100644 --- a/go.mod +++ b/go.mod @@ -3,17 +3,16 @@ module github.com/omec-project/util go 1.21 require ( - github.com/antonfisher/nested-logrus-formatter v1.3.1 github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d github.com/evanphx/json-patch v4.11.0+incompatible github.com/gin-gonic/gin v1.9.1 github.com/mitchellh/mapstructure v1.5.0 github.com/pkg/errors v0.9.1 - github.com/sirupsen/logrus v1.9.3 github.com/smartystreets/goconvey v1.6.4 github.com/stretchr/testify v1.9.0 github.com/thakurajayL/go-ipam v0.0.5-dev go.mongodb.org/mongo-driver v1.17.0 + go.uber.org/zap v1.23.0 golang.org/x/crypto v0.27.0 golang.org/x/net v0.23.0 ) @@ -51,6 +50,7 @@ require ( github.com/montanaflynn/stats v0.7.1 // indirect github.com/pelletier/go-toml/v2 v2.0.8 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/sirupsen/logrus v1.9.3 // indirect github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.11 // indirect @@ -63,7 +63,6 @@ require ( go.etcd.io/etcd/client/v3 v3.5.4 // indirect go.uber.org/atomic v1.9.0 // indirect go.uber.org/multierr v1.8.0 // indirect - go.uber.org/zap v1.23.0 // indirect go4.org/intern v0.0.0-20220617035311-6925f38cc365 // indirect go4.org/unsafe/assume-no-moving-gc v0.0.0-20220617031537-928513b29760 // indirect golang.org/x/arch v0.3.0 // indirect diff --git a/go.sum b/go.sum index ef93f7c..f5f5964 100644 --- a/go.sum +++ b/go.sum @@ -13,8 +13,6 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= -github.com/antonfisher/nested-logrus-formatter v1.3.1 h1:NFJIr+pzwv5QLHTPyKz9UMEoHck02Q9L0FP13b/xSbQ= -github.com/antonfisher/nested-logrus-formatter v1.3.1/go.mod h1:6WTfyWFkBc9+zyBaKIqRrg/KwMqBbodBjgbHjDz7zjA= github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d h1:Byv0BzEl3/e6D5CLfI0j/7hiIEtvGVFPCZ7Ei2oq8iQ= github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= github.com/avast/retry-go/v4 v4.1.0 h1:CwudD9anYv6JMVnDuTRlK6kLo4dBamiL+F3U8YDiyfg= diff --git a/logger/logger.go b/logger/logger.go index f62376d..df25ae9 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -1,216 +1,83 @@ // Copyright 2019 Communication Service/Software Laboratory, National Chiao Tung University (free5gc.org) +// SPDX-FileCopyrightText: 2024 Intel Corporation // // SPDX-License-Identifier: Apache-2.0 package logger import ( - "fmt" "net" "net/http" "net/http/httputil" "os" - "path/filepath" "runtime/debug" - "strconv" "strings" - "time" - formatter "github.com/antonfisher/nested-logrus-formatter" "github.com/gin-gonic/gin" - "github.com/sirupsen/logrus" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" ) -type FileHook struct { - file *os.File - flag int - chmod os.FileMode - formatter *logrus.TextFormatter -} - var ( - log *logrus.Logger - AppLog *logrus.Entry + log *zap.Logger + AppLog *zap.SugaredLogger + DrsmLog *zap.SugaredLogger + FsmLog *zap.SugaredLogger + PathLog *zap.SugaredLogger + UtilLog *zap.SugaredLogger + Util3GPPLog *zap.SugaredLogger + atomicLevel zap.AtomicLevel ) func init() { - log = logrus.New() - log.SetReportCaller(false) - - log.Formatter = &formatter.Formatter{ - TimestampFormat: time.RFC3339, - TrimMessages: true, - NoFieldsSpace: true, - HideKeys: true, - FieldsOrder: []string{"component", "category"}, - } - - AppLog = log.WithFields(logrus.Fields{"component": "DRSM", "category": "App"}) - - log.SetLevel(logrus.DebugLevel) -} - -func SetLogLevel(level logrus.Level) { - log.SetLevel(level) -} - -func SetReportCaller(set bool) { - log.SetReportCaller(set) -} - -// Fire(*Entry) implementation for logrus Hook interface -func (hook *FileHook) Fire(entry *logrus.Entry) error { - var line string - if plainformat, err := hook.formatter.Format(entry); err != nil { - return fmt.Errorf("fileHook formatter error: %+v", err) - } else { - line = string(plainformat) - } - if _, err := hook.file.WriteString(line); err != nil { - return fmt.Errorf("unable to write file on filehook(%s): %+v", line, err) + atomicLevel = zap.NewAtomicLevelAt(zap.InfoLevel) + config := zap.Config{ + Level: atomicLevel, + Development: false, + Encoding: "console", + EncoderConfig: zap.NewProductionEncoderConfig(), + OutputPaths: []string{"stdout"}, + ErrorOutputPaths: []string{"stderr"}, } - return nil -} - -// Levels() implementation for logrus Hook interface -func (hook *FileHook) Levels() []logrus.Level { - return []logrus.Level{ - logrus.PanicLevel, - logrus.FatalLevel, - logrus.ErrorLevel, - logrus.WarnLevel, - logrus.InfoLevel, - logrus.DebugLevel, - logrus.TraceLevel, - } -} - -func NewFileHook(file string, flag int, chmod os.FileMode) (*FileHook, error) { - plainFormatter := &logrus.TextFormatter{DisableColors: true} - logFile, err := os.OpenFile(file, flag, chmod) + config.EncoderConfig.TimeKey = "timestamp" + config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder + config.EncoderConfig.LevelKey = "level" + config.EncoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder + config.EncoderConfig.CallerKey = "caller" + config.EncoderConfig.EncodeCaller = zapcore.ShortCallerEncoder + config.EncoderConfig.MessageKey = "message" + config.EncoderConfig.StacktraceKey = "" + + var err error + log, err = config.Build() if err != nil { - return nil, fmt.Errorf("unable to open file(%s): %+v", file, err) + panic(err) } - return &FileHook{logFile, flag, chmod, plainFormatter}, nil + UtilLog = log.Sugar().With("component", "LIB", "category", "Util") + DrsmLog = log.Sugar().With("component", "LIB", "category", "DRSM") + FsmLog = log.Sugar().With("component", "LIB", "category", "FSM") + PathLog = log.Sugar().With("component", "LIB", "category", "Path") + Util3GPPLog = log.Sugar().With("component", "LIB", "category", "Util3GPP") } -func CreateFree5gcLogFile(file string) (string, error) { - // Because free5gc log file will be used by multiple NFs, it is not recommended to rename. - return createLogFile(file, "", false) -} - -func CreateNfLogFile(file string, defaultName string) (string, error) { - return createLogFile(file, defaultName, true) -} - -/* - * createLogFile - * @param file, The full file path from arguments input by user. - * @param defaultName, Default log file name (if it is empty, it means no default log file will be created) - * @param rename, Modify the file name if the file exists - * @return error, fullPath - */ -func createLogFile(file string, defaultName string, rename bool) (string, error) { - var fullPath string - directory, fileName := filepath.Split(file) - - if directory == "" || fileName == "" { - directory = "./log/" - fileName = defaultName - } - - if fileName == "" { - return "", nil - } - - fullPath = filepath.Join(directory, fileName) - - if rename { - if err := renameOldLogFile(fullPath); err != nil { - return "", err - } - } - - if err := os.MkdirAll(directory, 0775); err != nil { - return "", fmt.Errorf("make directory(%s) failed: %+v", directory, err) - } - - sudoUID, errUID := strconv.Atoi(os.Getenv("SUDO_UID")) - sudoGID, errGID := strconv.Atoi(os.Getenv("SUDO_GID")) - if errUID == nil && errGID == nil { - // if using sudo to run the program, errUID will be nil and sudoUID will get the uid who run sudo - // else errUID will not be nil and sudoUID will be nil - // If user using sudo to run the program and create log file, log will own by root, - // here we change own to user so user can view and reuse the file - if err := os.Chown(directory, sudoUID, sudoGID); err != nil { - return "", fmt.Errorf("directory(%s) chown to [%d:%d] error: %+v", directory, sudoUID, sudoGID, err) - } - - // Create log file or if it already exist, check if user can access it - if f, err := os.OpenFile(fullPath, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666); err != nil { - // user cannot access it. - return "", fmt.Errorf("cannot Open [%s] error: %+v", fullPath, err) - } else { - // user can access it - if err := f.Close(); err != nil { - return "", fmt.Errorf("file [%s] cannot been closed", fullPath) - } - if err := os.Chown(fullPath, sudoUID, sudoGID); err != nil { - return "", fmt.Errorf("file [%s] chown to [%d:%d] error: %+v", fullPath, sudoUID, sudoGID, err) - } - } - } - - return fullPath, nil -} - -func renameOldLogFile(fullPath string) error { - _, err := os.Stat(fullPath) - - if os.IsNotExist(err) { - return nil - } - - counter := 0 - sep := "." - fileDir, fileName := filepath.Split(fullPath) - - if contents, err := os.ReadDir(fileDir); err != nil { - return fmt.Errorf("reads the directory(%s) error %+v", fileDir, err) - } else { - for _, content := range contents { - if !content.IsDir() { - if strings.Contains(content.Name(), (fileName + sep)) { - counter++ - } - } - } - } - - newFullPath := fmt.Sprintf("%s%s%s%d", fileDir, fileName, sep, (counter + 1)) - if err := os.Rename(fullPath, newFullPath); err != nil { - return fmt.Errorf("unable to rename file(%s) %+v", newFullPath, err) - } - - return nil +func SetLogLevel(level zapcore.Level) { + UtilLog.Infoln("set log level:", level) + atomicLevel.SetLevel(level) } -// NewGinWithLogrus - returns an Engine instance with the ginToLogrus and Recovery middleware already attached. -func NewGinWithLogrus(log *logrus.Entry) *gin.Engine { +func NewGinWithZap(logger *zap.SugaredLogger) *gin.Engine { engine := gin.New() - engine.Use(ginToLogrus(log), ginRecover(log)) + engine.Use(ginToZap(logger), ginRecover(logger)) return engine } -// The Middleware will write the Gin logs to logrus. -func ginToLogrus(log *logrus.Entry) gin.HandlerFunc { +func ginToZap(logger *zap.SugaredLogger) gin.HandlerFunc { return func(c *gin.Context) { path := c.Request.URL.Path raw := c.Request.URL.RawQuery - // Process request c.Next() clientIP := c.ClientIP() @@ -222,17 +89,15 @@ func ginToLogrus(log *logrus.Entry) gin.HandlerFunc { path = path + "?" + raw } - log.Infof("| %3d | %15s | %-7s | %s | %s", + logger.Infof("| %3d | %15s | %-7s | %s | %s", statusCode, clientIP, method, path, errorMessage) } } -// The Middleware will recover the Gin panic to logrus. -func ginRecover(log *logrus.Entry) gin.HandlerFunc { +func ginRecover(logger *zap.SugaredLogger) gin.HandlerFunc { return func(c *gin.Context) { defer func() { if p := recover(); p != nil { - // Check for a broken connection, as it is not really a condition that warrants a panic stack trace. var brokenPipe bool if ne, ok := p.(*net.OpError); ok { if se, ok := ne.Err.(*os.SyscallError); ok { @@ -243,10 +108,10 @@ func ginRecover(log *logrus.Entry) gin.HandlerFunc { } } - if log != nil { + if logger != nil { stack := string(debug.Stack()) if httpRequest, err := httputil.DumpRequest(c.Request, false); err != nil { - log.Errorf("dump http request error: %v", err) + logger.Errorf("dump http request error: %v", err) } else { headers := strings.Split(string(httpRequest), "\r\n") for idx, header := range headers { @@ -256,18 +121,16 @@ func ginRecover(log *logrus.Entry) gin.HandlerFunc { } } - // changing Fatalf to Errorf to let program not be exited if brokenPipe { - log.Errorf("%v\n%s", p, string(httpRequest)) + logger.Errorf("%v\n%s", p, string(httpRequest)) } else if gin.IsDebugging() { - log.Errorf("[Debugging] panic:\n%s\n%v\n%s", strings.Join(headers, "\r\n"), p, stack) + logger.Errorf("[Debugging] panic:\n%s\n%v\n%s", strings.Join(headers, "\r"), p, stack) } else { - log.Errorf("panic: %v\n%s", p, stack) + logger.Errorf("panic: %v\n%s", p, stack) } } } - // If the connection is dead, we can't write a status to it. if brokenPipe { c.Error(p.(error)) // nolint: errcheck c.Abort() diff --git a/logger/logger_config.go b/logger/logger_config.go index 406ae42..8ce607a 100644 --- a/logger/logger_config.go +++ b/logger/logger_config.go @@ -11,25 +11,25 @@ import ( ) type Logger struct { - AMF *LogSetting `yaml:"AMF" valid:"optional"` - AUSF *LogSetting `yaml:"AUSF" valid:"optional"` - N3IWF *LogSetting `yaml:"N3IWF" valid:"optional"` - NRF *LogSetting `yaml:"NRF" valid:"optional"` - NSSF *LogSetting `yaml:"NSSF" valid:"optional"` - PCF *LogSetting `yaml:"PCF" valid:"optional"` - SMF *LogSetting `yaml:"SMF" valid:"optional"` - UDM *LogSetting `yaml:"UDM" valid:"optional"` - UDR *LogSetting `yaml:"UDR" valid:"optional"` - UPF *LogSetting `yaml:"UPF" valid:"optional"` - NEF *LogSetting `yaml:"NEF" valid:"optional"` - BSF *LogSetting `yaml:"BSF" valid:"optional"` - CHF *LogSetting `yaml:"CHF" valid:"optional"` - UDSF *LogSetting `yaml:"UDSF" valid:"optional"` - NWDAF *LogSetting `yaml:"NWDAF" valid:"optional"` - WEBUI *LogSetting `yaml:"WEBUI" valid:"optional"` + AMF *LogSetting `yaml:"AMF" valid:"optional"` + AUSF *LogSetting `yaml:"AUSF" valid:"optional"` + N3IWF *LogSetting `yaml:"N3IWF" valid:"optional"` + NRF *LogSetting `yaml:"NRF" valid:"optional"` + NSSF *LogSetting `yaml:"NSSF" valid:"optional"` + PCF *LogSetting `yaml:"PCF" valid:"optional"` + SMF *LogSetting `yaml:"SMF" valid:"optional"` + UDM *LogSetting `yaml:"UDM" valid:"optional"` + UDR *LogSetting `yaml:"UDR" valid:"optional"` + UPF *LogSetting `yaml:"UPF" valid:"optional"` + NEF *LogSetting `yaml:"NEF" valid:"optional"` + BSF *LogSetting `yaml:"BSF" valid:"optional"` + CHF *LogSetting `yaml:"CHF" valid:"optional"` + UDSF *LogSetting `yaml:"UDSF" valid:"optional"` + NWDAF *LogSetting `yaml:"NWDAF" valid:"optional"` + WEBUI *LogSetting `yaml:"WEBUI" valid:"optional"` + SCTPLB *LogSetting `yaml:"SCTPLB" valid:"optional"` Aper *LogSetting `yaml:"Aper" valid:"optional"` - CommonConsumerTest *LogSetting `yaml:"CommonConsumerTest" valid:"optional"` FSM *LogSetting `yaml:"FSM" valid:"optional"` MongoDBLibrary *LogSetting `yaml:"MongoDBLibrary" valid:"optional"` NAS *LogSetting `yaml:"NAS" valid:"optional"` @@ -66,13 +66,12 @@ func (l *Logger) Validate() (bool, error) { type LogSetting struct { DebugLevel string `yaml:"debugLevel" valid:"debugLevel"` - ReportCaller bool `yaml:"ReportCaller" valid:"type(bool)"` } func (l *LogSetting) validate() (bool, error) { govalidator.TagMap["debugLevel"] = govalidator.Validator(func(str string) bool { if str == "panic" || str == "fatal" || str == "error" || str == "warn" || - str == "info" || str == "debug" || str == "trace" { + str == "info" || str == "debug" { return true } else { return false diff --git a/logger_conf/conf.go b/logger_conf/conf.go deleted file mode 100644 index 364c0f4..0000000 --- a/logger_conf/conf.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2019 Communication Service/Software Laboratory, National Chiao Tung University (free5gc.org) -// -// SPDX-License-Identifier: Apache-2.0 - -package logger_conf - -import ( - "log" - "os" - "strconv" - - "github.com/omec-project/util/path_util" -) - -var Free5gcLogDir string = path_util.Free5gcPath("free5gc/log") + "/" -var LibLogDir string = Free5gcLogDir + "lib/" -var NfLogDir string = Free5gcLogDir + "nf/" - -var Free5gcLogFile string = Free5gcLogDir + "free5gc.log" - -func init() { - if err := os.MkdirAll(LibLogDir, 0775); err != nil { - log.Printf("Mkdir %s failed: %+v", LibLogDir, err) - } - if err := os.MkdirAll(NfLogDir, 0775); err != nil { - log.Printf("Mkdir %s failed: %+v", NfLogDir, err) - } - - // Create log file or if it already exist, check if user can access it - f, fileOpenErr := os.OpenFile(Free5gcLogFile, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) - if fileOpenErr != nil { - // user cannot access it. - log.Printf("Cannot Open %s\n", Free5gcLogFile) - } else { - // user can access it - if err := f.Close(); err != nil { - log.Printf("File %s cannot been closed\n", Free5gcLogFile) - } - } - - sudoUID, errUID := strconv.Atoi(os.Getenv("SUDO_UID")) - sudoGID, errGID := strconv.Atoi(os.Getenv("SUDO_GID")) - - if errUID == nil && errGID == nil { - // if using sudo to run the program, errUID will be nil and sudoUID will get the uid who run sudo - // else errUID will not be nil and sudoUID will be nil - // If user using sudo to run the program and create log file, log will own by root, - // here we change own to user so user can view and reuse the file - if err := os.Chown(Free5gcLogDir, sudoUID, sudoGID); err != nil { - log.Printf("Dir %s chown to %d:%d error: %v\n", Free5gcLogDir, sudoUID, sudoGID, err) - } - if err := os.Chown(LibLogDir, sudoUID, sudoGID); err != nil { - log.Printf("Dir %s chown to %d:%d error: %v\n", LibLogDir, sudoUID, sudoGID, err) - } - if err := os.Chown(NfLogDir, sudoUID, sudoGID); err != nil { - log.Printf("Dir %s chown to %d:%d error: %v\n", NfLogDir, sudoUID, sudoGID, err) - } - - if fileOpenErr == nil { - if err := os.Chown(Free5gcLogFile, sudoUID, sudoGID); err != nil { - log.Printf("File %s chown to %d:%d error: %v\n", Free5gcLogFile, sudoUID, sudoGID, err) - } - } - } -} diff --git a/mongoapi/dbtestapp/dbtestapp.go b/mongoapi/dbtestapp/dbtestapp.go index 237760c..ba3c31a 100644 --- a/mongoapi/dbtestapp/dbtestapp.go +++ b/mongoapi/dbtestapp/dbtestapp.go @@ -7,8 +7,8 @@ package main import ( + "github.com/omec-project/util/logger" "github.com/omec-project/util/mongoapi" - "log" ) var mongoHndl *mongoapi.MongoClient @@ -17,7 +17,7 @@ var mongoHndl *mongoapi.MongoClient // TODO : inbuild shell commands to func main() { - log.Println("dbtestapp started") + logger.AppLog.Infoln("dbtestapp started") // connect to mongoDB mongoHndl, _ = mongoapi.NewMongoClient("mongodb://mongodb-arbiter-headless", "sdcore") diff --git a/mongoapi/dbtestapp/drsmapp.go b/mongoapi/dbtestapp/drsmapp.go index 5526231..8536ad6 100644 --- a/mongoapi/dbtestapp/drsmapp.go +++ b/mongoapi/dbtestapp/drsmapp.go @@ -8,7 +8,6 @@ package main import ( "github.com/omec-project/util/drsm" "github.com/omec-project/util/logger" - "log" "os" "time" ) @@ -23,13 +22,13 @@ type drsmInterface struct { var drsmIntf drsmInterface func scanChunk(i int32) bool { - logger.AppLog.Debugf("Received callback from module to scan Chunk resource %+v", i) + logger.AppLog.Debugf("received callback from module to scan Chunk resource %+v", i) return false } func initDrsm(resName string) { - if drsmIntf.initDrsm == true { + if drsmIntf.initDrsm { return } drsmIntf.initDrsm = true @@ -43,7 +42,7 @@ func initDrsm(resName string) { t := time.Now().UnixNano() opt := &drsm.Options{} if t%2 == 0 { - logger.AppLog.Debugf("Running in Demux Mode") + logger.AppLog.Debugln("running in Demux Mode") drsmIntf.Mode = drsm.ResourceDemux } else { opt.ResourceValidCb = scanChunk @@ -58,10 +57,10 @@ func initDrsm(resName string) { func AllocateInt32One(resName string) int32 { id, err := drsmIntf.d.AllocateInt32ID() if err != nil { - logger.AppLog.Debugf("Id allocation error %+v", err) + logger.AppLog.Debugf("id allocation error %+v", err) return 0 } - log.Printf("Received id %v ", id) + logger.AppLog.Infof("received id %d", id) return id } @@ -71,26 +70,24 @@ func AllocateInt32Many(resName string, number int32) []int32 { var count int32 = 0 ticker := time.NewTicker(50 * time.Millisecond) - for { - select { - case <-ticker.C: - id, _ := drsmIntf.d.AllocateInt32ID() - if id != 0 { - resIds = append(resIds, id) - } - log.Printf("Received id %v ", id) - count++ - if count >= number { - return resIds - } + for range ticker.C { + id, _ := drsmIntf.d.AllocateInt32ID() + if id != 0 { + resIds = append(resIds, id) + } + logger.AppLog.Infof("received id %d", id) + count++ + if count >= number { + return resIds } } + return resIds } func ReleaseInt32One(resName string, resId int32) error { err := drsmIntf.d.ReleaseInt32ID(resId) if err != nil { - logger.AppLog.Debugf("Id release error %+v", err) + logger.AppLog.Debugf("id release error %+v", err) return err } return nil @@ -99,10 +96,10 @@ func ReleaseInt32One(resName string, resId int32) error { func IpAddressAllocOne(pool string) (string, error) { ip, err := drsmIntf.d.AcquireIp(pool) if err != nil { - log.Printf("%+v : Ip allocation error %+v", pool, err) + logger.AppLog.Errorf("%+v: ip allocation error %+v", pool, err) return "", err } - log.Printf("%v : Received ip %v ", pool, ip) + logger.AppLog.Infof("%v: received ip %v", pool, ip) return ip, nil } @@ -111,22 +108,20 @@ func IpAddressAllocMany(pool string, number int32) []string { var count int32 = 0 ticker := time.NewTicker(50 * time.Millisecond) - for { - select { - case <-ticker.C: - ip, err := drsmIntf.d.AcquireIp(pool) - if err != nil { - log.Printf("%v : Ip allocation error %v", pool, err) - } else { - log.Printf("%v : Received ip %v ", pool, ip) - resIds = append(resIds, ip) - } - count++ - if count >= number { - return resIds - } + for range ticker.C { + ip, err := drsmIntf.d.AcquireIp(pool) + if err != nil { + logger.AppLog.Errorf("%v: ip allocation error %v", pool, err) + } else { + logger.AppLog.Infof("%v: received ip %v", pool, ip) + resIds = append(resIds, ip) + } + count++ + if count >= number { + return resIds } } + return resIds } func IpAddressRelease(pool, ip string) error { diff --git a/mongoapi/dbtestapp/go.mod b/mongoapi/dbtestapp/go.mod index 79b02c2..4422caa 100644 --- a/mongoapi/dbtestapp/go.mod +++ b/mongoapi/dbtestapp/go.mod @@ -41,7 +41,7 @@ require ( github.com/mattn/go-isatty v0.0.20 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect - github.com/montanaflynn/stats v0.6.6 // indirect + github.com/montanaflynn/stats v0.7.1 // indirect github.com/pelletier/go-toml/v2 v2.2.2 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/sirupsen/logrus v1.9.0 // indirect @@ -49,9 +49,9 @@ require ( github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect github.com/xdg-go/pbkdf2 v1.0.0 // indirect - github.com/xdg-go/scram v1.1.1 // indirect - github.com/xdg-go/stringprep v1.0.3 // indirect - github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a // indirect + github.com/xdg-go/scram v1.1.2 // indirect + github.com/xdg-go/stringprep v1.0.4 // indirect + github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect go.etcd.io/etcd/api/v3 v3.5.4 // indirect go.etcd.io/etcd/client/pkg/v3 v3.5.4 // indirect go.etcd.io/etcd/client/v3 v3.5.4 // indirect @@ -61,11 +61,11 @@ require ( go4.org/intern v0.0.0-20220617035311-6925f38cc365 // indirect go4.org/unsafe/assume-no-moving-gc v0.0.0-20220617031537-928513b29760 // indirect golang.org/x/arch v0.8.0 // indirect - golang.org/x/crypto v0.23.0 // indirect + golang.org/x/crypto v0.27.0 // indirect golang.org/x/net v0.25.0 // indirect - golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde // indirect - golang.org/x/sys v0.20.0 // indirect - golang.org/x/text v0.15.0 // indirect + golang.org/x/sync v0.8.0 // indirect + golang.org/x/sys v0.25.0 // indirect + golang.org/x/text v0.18.0 // indirect google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect google.golang.org/grpc v1.56.3 // indirect google.golang.org/protobuf v1.34.1 // indirect diff --git a/mongoapi/dbtestapp/go.sum b/mongoapi/dbtestapp/go.sum index bcc15b0..e387c8c 100644 --- a/mongoapi/dbtestapp/go.sum +++ b/mongoapi/dbtestapp/go.sum @@ -200,8 +200,8 @@ github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3Rllmb github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= -github.com/montanaflynn/stats v0.6.6 h1:Duep6KMIDpY4Yo11iFsvyqJDyfzLF9+sndUKT+v64GQ= -github.com/montanaflynn/stats v0.6.6/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= +github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE= +github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= @@ -282,17 +282,20 @@ github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65E github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= -github.com/xdg-go/scram v1.1.1 h1:VOMT+81stJgXW3CpHyqHN3AXDYIMsx56mEFrB37Mb/E= github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g= -github.com/xdg-go/stringprep v1.0.3 h1:kdwGpVNwPFtjs98xCGkHjQtGKh86rDcRZN17QEMCOIs= +github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8= +github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= -github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a h1:fZHgsYlfvtyqToslyjUt3VOPF4J7aK/3MPcK7xp3PDk= -github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a/go.mod h1:ul22v+Nro/R083muKhosV54bj5niojjWZvU8xrevuH4= +github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM= +github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.etcd.io/etcd/api/v3 v3.5.4 h1:OHVyt3TopwtUQ2GKdd5wu3PmmipR4FTwCqoEjSyRdIc= go.etcd.io/etcd/api/v3 v3.5.4/go.mod h1:5GB2vv4A4AOn3yk7MftYGHkUfGtDHnEraIjym4dYz5A= go.etcd.io/etcd/client/pkg/v3 v3.5.4 h1:lrneYvz923dvC14R54XcA7FXoZ3mlGZAgmwhfm7HqOg= @@ -326,11 +329,11 @@ golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= -golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= +golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= @@ -340,6 +343,7 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -353,9 +357,11 @@ golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -369,8 +375,9 @@ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde h1:ejfdSekXMDxDLbRrJMwUk6KnSLZ2McaUCVcIKM+N6jc= -golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -393,20 +400,24 @@ golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211107104306-e0b2ad06fe42/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= -golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= +golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= -golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= +golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= @@ -419,6 +430,7 @@ golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/mongoapi/dbtestapp/routers.go b/mongoapi/dbtestapp/routers.go index 8c6563d..07f7044 100644 --- a/mongoapi/dbtestapp/routers.go +++ b/mongoapi/dbtestapp/routers.go @@ -5,11 +5,12 @@ package main import ( - "github.com/gin-contrib/cors" - "github.com/gin-gonic/gin" - "log" "net/http" "strconv" + + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" + "github.com/omec-project/util/logger" ) // Route is the information for every URI. @@ -145,7 +146,7 @@ func http_server() { httpAddr := ":" + strconv.Itoa(8000) engine.Run(httpAddr) - log.Println("Webserver stopped/terminated/not-started ") + logger.AppLog.Infoln("webserver stopped/terminated/not-started") } func Index(c *gin.Context) { @@ -155,53 +156,51 @@ func Index(c *gin.Context) { func IntegerResourceNamePost(c *gin.Context) { c.String(http.StatusOK, "IntegerResourceNamePost!") resName, exists := c.Params.Get("resource-name") - if exists == false { - log.Printf("Received resource delete. resource-name not found ") + if !exists { + logger.AppLog.Warnln("received resource delete. resource-name not found") c.JSON(http.StatusBadRequest, gin.H{}) return } number, ok := c.GetQuery("number") - if ok == true { + if ok { n1, _ := strconv.Atoi(number) - var n int32 - n = int32(n1) + n := int32(n1) resId := AllocateInt32Many(resName, n) if len(resId) == 0 { - log.Println("Id allocation error ") + logger.AppLog.Errorln("id allocation error") c.JSON(http.StatusBadRequest, gin.H{}) } - log.Printf("Received resource create. Pool name %v, Pool Id %v ", resName, resId) + logger.AppLog.Infof("received resource create. Pool name %v, Pool Id %v", resName, resId) c.JSON(http.StatusOK, gin.H{}) } else { resId := AllocateInt32One(resName) if resId == 0 { - log.Println("Id allocation error ") + logger.AppLog.Errorln("id allocation error") c.JSON(http.StatusBadRequest, gin.H{}) } - log.Printf("Received resource create. Pool name %v, Pool Id %v ", resName, resId) + logger.AppLog.Infof("received resource create. Pool name %v, Pool Id %v", resName, resId) c.JSON(http.StatusOK, gin.H{}) } - return } func IntegerResourceNameDelete(c *gin.Context) { c.String(http.StatusOK, "IntegerResourceNameDelete!") resName, exists := c.Params.Get("resource-name") - if exists == false { - log.Printf("Received resource delete. resource-name not found ") + if !exists { + logger.AppLog.Warnln("received resource delete. resource-name not found") c.JSON(http.StatusBadRequest, gin.H{}) return } - log.Printf("Received resource delete. Pool name %v ", resName) + logger.AppLog.Infof("received resource delete. Pool name %v", resName) resId, exists := c.Params.Get("resource-id") - if exists == false { - log.Printf("resource-id param not found ") + if !exists { + logger.AppLog.Warnln("resource-id param not found") c.JSON(http.StatusBadRequest, gin.H{}) return } - log.Printf("Received resource delete. Res Id %v ", resId) + logger.AppLog.Infof("received resource delete. Res Id %v", resId) r, _ := strconv.Atoi(resId) rid := int32(r) @@ -211,127 +210,123 @@ func IntegerResourceNameDelete(c *gin.Context) { } else { c.JSON(http.StatusOK, gin.H{}) } - return } func Ipv4ResourceNamePost(c *gin.Context) { c.String(http.StatusOK, "Ipv4ResourceNamePost!") resName, exists := c.Params.Get("resource-name") - if exists == false { - log.Printf("Received resource delete. resource-name not found ") + if !exists { + logger.AppLog.Warnln("received resource delete. resource-name not found") c.JSON(http.StatusBadRequest, gin.H{}) return } number, ok := c.GetQuery("number") - if ok == true { + if ok { n1, _ := strconv.Atoi(number) - var n int32 - n = int32(n1) + n := int32(n1) resId := IpAddressAllocMany(resName, n) if len(resId) == 0 { - log.Println("Id allocation error ") + logger.AppLog.Errorln("id allocation error") c.JSON(http.StatusBadRequest, gin.H{}) } - log.Printf("Received resource create. Pool name %v, Pool Id %v ", resName, resId) + logger.AppLog.Infof("received resource create. Pool name %v, Pool Id %v", resName, resId) c.JSON(http.StatusOK, gin.H{}) } else { resId, err := IpAddressAllocOne(resName) if err != nil { - log.Println("Id allocation error ") + logger.AppLog.Errorln("id allocation error") c.JSON(http.StatusBadRequest, gin.H{}) } - log.Printf("Received resource create. Pool name %v, Pool Id %v ", resName, resId) + logger.AppLog.Infof("received resource create. Pool name %v, Pool Id %v", resName, resId) c.JSON(http.StatusOK, gin.H{}) } - return } func Ipv4ResourceNameDelete(c *gin.Context) { c.String(http.StatusOK, "Ipv4ResourceNameDelete!") resName, exists := c.Params.Get("resource-name") - if exists == false { - log.Printf("Received resource delete. resource-name not found ") + if !exists { + logger.AppLog.Warnln("received resource delete. resource-name not found") c.JSON(http.StatusBadRequest, gin.H{}) return } - log.Printf("Received resource delete. Pool name %v ", resName) + logger.AppLog.Infof("received resource delete. Pool name %v", resName) resId, exists := c.Params.Get("resource-id") - if exists == false { - log.Printf("resource-id param not found ") + if !exists { + logger.AppLog.Warnln("resource-id param not found") c.JSON(http.StatusBadRequest, gin.H{}) return } - log.Printf("Received resource delete. Res Id %v ", resId) + logger.AppLog.Infof("received resource delete. Res Id %v", resId) err := IpAddressRelease(resName, resId) if err != nil { - log.Printf("IP address %v release failed - %v ", resId, err) + logger.AppLog.Errorf("ip address %v release failed - %v", resId, err) c.JSON(http.StatusBadRequest, gin.H{}) } else { - log.Printf("IP address %v release success ", resId) + logger.AppLog.Infof("ip address %v release success", resId) c.JSON(http.StatusOK, gin.H{}) } - return } func GetUniqueIdentityTest(c *gin.Context) { c.String(http.StatusOK, "GetUniqueIdentityTest!") resName, exists := c.Params.Get("pool") - if exists == false { - log.Printf("pool param missing in URI") + if !exists { + logger.AppLog.Warnln("pool param missing in URI") c.JSON(http.StatusBadRequest, gin.H{}) return } uniqueId := mongoHndl.GetUniqueIdentity(resName) - log.Println(uniqueId) + logger.AppLog.Infoln(uniqueId) c.JSON(http.StatusOK, gin.H{}) } func GetUniqueIdentityWithinRangeTest(c *gin.Context) { c.String(http.StatusOK, "GetUniqueIdentityWithinRangeTest!") resName, exists := c.Params.Get("pool") - if exists == false { - log.Printf("pool param missing in URI") + if !exists { + logger.AppLog.Infoln("pool param missing in URI") c.JSON(http.StatusBadRequest, gin.H{}) return } min, ok := GetQuery("min", c) - if ok == false { + if !ok { c.JSON(http.StatusBadRequest, gin.H{}) return } max, ok := GetQuery("max", c) - if ok == false { + if !ok { c.JSON(http.StatusBadRequest, gin.H{}) return } uniqueId := mongoHndl.GetUniqueIdentityWithinRange(resName, min, max) - log.Println(uniqueId) + logger.AppLog.Infoln(uniqueId) c.JSON(http.StatusOK, gin.H{}) } func GetIdFromPoolTest(c *gin.Context) { - log.Println("TESTING POOL OF IDS") + logger.AppLog.Infoln("testing pool of ids") poolName, exists := c.Params.Get("pool") - if exists == false { - log.Printf("pool param missing in URI") + if !exists { + logger.AppLog.Infoln("pool param missing in URI") c.JSON(http.StatusBadRequest, gin.H{}) return } min, ok := GetQuery("min", c) - if ok == false { + if !ok { c.JSON(http.StatusBadRequest, gin.H{}) return } max, ok := GetQuery("max", c) - if ok == false { + if !ok { c.JSON(http.StatusBadRequest, gin.H{}) return } @@ -339,44 +334,44 @@ func GetIdFromPoolTest(c *gin.Context) { mongoHndl.InitializePool(poolName, min, max) uniqueId, err := mongoHndl.GetIDFromPool(poolName) - log.Println(uniqueId, err) + logger.AppLog.Infoln(uniqueId, err) mongoHndl.ReleaseIDToPool(poolName, uniqueId) uniqueId, err = mongoHndl.GetIDFromPool(poolName) - log.Println(uniqueId, err) + logger.AppLog.Infoln(uniqueId, err) uniqueId, err = mongoHndl.GetIDFromPool(poolName) - log.Println(uniqueId, err) + logger.AppLog.Infoln(uniqueId, err) c.JSON(http.StatusOK, gin.H{}) } func GetIdFromInsertPoolTest(c *gin.Context) { - log.Println("TESTING INSERT APPROACH") + logger.AppLog.Infoln("testing insert approach") var randomId int32 pool, exists := c.Params.Get("pool") - if exists == false { - log.Printf("pool param missing in URI") + if !exists { + logger.AppLog.Infoln("pool param missing in URI") c.JSON(http.StatusBadRequest, gin.H{}) return } min, ok := GetQuery("min", c) - if ok == false { + if !ok { c.JSON(http.StatusBadRequest, gin.H{}) return } max, ok := GetQuery("max", c) - if ok == false { + if !ok { c.JSON(http.StatusBadRequest, gin.H{}) return } retry, ok := GetQuery("retry", c) - if ok == false { + if !ok { c.JSON(http.StatusBadRequest, gin.H{}) return } @@ -384,21 +379,21 @@ func GetIdFromInsertPoolTest(c *gin.Context) { mongoHndl.InitializeInsertPool(pool, min, max, retry) randomId, err := mongoHndl.GetIDFromInsertPool(pool) - log.Println(randomId) + logger.AppLog.Infoln(randomId) if err != nil { - log.Println(err.Error()) + logger.AppLog.Errorln(err.Error()) } randomId, err = mongoHndl.GetIDFromInsertPool(pool) - log.Println(randomId) + logger.AppLog.Infoln(randomId) if err != nil { - log.Println(err.Error()) + logger.AppLog.Errorln(err.Error()) } randomId, err = mongoHndl.GetIDFromInsertPool(pool) - log.Println(randomId) + logger.AppLog.Infoln(randomId) if err != nil { - log.Println(err.Error()) + logger.AppLog.Errorln(err.Error()) } mongoHndl.ReleaseIDToInsertPool(pool, randomId) @@ -406,37 +401,37 @@ func GetIdFromInsertPoolTest(c *gin.Context) { } func GetChunkFromPoolTest(c *gin.Context) { - log.Println("TESTING CHUNK APPROACH") + logger.AppLog.Infoln("testing chunk approach") var lower int32 var upper int32 resName, exists := c.Params.Get("chunk") - if exists == false { - log.Printf("chunk param missing in URI") + if !exists { + logger.AppLog.Warnln("chunk param missing in URI") c.JSON(http.StatusBadRequest, gin.H{}) return } min, ok := GetQuery("min", c) - if ok == false { + if !ok { c.JSON(http.StatusBadRequest, gin.H{}) return } max, ok := GetQuery("max", c) - if ok == false { + if !ok { c.JSON(http.StatusBadRequest, gin.H{}) return } retry, ok := GetQuery("retry", c) - if ok == false { + if !ok { c.JSON(http.StatusBadRequest, gin.H{}) return } csize, ok := GetQuery("csize", c) - if ok == false { + if !ok { c.JSON(http.StatusBadRequest, gin.H{}) return } @@ -444,21 +439,21 @@ func GetChunkFromPoolTest(c *gin.Context) { mongoHndl.InitializeChunkPool(resName, min, max, retry, csize) // min, max, retries, chunkSize randomId, lower, upper, err := mongoHndl.GetChunkFromPool(resName) - log.Println(randomId, lower, upper) + logger.AppLog.Infoln(randomId, lower, upper) if err != nil { - log.Println(err.Error()) + logger.AppLog.Errorln(err.Error()) } randomId, lower, upper, err = mongoHndl.GetChunkFromPool(resName) - log.Println(randomId, lower, upper) + logger.AppLog.Infoln(randomId, lower, upper) if err != nil { - log.Println(err.Error()) + logger.AppLog.Errorln(err.Error()) } randomId, lower, upper, err = mongoHndl.GetChunkFromPool(resName) - log.Println(randomId, lower, upper) + logger.AppLog.Infoln(randomId, lower, upper) if err != nil { - log.Println(err.Error()) + logger.AppLog.Errorln(err.Error()) } mongoHndl.ReleaseChunkToPool(resName, randomId) @@ -469,7 +464,7 @@ func GetChunkFromPoolTest(c *gin.Context) { func GetQuery(param string, c *gin.Context) (int32, bool) { p1, ok := c.GetQuery(param) - if ok == false { + if !ok { return 0, false } p2, _ := strconv.Atoi(p1) diff --git a/mongoapi/dbtestapp/student.go b/mongoapi/dbtestapp/student.go index 6d9a34d..5ab0b3a 100644 --- a/mongoapi/dbtestapp/student.go +++ b/mongoapi/dbtestapp/student.go @@ -7,11 +7,12 @@ package main import ( - "github.com/gin-gonic/gin" - "go.mongodb.org/mongo-driver/bson" - "log" "net/http" "time" + + "github.com/gin-gonic/gin" + "github.com/omec-project/util/logger" + "go.mongodb.org/mongo-driver/bson" ) type Student struct { @@ -28,7 +29,7 @@ func StudentRecordTest(c *gin.Context) { collName := "student" _, errVal := mongoHndl.CreateIndex(collName, "Name") if errVal != nil { - log.Println("Create index failed on Name field : ", errVal) + logger.AppLog.Errorln("create index failed on Name field:", errVal) } //add document to student collection. @@ -38,9 +39,9 @@ func StudentRecordTest(c *gin.Context) { //fetch document from student db based on index student, err := getStudentFromDB(collName, "Osman Amjad") if err == nil { - log.Printf("Retrieved student %v ", student) + logger.AppLog.Infof("retrieved student %v", student) } else { - log.Printf("Failed to retrieve student %v. Error - %+v", student, err) + logger.AppLog.Errorf("failed to retrieve student %v. Error - %+v", student, err) } insertStudentInDB(collName, "John Smith", 25) @@ -49,9 +50,9 @@ func StudentRecordTest(c *gin.Context) { qName := "Nerf Doodle" _, err = getStudentFromDB(collName, qName) if err == nil { - log.Printf("Retrieved student %v ", qName) + logger.AppLog.Infof("retrieved student %v", qName) } else { - log.Printf("Failed to retrieve student %v. Error - %+v ", qName, err) + logger.AppLog.Errorf("failed to retrieve student %v. Error - %+v", qName, err) } c.JSON(http.StatusOK, gin.H{}) } @@ -65,10 +66,10 @@ func insertStudentInDB(collName string, name string, age int) { filter := bson.M{} _, err := mongoHndl.PutOneCustomDataStructure(collName, filter, student) if err != nil { - log.Printf("Inserting student %v failed with error %+v ", student, err) + logger.AppLog.Errorf("inserting student %v failed with error %+v", student, err) return } - log.Printf("Inserting student %v successful ", student) + logger.AppLog.Infof("inserting student %v successful", student) } func getStudentFromDB(collName string, name string) (Student, error) { diff --git a/mongoapi/dbtestapp/timeout.go b/mongoapi/dbtestapp/timeout.go index 00fe5f9..3ba078d 100644 --- a/mongoapi/dbtestapp/timeout.go +++ b/mongoapi/dbtestapp/timeout.go @@ -7,29 +7,30 @@ package main import ( "context" + "net/http" + "time" + "github.com/gin-gonic/gin" + "github.com/omec-project/util/logger" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" - "log" - "net/http" - "time" ) func iterateChangeStream(routineCtx context.Context, stream *mongo.ChangeStream) { - log.Println("iterate change stream for timeout") + logger.AppLog.Infoln("iterate change stream for timeout") defer stream.Close(routineCtx) for stream.Next(routineCtx) { var data bson.M if err := stream.Decode(&data); err != nil { panic(err) } - log.Println("iterate stream : ", data) + logger.AppLog.Infoln("iterate stream:", data) } } func timeoutTest(c *gin.Context) { c.String(http.StatusOK, "timeoutTest!") - log.Println("starting timeout document") + logger.AppLog.Infoln("starting timeout document") database := mongoHndl.Client.Database("sdcore") timeoutColl := database.Collection("timeout") @@ -47,9 +48,9 @@ func timeoutTest(c *gin.Context) { //createDocumentWithTimeout("timeout", "yak2", 60, "createdAt") ret := mongoHndl.RestfulAPICreateTTLIndex("timeout", 20, "updatedAt") if ret { - log.Println("TTL index create successful") + logger.AppLog.Infoln("ttl index create successful") } else { - log.Println("TTL index exists already") + logger.AppLog.Infoln("ttl index exists already") } createDocumentWithCommonTimeout("timeout", "yak1") @@ -63,20 +64,20 @@ func timeoutTest(c *gin.Context) { ret = mongoHndl.RestfulAPIDropTTLIndex("timeout", "updatedAt") if !ret { - log.Println("TTL index drop failed") + logger.AppLog.Warnln("ttl index drop failed") } ret = mongoHndl.RestfulAPIPatchTTLIndex("timeout", 0, "expireAt") if ret { - log.Println("TTL index patch successful") + logger.AppLog.Infoln("ttl index patch successful") } else { - log.Println("TTL index patch failed") + logger.AppLog.Warnln("ttl index patch failed") } createDocumentWithExpiryTime("timeout", "yak1", 30) createDocumentWithExpiryTime("timeout", "yak3", 30) updateDocumentWithExpiryTime("timeout", "yak3", 40) updateDocumentWithExpiryTime("timeout", "yak1", 50) - //log.Println("sleeping for 120 seconds") + //logger.AppLog.Infoln("sleeping for 120 seconds") //time.Sleep(120 * time.Second) //updateDocumentWithTimeout("timeout", "yak1", 200, "createdAt") c.JSON(http.StatusOK, gin.H{}) @@ -87,7 +88,7 @@ func createDocumentWithCommonTimeout(collName string, name string) { putData["name"] = name putData["createdAt"] = time.Now() //timein := time.Now().Local().Add(time.Second * time.Duration(20)) - //log.Println("updated timeout : ", timein) + //logger.AppLog.Infoln("updated timeout:", timein) //putData["updatedAt"] = timein putData["updatedAt"] = time.Now() filter := bson.M{"name": name} @@ -118,7 +119,7 @@ func createDocumentWithExpiryTime(collName string, name string, timeVal int) { putData["name"] = name putData["createdAt"] = time.Now() timein := time.Now().Local().Add(time.Second * time.Duration(timeVal)) - //log.Println("updated timeout : ", timein) + //logger.AppLog.Infoln("updated timeout:", timein) putData["expireAt"] = timein //putData["updatedAt"] = time.Now() filter := bson.M{"name": name} diff --git a/path_util/logger/logger.go b/path_util/logger/logger.go deleted file mode 100644 index abac9b2..0000000 --- a/path_util/logger/logger.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2019 Communication Service/Software Laboratory, National Chiao Tung University (free5gc.org) -// -// SPDX-License-Identifier: Apache-2.0 - -package logger - -import ( - "time" - - formatter "github.com/antonfisher/nested-logrus-formatter" - "github.com/sirupsen/logrus" -) - -var log *logrus.Logger -var PathLog *logrus.Entry - -func init() { - log = logrus.New() - log.SetReportCaller(false) - - log.Formatter = &formatter.Formatter{ - TimestampFormat: time.RFC3339, - TrimMessages: true, - NoFieldsSpace: true, - HideKeys: true, - FieldsOrder: []string{"component", "category"}, - } - - PathLog = log.WithFields(logrus.Fields{"component": "LIB", "category": "Path"}) -} - -func SetLogLevel(level logrus.Level) { - PathLog.Infoln("set log level :", level) - log.SetLevel(level) -} - -func SetReportCaller(bool bool) { - PathLog.Infoln("set report call :", bool) - log.SetReportCaller(bool) -} diff --git a/path_util/path.go b/path_util/path.go index f0e55f4..de20436 100644 --- a/path_util/path.go +++ b/path_util/path.go @@ -10,27 +10,9 @@ import ( "path/filepath" "strings" - "github.com/omec-project/util/path_util/logger" + "github.com/omec-project/util/logger" ) -// Free5gcPath ... -/* - * Author: Roger Chu aka Sasuke - * - * This package is used to locate the root directory of gofree5gc project - * Compatible with Windows and Linux - * - * Please import "github.com/omec-project/path_util" - * - * Return value: - * A string value of the relative path between the working directory and the root directory of the gofree5gc project - * - * Usage: - * path_util.Free5gcPath("your file location starting with gofree5gc") - * - * Example: - * path_util.Free5gcPath("free5gc/abcdef/abcdef.pem") - */ func Free5gcPath(path string) string { rootCode := strings.Split(path, "/")[0] cleanPath := filepath.Clean(path) @@ -114,20 +96,20 @@ func FindModuleRoot(path string, rootCode string) (string, bool) { if Exists(moduleFilePath) { var file *os.File if fileTmp, err := os.Open(moduleFilePath); err != nil { - logger.PathLog.Fatalf("Cannot open %s: %+v", moduleFilePath, err) + logger.PathLog.Fatalf("cannot open %s: %+v", moduleFilePath, err) } else { file = fileTmp } defer func() { if err := file.Close(); err != nil { - logger.PathLog.Warnf("File %s cannot close: %v", moduleFilePath, err) + logger.PathLog.Warnf("file %s cannot close: %v", moduleFilePath, err) } }() reader := bufio.NewReader(file) moduleDeclearation, _, err := reader.ReadLine() if err != nil { - logger.PathLog.Warnf("Read Line failed: %+v", err) + logger.PathLog.Warnf("read Line failed: %+v", err) } if string(moduleDeclearation) == "module "+rootCode { return path, true diff --git a/path_util/path_test.go b/path_util/path_test.go index 7ff1c79..7ee1adc 100644 --- a/path_util/path_test.go +++ b/path_util/path_test.go @@ -7,7 +7,7 @@ package path_util import ( "testing" - "github.com/omec-project/util/path_util/logger" + "github.com/omec-project/util/logger" ) func TestFree5gcPath(t *testing.T) { diff --git a/util_3gpp/logger/logger.go b/util_3gpp/logger/logger.go deleted file mode 100644 index 85e19b8..0000000 --- a/util_3gpp/logger/logger.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2019 Communication Service/Software Laboratory, National Chiao Tung University (free5gc.org) -// -// SPDX-License-Identifier: Apache-2.0 - -package logger - -import ( - "os" - "time" - - formatter "github.com/antonfisher/nested-logrus-formatter" - "github.com/sirupsen/logrus" - - "github.com/omec-project/util/logger_conf" - "github.com/omec-project/util/logger" -) - -var log *logrus.Logger - -// Util3GPPLog : Log entry of util_3gpp -var Util3GPPLog *logrus.Entry - -func init() { - log = logrus.New() - log.SetReportCaller(false) - - log.Formatter = &formatter.Formatter{ - TimestampFormat: time.RFC3339, - TrimMessages: true, - NoFieldsSpace: true, - HideKeys: true, - FieldsOrder: []string{"component", "category"}, - } - - free5gcLogHook, err := logger.NewFileHook(logger_conf.Free5gcLogFile, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) - if err == nil { - log.Hooks.Add(free5gcLogHook) - } - - selfLogHook, err := logger.NewFileHook(logger_conf.LibLogDir+"util_3gpp.log", - os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) - if err == nil { - log.Hooks.Add(selfLogHook) - } - - Util3GPPLog = log.WithFields(logrus.Fields{"component": "LIB", "category": "3GPP"}) -} - -// SetLogLevel : set the log level (panic|fatal|error|warn|info|debug|trace) -func SetLogLevel(level logrus.Level) { - Util3GPPLog.Infoln("set log level :", level) - log.SetLevel(level) -} - -// SetReportCaller : Set whether shows the filePath and functionName on loggers -func SetReportCaller(bool bool) { - Util3GPPLog.Infoln("set report call :", bool) - log.SetReportCaller(bool) -} diff --git a/util_3gpp/suci/toSupi.go b/util_3gpp/suci/toSupi.go index b6a7ae2..78b8908 100644 --- a/util_3gpp/suci/toSupi.go +++ b/util_3gpp/suci/toSupi.go @@ -14,7 +14,6 @@ import ( "encoding/binary" "encoding/hex" "fmt" - "log" "math" "math/big" "math/bits" @@ -23,7 +22,7 @@ import ( "golang.org/x/crypto/curve25519" - "github.com/omec-project/util/util_3gpp/logger" + "github.com/omec-project/util/logger" ) type SuciProfile struct { @@ -53,7 +52,7 @@ func CompressKey(uncompressed []byte, y *big.Int) []byte { } else { // 0x02 compressed[0] = 0x02 } - // fmt.Printf("compressed: %x\n", compressed) + // logger.Util3GPPLog.Debugf("compressed: %x", compressed) return compressed } @@ -87,7 +86,7 @@ func uncompressKey(compressedBytes []byte, priv []byte) (*big.Int, *big.Int) { y := new(big.Int).ModSqrt(ySquared, c.P) if y == nil { // If this happens then you're dealing with an invalid point. - logger.Util3GPPLog.Errorln("Uncompressed key with invalid point") + logger.Util3GPPLog.Errorln("uncompressed key with invalid point") return nil, nil } @@ -96,18 +95,18 @@ func uncompressKey(compressedBytes []byte, priv []byte) (*big.Int, *big.Int) { y.Neg(y) y.Mod(y, c.P) } - // fmt.Printf("xUncom: %x\nyUncon: %x\n", x, y) + // logger.Util3GPPLog.Debugf("xUncom: %x\nyUncon: %x", x, y) return x, y } func HmacSha256(input, macKey []byte, macLen int) []byte { h := hmac.New(sha256.New, macKey) if _, err := h.Write(input); err != nil { - log.Printf("HMAC SHA256 error %+v", err) + logger.Util3GPPLog.Errorf("HMAC SHA256 error %+v", err) } macVal := h.Sum(nil) macTag := macVal[:macLen] - // fmt.Printf("macVal: %x\nmacTag: %x\n", macVal, macTag) + // logger.Util3GPPLog.Debugf("macVal: %x\nmacTag: %x", macVal, macTag) return macTag } @@ -115,11 +114,11 @@ func Aes128ctr(input, encKey, icb []byte) []byte { output := make([]byte, len(input)) block, err := aes.NewCipher(encKey) if err != nil { - log.Printf("AES128 CTR error %+v", err) + logger.Util3GPPLog.Errorf("AES128 CTR error %+v", err) } stream := cipher.NewCTR(block, icb) stream.XORKeyStream(output, input) - // fmt.Printf("aes input: %x %x %x\naes output: %x\n", input, encKey, icb, output) + // logger.Util3GPPLog.Debugf("aes input: %x %x %x\naes output: %x", input, encKey, icb, output) return output } @@ -130,11 +129,11 @@ func AnsiX963KDF(sharedKey, publicKey []byte, profileEncKeyLen, profileMacKeyLen for i := 1; i <= kdfRounds; i++ { counterBytes := make([]byte, 4) binary.BigEndian.PutUint32(counterBytes, counter) - // fmt.Printf("counterBytes: %x\n", counterBytes) + // logger.Util3GPPLog.Debugf("counterBytes: %x", counterBytes) tmpK := sha256.Sum256(append(append(sharedKey, counterBytes...), publicKey...)) sliceK := tmpK[:] kdfKey = append(kdfKey, sliceK...) - // fmt.Printf("kdfKey in round %d: %x\n", i, kdfKey) + // logger.Util3GPPLog.Debugf("kdfKey in round %d: %x", i, kdfKey) counter++ } return kdfKey @@ -162,7 +161,7 @@ func calcSchemeResult(decryptPlainText []byte, supiType string) string { } func profileA(input, supiType, privateKey string) (string, error) { - logger.Util3GPPLog.Infoln("SuciToSupi Profile A") + logger.Util3GPPLog.Infoln("suciToSupi Profile A") s, hexDecodeErr := hex.DecodeString(input) if hexDecodeErr != nil { logger.Util3GPPLog.Errorln("hex DecodeString error") @@ -180,29 +179,29 @@ func profileA(input, supiType, privateKey string) (string, error) { decryptMac := s[len(s)-ProfileAMacLen:] decryptPublicKey := s[:ProfileAPubKeyLen] decryptCipherText := s[ProfileAPubKeyLen : len(s)-ProfileAMacLen] - // fmt.Printf("dePub: %x\ndeCiph: %x\ndeMac: %x\n", decryptPublicKey, decryptCipherText, decryptMac) + // logger.Util3GPPLog.Debugf("dePub: %x deCiph: %x deMac: %x", decryptPublicKey, decryptCipherText, decryptMac) // test data from TS33.501 Annex C.4 // aHNPriv, _ := hex.DecodeString("c53c2208b61860b06c62e5406a7b330c2b577aa5558981510d128247d38bd1d") var aHNPriv []byte if aHNPrivTmp, err := hex.DecodeString(privateKey); err != nil { - log.Printf("Decode error: %+v", err) + logger.Util3GPPLog.Errorf("decode error: %+v", err) } else { aHNPriv = aHNPrivTmp } var decryptSharedKey []byte if decryptSharedKeyTmp, err := curve25519.X25519(aHNPriv, []byte(decryptPublicKey)); err != nil { - log.Printf("X25519 error: %+v", err) + logger.Util3GPPLog.Errorf("X25519 error: %+v", err) } else { decryptSharedKey = decryptSharedKeyTmp } - // fmt.Printf("deShared: %x\n", decryptSharedKey) + // logger.Util3GPPLog.Debugf("deShared: %x", decryptSharedKey) kdfKey := AnsiX963KDF(decryptSharedKey, decryptPublicKey, ProfileAEncKeyLen, ProfileAMacKeyLen, ProfileAHashLen) decryptEncKey := kdfKey[:ProfileAEncKeyLen] decryptIcb := kdfKey[ProfileAEncKeyLen : ProfileAEncKeyLen+ProfileAIcbLen] decryptMacKey := kdfKey[len(kdfKey)-ProfileAMacKeyLen:] - // fmt.Printf("\ndeEncKey(size%d): %x\ndeMacKey: %x\ndeIcb: %x\n", len(decryptEncKey), decryptEncKey, decryptMacKey, + // logger.Util3GPPLog.Debugf("deEncKey(size%d): %x deMacKey: %x deIcb: %x", len(decryptEncKey), decryptEncKey, decryptMacKey, // decryptIcb) decryptMacTag := HmacSha256(decryptCipherText, decryptMacKey, ProfileAMacLen) @@ -239,7 +238,7 @@ func profileB(input, supiType, privateKey string) (string, error) { return "", fmt.Errorf("suci input error") } - // fmt.Printf("len:%d %d\n", len(s), ProfileBPubKeyLen + ProfileBMacLen) + // logger.Util3GPPLog.Debugf("len:%d %d", len(s), ProfileBPubKeyLen + ProfileBMacLen) if len(s) < ProfileBPubKeyLen+ProfileBMacLen { logger.Util3GPPLog.Errorln("len of input data is too short") return "", fmt.Errorf("suci input too short") @@ -247,13 +246,13 @@ func profileB(input, supiType, privateKey string) (string, error) { decryptPublicKey := s[:ProfileBPubKeyLen] decryptMac := s[len(s)-ProfileBMacLen:] decryptCipherText := s[ProfileBPubKeyLen : len(s)-ProfileBMacLen] - // fmt.Printf("dePub: %x\ndeCiph: %x\ndeMac: %x\n", decryptPublicKey, decryptCipherText, decryptMac) + // logger.Util3GPPLog.Debugf("dePub: %x deCiph: %x deMac: %x", decryptPublicKey, decryptCipherText, decryptMac) // test data from TS33.501 Annex C.4 // bHNPriv, _ := hex.DecodeString("F1AB1074477EBCC7F554EA1C5FC368B1616730155E0041AC447D6301975FECDA") var bHNPriv []byte if bHNPrivTmp, err := hex.DecodeString(privateKey); err != nil { - log.Printf("Decode error: %+v", err) + logger.Util3GPPLog.Errorf("decode error: %+v", err) } else { bHNPriv = bHNPrivTmp } @@ -269,11 +268,11 @@ func profileB(input, supiType, privateKey string) (string, error) { return "", fmt.Errorf("key uncompression error") } } - // fmt.Printf("xUncom: %x\nyUncom: %x\n", xUncompressed, yUncompressed) + // logger.Util3GPPLog.Debugf("xUncom: %x yUncom: %x", xUncompressed, yUncompressed) // x-coordinate is the shared key decryptSharedKey, _ := elliptic.P256().ScalarMult(xUncompressed, yUncompressed, bHNPriv) - // fmt.Printf("deShared: %x\n", decryptSharedKey.Bytes()) + // logger.Util3GPPLog.Debugf("deShared: %x", decryptSharedKey.Bytes()) decryptPublicKeyForKDF := decryptPublicKey if uncompressed { @@ -282,11 +281,11 @@ func profileB(input, supiType, privateKey string) (string, error) { kdfKey := AnsiX963KDF(decryptSharedKey.Bytes(), decryptPublicKeyForKDF, ProfileBEncKeyLen, ProfileBMacKeyLen, ProfileBHashLen) - // fmt.Printf("kdfKey: %x\n", kdfKey) + // logger.Util3GPPLog.Debugf("kdfKey: %x", kdfKey) decryptEncKey := kdfKey[:ProfileBEncKeyLen] decryptIcb := kdfKey[ProfileBEncKeyLen : ProfileBEncKeyLen+ProfileBIcbLen] decryptMacKey := kdfKey[len(kdfKey)-ProfileBMacKeyLen:] - // fmt.Printf("\ndeEncKey(size%d): %x\ndeMacKey: %x\ndeIcb: %x\n", len(decryptEncKey), decryptEncKey, decryptMacKey, + // logger.Util3GPPLog.Debugf("deEncKey(size%d): %x deMacKey: %x deIcb: %x", len(decryptEncKey), decryptEncKey, decryptMacKey, // decryptIcb) decryptMacTag := HmacSha256(decryptCipherText, decryptMacKey, ProfileBMacLen) @@ -321,7 +320,7 @@ func ToSupi(suci string, suciProfiles []SuciProfile) (string, error) { suciPrefix := suciPart[0] if suciPrefix == "imsi" || suciPrefix == "nai" { - logger.Util3GPPLog.Infof("got supi") + logger.Util3GPPLog.Infoln("got supi") return suci, nil } else if suciPrefix == "suci" { @@ -340,7 +339,7 @@ func ToSupi(suci string, suciProfiles []SuciProfile) (string, error) { supiPrefix := imsiPrefix if suciPrefix == "suci" && suciPart[supiTypePlace] == typeIMSI { supiPrefix = imsiPrefix - logger.Util3GPPLog.Infof("supi type is IMSI") + logger.Util3GPPLog.Infoln("supi type is IMSI") } if scheme == nullScheme { // NULL scheme diff --git a/version/version.go b/version/version.go deleted file mode 100644 index c4fef2e..0000000 --- a/version/version.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2019 Communication Service/Software Laboratory, National Chiao Tung University (free5gc.org) -// -// SPDX-License-Identifier: Apache-2.0 - -package version - -import ( - "fmt" - "runtime" -) - -var ( - VERSION string - BUILD_TIME string - COMMIT_HASH string - COMMIT_TIME string -) - -func GetVersion() string { - if VERSION != "" { - return fmt.Sprintf( - "\n\tfree5GC version: %s"+ - "\n\tbuild time: %s"+ - "\n\tcommit hash: %s"+ - "\n\tcommit time: %s"+ - "\n\tgo version: %s %s/%s", - VERSION, - BUILD_TIME, - COMMIT_HASH, - COMMIT_TIME, - runtime.Version(), - runtime.GOOS, - runtime.GOARCH, - ) - } else { - return fmt.Sprintf( - "\n\tNot specify ldflags (which link version) during go build\n\tgo version: %s %s/%s", - runtime.Version(), - runtime.GOOS, - runtime.GOARCH, - ) - } -} diff --git a/version/version_test.go b/version/version_test.go deleted file mode 100644 index 1afca3c..0000000 --- a/version/version_test.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2019 Communication Service/Software Laboratory, National Chiao Tung University (free5gc.org) -// -// SPDX-License-Identifier: Apache-2.0 - -package version - -import ( - "fmt" - "os/exec" - "runtime" - "strings" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestVersion(t *testing.T) { - t.Run("VERSION not specified", func(t *testing.T) { - expected := fmt.Sprintf( - "\n\tNot specify ldflags (which link version) during go build\n\tgo version: %s %s/%s", - runtime.Version(), - runtime.GOOS, - runtime.GOARCH) - assert.Equal(t, expected, GetVersion()) - }) - - t.Run("VERSION constly specified", func(t *testing.T) { - VERSION = "Release-v3.100.200" - BUILD_TIME = "2020-09-11T07:05:04Z" - COMMIT_HASH = "fb2481c2" - COMMIT_TIME = "2020-09-11T07:00:29Z" - - expected := fmt.Sprintf( - "\n\tfree5GC version: %s"+ - "\n\tbuild time: %s"+ - "\n\tcommit hash: %s"+ - "\n\tcommit time: %s"+ - "\n\tgo version: %s %s/%s", - VERSION, - BUILD_TIME, - COMMIT_HASH, - COMMIT_TIME, - runtime.Version(), - runtime.GOOS, - runtime.GOARCH) - - assert.Equal(t, expected, GetVersion()) - fmt.Println(VERSION) - }) - - t.Run("VERSION capture by system", func(t *testing.T) { - var stdout []byte - var err error - VERSION = "Release-v3.100.200" // VERSION using free5gc's version (git tag), we static set it here - stdout, err = exec.Command("bash", "-c", "date -u +\"%Y-%m-%dT%H:%M:%SZ\"").Output() - if err != nil { - t.Errorf("err: %+v\n", err) - } - BUILD_TIME = strings.TrimSuffix(string(stdout), "\n") - stdout, err = exec.Command("bash", "-c", "git log --pretty=\"%H\" -1 | cut -c1-8").Output() - if err != nil { - t.Errorf("err: %+v\n", err) - } - COMMIT_HASH = strings.TrimSuffix(string(stdout), "\n") - stdout, err = exec.Command("bash", "-c", - "git log --pretty=\"%ai\" -1 | awk '{time=$1\"T\"$2\"Z\"; print time}'").Output() - if err != nil { - t.Errorf("err: %+v\n", err) - } - fmt.Println("Insert Data") - COMMIT_TIME = strings.TrimSuffix(string(stdout), "\n") - - expected := fmt.Sprintf( - "\n\tfree5GC version: %s"+ - "\n\tbuild time: %s"+ - "\n\tcommit hash: %s"+ - "\n\tcommit time: %s"+ - "\n\tgo version: %s %s/%s", - VERSION, - BUILD_TIME, - COMMIT_HASH, - COMMIT_TIME, - runtime.Version(), - runtime.GOOS, - runtime.GOARCH) - - assert.Equal(t, expected, GetVersion()) - fmt.Println(VERSION) - }) -}