فهرست منبع

hook manager, api to fetch server usage

Abhishek Kondur 2 سال پیش
والد
کامیت
3e15491ff6
6فایلهای تغییر یافته به همراه94 افزوده شده و 17 حذف شده
  1. 33 0
      controllers/server.go
  2. 9 15
      ee/license.go
  3. 0 1
      ee/util.go
  4. 34 0
      logic/timer.go
  5. 3 1
      main.go
  6. 15 0
      models/structs.go

+ 33 - 0
controllers/server.go

@@ -22,6 +22,33 @@ func serverHandlers(r *mux.Router) {
 	r.HandleFunc("/api/server/getconfig", allowUsers(http.HandlerFunc(getConfig))).Methods(http.MethodGet)
 	r.HandleFunc("/api/server/getserverinfo", authorize(true, false, "node", http.HandlerFunc(getServerInfo))).Methods(http.MethodGet)
 	r.HandleFunc("/api/server/status", http.HandlerFunc(getStatus)).Methods(http.MethodGet)
+	r.HandleFunc("/api/server/usage", authorize(true, false, "user", http.HandlerFunc(getUsage))).Methods(http.MethodGet)
+}
+func getUsage(w http.ResponseWriter, r *http.Request) {
+	type usage struct {
+		Hosts    int `json:"hosts"`
+		Clients  int `json:"clients"`
+		Networks int `json:"networks"`
+		Users    int `json:"users"`
+	}
+	var serverUsage usage
+	hosts, err := logic.GetAllHosts()
+	if err == nil {
+		serverUsage.Hosts = len(hosts)
+	}
+	clients, err := logic.GetAllExtClients()
+	if err == nil {
+		serverUsage.Clients = len(clients)
+	}
+	users, err := logic.GetUsers()
+	if err == nil {
+		serverUsage.Users = len(users)
+	}
+	networks, err := logic.GetNetworks()
+	if err == nil {
+		serverUsage.Networks = len(networks)
+	}
+
 }
 
 // swagger:route GET /api/server/status server getStatus
@@ -41,6 +68,12 @@ func getStatus(w http.ResponseWriter, r *http.Request) {
 	type status struct {
 		DB     bool `json:"db_connected"`
 		Broker bool `json:"broker_connected"`
+		Usage  struct {
+			Hosts    int `json:"hosts"`
+			Clients  int `json:"clients"`
+			Networks int `json:"networks"`
+			Users    int `json:"users"`
+		} `json:"usage"`
 	}
 
 	currentServerStatus := status{

+ 9 - 15
ee/license.go

@@ -15,6 +15,7 @@ import (
 	"github.com/gravitl/netmaker/database"
 	"github.com/gravitl/netmaker/logger"
 	"github.com/gravitl/netmaker/logic"
+	"github.com/gravitl/netmaker/models"
 	"github.com/gravitl/netmaker/netclient/ncutils"
 	"github.com/gravitl/netmaker/servercfg"
 	"golang.org/x/crypto/nacl/box"
@@ -31,21 +32,14 @@ type apiServerConf struct {
 
 // AddLicenseHooks - adds the validation and cache clear hooks
 func AddLicenseHooks() {
-	logic.AddHook(ValidateLicense)
-	logic.AddHook(ClearLicenseCache)
-}
-func init() {
-	go func() {
-		for {
-			time.Sleep(time.Hour)
-			err := ValidateLicense()
-			if err != nil {
-				logger.Log(0, "failed to validate license: ", err.Error())
-				continue
-			}
-			logger.Log(0, "Validated License!!")
-		}
-	}()
+	logic.HookManangerCh <- models.HookDetails{
+		Hook:     ValidateLicense,
+		Interval: time.Hour,
+	}
+	logic.HookManangerCh <- models.HookDetails{
+		Hook:     ClearLicenseCache,
+		Interval: time.Hour,
+	}
 }
 
 // ValidateLicense - the initial license check for netmaker server

+ 0 - 1
ee/util.go

@@ -30,7 +30,6 @@ func base64decode(input string) []byte {
 
 	return bytes
 }
-
 func getCurrentServerLimit() (limits LicenseLimits) {
 	limits.SetDefaults()
 	hosts, err := logic.GetAllHosts()

+ 34 - 0
logic/timer.go

@@ -1,10 +1,13 @@
 package logic
 
 import (
+	"context"
 	"fmt"
+	"sync"
 	"time"
 
 	"github.com/gravitl/netmaker/logger"
+	"github.com/gravitl/netmaker/models"
 )
 
 // == Constants ==
@@ -40,6 +43,37 @@ func AddHook(ifaceToAdd interface{}) {
 	timeHooks = append(timeHooks, ifaceToAdd)
 }
 
+var HookManangerCh = make(chan models.HookDetails, 2)
+
+func StartHookManager(ctx context.Context, wg *sync.WaitGroup) {
+	defer wg.Done()
+	for {
+		select {
+		case <-ctx.Done():
+			logger.Log(0, "## Stopping Hook Manager")
+			return
+		case newhook := <-HookManangerCh:
+			wg.Add(1)
+			go addHookWithInterval(ctx, wg, newhook.Hook, newhook.Interval)
+		}
+	}
+}
+
+func addHookWithInterval(ctx context.Context, wg *sync.WaitGroup, hook func() error, interval time.Duration) {
+	defer wg.Done()
+	ticker := time.NewTicker(interval)
+	defer ticker.Stop()
+	for {
+		select {
+		case <-ctx.Done():
+			return
+		case <-ticker.C:
+			hook()
+		}
+	}
+
+}
+
 // == private ==
 
 // timeHooks - functions to run once a day, functions must take no parameters

+ 3 - 1
main.go

@@ -88,7 +88,6 @@ func initialize() { // Client Mode Prereq Check
 	if err != nil {
 		logger.Log(1, "Timer error occurred: ", err.Error())
 	}
-
 	logic.EnterpriseCheck()
 
 	var authProvider = auth.InitializeAuthProvider()
@@ -149,6 +148,9 @@ func startControllers(wg *sync.WaitGroup, ctx context.Context) {
 	// starts the stun server
 	wg.Add(1)
 	go stunserver.Start(wg, ctx)
+
+	wg.Add(1)
+	go logic.StartHookManager(ctx, wg)
 }
 
 // Should we be using a context vice a waitgroup????????????

+ 15 - 0
models/structs.go

@@ -267,3 +267,18 @@ type StunServer struct {
 	Domain string `json:"domain" yaml:"domain"`
 	Port   int    `json:"port" yaml:"port"`
 }
+
+// HookDetails - struct to hold hook info
+type HookDetails struct {
+	Hook     func() error
+	Interval time.Duration
+}
+
+// LicenseLimits - struct license limits
+type LicenseLimits struct {
+	Servers  int `json:"servers"`
+	Users    int `json:"users"`
+	Hosts    int `json:"hosts"`
+	Clients  int `json:"clients"`
+	Networks int `json:"networks"`
+}