Skip to content

Commit e6667ae

Browse files
Merge pull request #2481 from threefoldtech/main_addLocationEndpoint
add location endpoint
2 parents e4279ca + b5a3940 commit e6667ae

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

pkg/zos_api/location.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package zosapi
2+
3+
import (
4+
"context"
5+
6+
"github.com/patrickmn/go-cache"
7+
"github.com/threefoldtech/zos/pkg/geoip"
8+
)
9+
10+
const (
11+
locationCacheKey = "location"
12+
)
13+
14+
func (g *ZosAPI) locationGet(ctx context.Context, payload []byte) (interface{}, error) {
15+
if loc, found := g.inMemCache.Get(locationCacheKey); found {
16+
return loc, nil
17+
}
18+
19+
loc, err := geoip.Fetch()
20+
if err != nil {
21+
return nil, err
22+
}
23+
24+
g.inMemCache.Set(locationCacheKey, loc, cache.DefaultExpiration)
25+
26+
return loc, nil
27+
}

pkg/zos_api/routes.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,7 @@ func (g *ZosAPI) SetupRoutes(router *peer.Router) {
4848
admin.WithHandler("interfaces", g.adminInterfacesHandler)
4949
admin.WithHandler("set_public_nic", g.adminSetPublicNICHandler)
5050
admin.WithHandler("get_public_nic", g.adminGetPublicNICHandler)
51+
52+
location := root.SubRoute("location")
53+
location.WithHandler("get", g.locationGet)
5154
}

pkg/zos_api/zos_api.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ package zosapi
22

33
import (
44
"fmt"
5+
"time"
56

7+
"github.com/patrickmn/go-cache"
68
substrate "github.com/threefoldtech/tfchain/clients/tfchain-client-go"
79
"github.com/threefoldtech/zbus"
810
"github.com/threefoldtech/zos/pkg/capacity"
@@ -11,6 +13,11 @@ import (
1113
"github.com/threefoldtech/zos/pkg/stubs"
1214
)
1315

16+
const (
17+
cacheDefaultExpiration = 24 * time.Hour
18+
cacheDefaultCleanup = 24 * time.Hour
19+
)
20+
1421
type ZosAPI struct {
1522
oracle *capacity.ResourceOracle
1623
versionMonitorStub *stubs.VersionMonitorStub
@@ -22,6 +29,7 @@ type ZosAPI struct {
2229
performanceMonitorStub *stubs.PerformanceMonitorStub
2330
diagnosticsManager *diagnostics.DiagnosticsManager
2431
farmerID uint32
32+
inMemCache *cache.Cache
2533
}
2634

2735
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
5664
return ZosAPI{}, err
5765
}
5866
api.farmerID = uint32(farmer.ID)
67+
api.inMemCache = cache.New(cacheDefaultExpiration, cacheDefaultCleanup)
5968
return api, nil
6069
}

0 commit comments

Comments
 (0)