diff --git a/pkg/zos_api/location.go b/pkg/zos_api/location.go new file mode 100644 index 000000000..2da54e8a9 --- /dev/null +++ b/pkg/zos_api/location.go @@ -0,0 +1,27 @@ +package zosapi + +import ( + "context" + + "github.com/patrickmn/go-cache" + "github.com/threefoldtech/zos/pkg/geoip" +) + +const ( + locationCacheKey = "location" +) + +func (g *ZosAPI) locationGet(ctx context.Context, payload []byte) (interface{}, error) { + if loc, found := g.inMemCache.Get(locationCacheKey); found { + return loc, nil + } + + loc, err := geoip.Fetch() + if err != nil { + return nil, err + } + + g.inMemCache.Set(locationCacheKey, loc, cache.DefaultExpiration) + + return loc, nil +} diff --git a/pkg/zos_api/routes.go b/pkg/zos_api/routes.go index 8006f23b7..a0a3fa214 100644 --- a/pkg/zos_api/routes.go +++ b/pkg/zos_api/routes.go @@ -48,4 +48,7 @@ func (g *ZosAPI) SetupRoutes(router *peer.Router) { admin.WithHandler("interfaces", g.adminInterfacesHandler) admin.WithHandler("set_public_nic", g.adminSetPublicNICHandler) admin.WithHandler("get_public_nic", g.adminGetPublicNICHandler) + + location := root.SubRoute("location") + location.WithHandler("get", g.locationGet) } diff --git a/pkg/zos_api/zos_api.go b/pkg/zos_api/zos_api.go index e3661f706..210ce6045 100644 --- a/pkg/zos_api/zos_api.go +++ b/pkg/zos_api/zos_api.go @@ -2,7 +2,9 @@ package zosapi import ( "fmt" + "time" + "github.com/patrickmn/go-cache" substrate "github.com/threefoldtech/tfchain/clients/tfchain-client-go" "github.com/threefoldtech/zbus" "github.com/threefoldtech/zos/pkg/capacity" @@ -11,6 +13,11 @@ import ( "github.com/threefoldtech/zos/pkg/stubs" ) +const ( + cacheDefaultExpiration = 24 * time.Hour + cacheDefaultCleanup = 24 * time.Hour +) + type ZosAPI struct { oracle *capacity.ResourceOracle versionMonitorStub *stubs.VersionMonitorStub @@ -22,6 +29,7 @@ type ZosAPI struct { performanceMonitorStub *stubs.PerformanceMonitorStub diagnosticsManager *diagnostics.DiagnosticsManager farmerID uint32 + inMemCache *cache.Cache } func NewZosAPI(manager substrate.Manager, client zbus.Client, msgBrokerCon string) (ZosAPI, error) { @@ -56,5 +64,6 @@ func NewZosAPI(manager substrate.Manager, client zbus.Client, msgBrokerCon strin return ZosAPI{}, err } api.farmerID = uint32(farmer.ID) + api.inMemCache = cache.New(cacheDefaultExpiration, cacheDefaultCleanup) return api, nil }