Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get folder size #215

Merged
merged 3 commits into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion blockchain/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,9 @@
actionFetchContainerLogs: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleFetchContainerLogs(r.Context(), from, w, r)
},
actionGetFolderSize: func(from peer.ID, w http.ResponseWriter, r *http.Request) {
bl.handleGetFolderSize(r.Context(), from, w, r)
},
}

// Look up the function in the map and call it
Expand Down Expand Up @@ -674,7 +677,7 @@
return true
}
switch action {
case actionBloxFreeSpace, actionAccountFund, actionAssetsBalance, actionFetchContainerLogs, actionEraseBlData, actionWifiRemoveall, actionReboot, actionPartition, actionDeleteWifi, actionDisconnectWifi, actionDeleteFulaConfig, actionGetAccount, actionSeeded, actionAccountExists, actionPoolCreate, actionPoolJoin, actionPoolCancelJoin, actionPoolRequests, actionPoolList, actionPoolVote, actionPoolLeave, actionManifestUpload, actionManifestStore, actionManifestAvailable, actionManifestRemove, actionManifestRemoveStorer, actionManifestRemoveStored:
case actionBloxFreeSpace, actionAccountFund, actionAssetsBalance, actionGetFolderSize, actionFetchContainerLogs, actionEraseBlData, actionWifiRemoveall, actionReboot, actionPartition, actionDeleteWifi, actionDisconnectWifi, actionDeleteFulaConfig, actionGetAccount, actionSeeded, actionAccountExists, actionPoolCreate, actionPoolJoin, actionPoolCancelJoin, actionPoolRequests, actionPoolList, actionPoolVote, actionPoolLeave, actionManifestUpload, actionManifestStore, actionManifestAvailable, actionManifestRemove, actionManifestRemoveStorer, actionManifestRemoveStored:
bl.authorizedPeersLock.RLock()
_, ok := bl.authorizedPeers[pid]
bl.authorizedPeersLock.RUnlock()
Expand Down Expand Up @@ -1017,7 +1020,7 @@
err = bl.p.Start(ctx)
if err != nil {
log.Errorw("Error when starting the Ping Server", "PeerID", user.PeerID, "err", err)
} else {

Check failure on line 1023 in blockchain/blockchain.go

View workflow job for this annotation

GitHub Actions / All

empty branch (SA9003)

Check failure on line 1023 in blockchain/blockchain.go

View workflow job for this annotation

GitHub Actions / All

empty branch (SA9003)
// TODO: THIS METHOD BELOW NEEDS TO RE_INITIALIZE ANNONCEMENTS WITH NEW TOPIC ND START IT FIRST
/*
log.Debugw("Found self peerID and ran Ping Server and announcing pooljoinrequest now", "peer", user.PeerID)
Expand Down
72 changes: 72 additions & 0 deletions blockchain/blox.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,43 @@
}
}

func (bl *FxBlockchain) GetFolderSize(ctx context.Context, to peer.ID, r wifi.GetFolderSizeRequest) ([]byte, error) {

if bl.allowTransientConnection {
ctx = network.WithUseTransient(ctx, "fx.blockchain")
}

var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(r); err != nil {
return nil, err
}

req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+to.String()+".invalid/"+actionGetFolderSize, &buf)
if err != nil {
return nil, err
}
resp, err := bl.c.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
switch {
case err != nil:
return nil, err
case resp.StatusCode != http.StatusAccepted:
// Attempt to parse the body as JSON.
if jsonErr := json.Unmarshal(b, &apiError); jsonErr != nil {
// If we can't parse the JSON, return the original body in the error.
return nil, fmt.Errorf("unexpected response: %d %s", resp.StatusCode, string(b))
}
// Return the parsed error message and description.
return nil, fmt.Errorf("unexpected response: %d %s - %s", resp.StatusCode, apiError.Message, apiError.Description)
default:
return b, nil
}
}

func (bl *FxBlockchain) DeleteWifi(ctx context.Context, to peer.ID, r wifi.DeleteWifiRequest) ([]byte, error) {

if bl.allowTransientConnection {
Expand Down Expand Up @@ -331,7 +368,7 @@
}
log.Debugw("handleFetchContainerLogs received", "req", req)

out := wifi.FetchContainerLogsResponse{

Check failure on line 371 in blockchain/blox.go

View workflow job for this annotation

GitHub Actions / All

this value of out is never used (SA4006)

Check failure on line 371 in blockchain/blox.go

View workflow job for this annotation

GitHub Actions / All

this value of out is never used (SA4006)
Status: true,
Msg: "",
}
Expand All @@ -356,3 +393,38 @@
}

}

func (bl *FxBlockchain) handleGetFolderSize(ctx context.Context, from peer.ID, w http.ResponseWriter, r *http.Request) {
log := log.With("action", actionGetFolderSize, "from", from)

// Parse the JSON body of the request into the DeleteWifiRequest struct
var req wifi.GetFolderSizeRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
log.Error("failed to decode request: %v", err)
http.Error(w, "failed to decode request", http.StatusBadRequest)
return
}
log.Debugw("handleGetFolderSize received", "req", req)

out := wifi.GetFolderSizeResponse{

Check failure on line 409 in blockchain/blox.go

View workflow job for this annotation

GitHub Actions / All

this value of out is never used (SA4006)

Check failure on line 409 in blockchain/blox.go

View workflow job for this annotation

GitHub Actions / All

this value of out is never used (SA4006)
FolderPath: "",
SizeInBytes: "",
}
res, err := wifi.GetFolderSize(ctx, req)
if err != nil {
out = wifi.GetFolderSizeResponse{
FolderPath: "",
SizeInBytes: "",
}
} else {
out = res
}
log.Debugw("handleGetFolderSize response", "out", out)
w.WriteHeader(http.StatusAccepted)
if err := json.NewEncoder(w).Encode(out); err != nil {
log.Error("failed to write response: %v", err)
http.Error(w, "failed to write response", http.StatusInternalServerError)
return
}

}
4 changes: 4 additions & 0 deletions blockchain/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const (
actionDisconnectWifi = "disconnect-wifi"
actionGetAccount = "get-account"
actionFetchContainerLogs = "fetch-container-logs"
actionGetFolderSize = "get-folder-size"
)

type LinkWithLimit struct {
Expand Down Expand Up @@ -356,6 +357,7 @@ type Blockchain interface {
DeleteFulaConfig(context.Context, peer.ID) ([]byte, error)
GetAccount(context.Context, peer.ID) ([]byte, error)
FetchContainerLogs(context.Context, peer.ID, wifi.FetchContainerLogsRequest) ([]byte, error)
GetFolderSize(context.Context, peer.ID, wifi.GetFolderSizeRequest) ([]byte, error)
}

var requestTypes = map[string]reflect.Type{
Expand Down Expand Up @@ -393,6 +395,7 @@ var requestTypes = map[string]reflect.Type{
actionDisconnectWifi: reflect.TypeOf(wifi.DeleteWifiRequest{}),
actionGetAccount: reflect.TypeOf(GetAccountRequest{}),
actionFetchContainerLogs: reflect.TypeOf(wifi.FetchContainerLogsRequest{}),
actionGetFolderSize: reflect.TypeOf(wifi.GetFolderSizeRequest{}),
}

var responseTypes = map[string]reflect.Type{
Expand Down Expand Up @@ -430,4 +433,5 @@ var responseTypes = map[string]reflect.Type{
actionDisconnectWifi: reflect.TypeOf(wifi.DeleteWifiResponse{}),
actionGetAccount: reflect.TypeOf(GetAccountResponse{}),
actionFetchContainerLogs: reflect.TypeOf(wifi.FetchContainerLogsResponse{}),
actionGetFolderSize: reflect.TypeOf(wifi.GetFolderSizeResponse{}),
}
7 changes: 7 additions & 0 deletions mobile/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,3 +196,10 @@ func (c *Client) FetchContainerLogs(ContainerName string, TailCount string) ([]b
ctx := context.TODO()
return c.bl.FetchContainerLogs(ctx, c.bloxPid, wifi.FetchContainerLogsRequest{ContainerName: ContainerName, TailCount: TailCount})
}

// GetAccount requests blox at Config.BloxAddr to get the balance of the account.
// the addr must be a valid multiaddr that includes peer ID.
func (c *Client) GetFolderSize(folderPath string) ([]byte, error) {
ctx := context.TODO()
return c.bl.GetFolderSize(ctx, c.bloxPid, wifi.GetFolderSizeRequest{FolderPath: folderPath})
}
27 changes: 27 additions & 0 deletions wap/pkg/wifi/properties.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@ type BloxFreeSpaceResponse struct {
UsedPercentage float32 `json:"used_percentage"`
}

type GetFolderSizeRequest struct {
FolderPath string `json:"folder_path"`
}

type GetFolderSizeResponse struct {
FolderPath string `json:"folder_path"`
SizeInBytes string `json:"size"`
}

type FetchContainerLogsResponse struct {
Status bool `json:"status"`
Msg string `json:"msg"`
Expand Down Expand Up @@ -111,6 +120,24 @@ func GenerateRandomString(length int) (string, error) {
return base64.URLEncoding.EncodeToString(bytes), nil
}

func GetFolderSize(ctx context.Context, req GetFolderSizeRequest) (GetFolderSizeResponse, error) {
cmd := fmt.Sprintf(`du -sb %s | cut -f1`, req.FolderPath)
out, err := exec.CommandContext(ctx, "sh", "-c", cmd).Output()
if err != nil {
return GetFolderSizeResponse{}, fmt.Errorf("error executing shell command: %v", err)
}

sizeInBytes, err := strconv.ParseInt(strings.TrimSpace(string(out)), 10, 64)
if err != nil {
return GetFolderSizeResponse{}, fmt.Errorf("error parsing folder size: %v", err)
}

return GetFolderSizeResponse{
FolderPath: req.FolderPath,
SizeInBytes: fmt.Sprint(sizeInBytes),
}, nil
}

func GetBloxFreeSpace() (BloxFreeSpaceResponse, error) {
cmd := `df -B1 2>/dev/null | grep -nE '/storage/(usb|sd[a-z]|nvme)' | awk '{sum2+=$2; sum3+=$3; sum4+=$4; sum5+=$5} END { print NR "," sum2 "," sum3 "," sum4 "," sum5}'`
out, err := exec.Command("sh", "-c", cmd).Output()
Expand Down
Loading