Skip to content

Commit

Permalink
api for network with stats
Browse files Browse the repository at this point in the history
  • Loading branch information
abhishek9686 committed Sep 9, 2024
1 parent db4cf1d commit ad6baff
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
44 changes: 44 additions & 0 deletions controllers/network.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import (
func networkHandlers(r *mux.Router) {
r.HandleFunc("/api/networks", logic.SecurityCheck(true, http.HandlerFunc(getNetworks))).
Methods(http.MethodGet)
r.HandleFunc("/api/v1/networks/stats", logic.SecurityCheck(true, http.HandlerFunc(getNetworksStats))).
Methods(http.MethodGet)
r.HandleFunc("/api/networks", logic.SecurityCheck(true, checkFreeTierLimits(limitChoiceNetworks, http.HandlerFunc(createNetwork)))).
Methods(http.MethodPost)
r.HandleFunc("/api/networks/{networkname}", logic.SecurityCheck(true, http.HandlerFunc(getNetwork))).
Expand Down Expand Up @@ -74,6 +76,48 @@ func getNetworks(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(allnetworks)
}

// @Summary Lists all networks with stats
// @Router /api/v1/networks/stats [get]
// @Tags Networks
// @Security oauth
// @Produce json
// @Success 200 {object} models.SuccessResponse
// @Failure 500 {object} models.ErrorResponse
func getNetworksStats(w http.ResponseWriter, r *http.Request) {

var err error
allnetworks, err := logic.GetNetworks()
if err != nil && !database.IsEmptyRecord(err) {
slog.Error("failed to fetch networks", "error", err.Error())
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
return
}
if r.Header.Get("ismaster") != "yes" {
username := r.Header.Get("user")
user, err := logic.GetUser(username)
if err != nil {
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
return
}
allnetworks = logic.FilterNetworksByRole(allnetworks, *user)
}
allNodes, err := logic.GetAllNodes()
if err != nil {
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
return
}
netstats := []models.NetworkStatResp{}
logic.SortNetworks(allnetworks[:])
for _, network := range allnetworks {
netstats = append(netstats, models.NetworkStatResp{
Network: network,
Hosts: len(logic.GetNetworkNodesMemory(allNodes, network.NetID)),
})
}
logger.Log(2, r.Header.Get("user"), "fetched networks.")
logic.ReturnSuccessResponseWithJson(w, r, netstats, "fetched networks with stats")
}

// @Summary Get a network
// @Router /api/networks/{networkname} [get]
// @Tags Networks
Expand Down
5 changes: 5 additions & 0 deletions models/network.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,8 @@ func (network *Network) GetNetworkNetworkCIDR6() *net.IPNet {
_, netCidr, _ := net.ParseCIDR(network.AddressRange6)
return netCidr
}

type NetworkStatResp struct {
Network
Hosts int `json:"hosts"`
}

0 comments on commit ad6baff

Please sign in to comment.