GetPath improvements (#20)

* Use named variables for getting path
Fixed bug with env var

* Fix test

* Use utils to get paths
enable-codecov
Malachi Soord 2022-10-08 18:41:37 +02:00 committed by GitHub
parent 83d2fdcae1
commit 0680b7ffb9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 56 additions and 54 deletions

View File

@ -99,7 +99,7 @@ func printDbDetails() {
// IsSystemReady : Checks hability of the service to execute commands (Only after "edgebox --build" is ran at least once via SSH, or if built for distribution) // IsSystemReady : Checks hability of the service to execute commands (Only after "edgebox --build" is ran at least once via SSH, or if built for distribution)
func isSystemReady() bool { func isSystemReady() bool {
_, err := os.Stat("/home/system/components/ws/.ready") _, err := os.Stat(utils.GetPath(utils.WsPath) + ".ready")
return !os.IsNotExist(err) return !os.IsNotExist(err)
} }

View File

@ -56,14 +56,14 @@ func GetEdgeApp(ID string) MaybeEdgeApp {
Valid: false, Valid: false,
} }
_, err := os.Stat(utils.GetPath("edgeAppsPath") + ID + configFilename) _, err := os.Stat(utils.GetPath(utils.EdgeAppsPath) + ID + configFilename)
if !os.IsNotExist(err) { if !os.IsNotExist(err) {
// File exists. Start digging! // File exists. Start digging!
edgeAppName := ID edgeAppName := ID
edgeAppDescription := "" edgeAppDescription := ""
edgeAppEnv, err := godotenv.Read(utils.GetPath("edgeAppsPath") + ID + envFilename) edgeAppEnv, err := godotenv.Read(utils.GetPath(utils.EdgeAppsPath) + ID + envFilename)
if err != nil { if err != nil {
log.Println("Error loading .env file for edgeapp " + edgeAppName) log.Println("Error loading .env file for edgeapp " + edgeAppName)
@ -79,7 +79,7 @@ func GetEdgeApp(ID string) MaybeEdgeApp {
edgeAppInternetAccessible := false edgeAppInternetAccessible := false
edgeAppInternetURL := "" edgeAppInternetURL := ""
myEdgeAppServiceEnv, err := godotenv.Read(utils.GetPath("edgeAppsPath") + ID + myEdgeAppServiceEnvFilename) myEdgeAppServiceEnv, err := godotenv.Read(utils.GetPath(utils.EdgeAppsPath) + ID + myEdgeAppServiceEnvFilename)
if err != nil { if err != nil {
log.Println("No myedge.app environment file found. Status is Network-Only") log.Println("No myedge.app environment file found. Status is Network-Only")
} else { } else {
@ -113,7 +113,7 @@ func IsEdgeAppInstalled(ID string) bool {
result := false result := false
_, err := os.Stat(utils.GetPath("edgeAppsPath") + ID + runnableFilename) _, err := os.Stat(utils.GetPath(utils.EdgeAppsPath) + ID + runnableFilename)
if !os.IsNotExist(err) { if !os.IsNotExist(err) {
result = true result = true
} }
@ -125,11 +125,12 @@ func IsEdgeAppInstalled(ID string) bool {
func SetEdgeAppInstalled(ID string) bool { func SetEdgeAppInstalled(ID string) bool {
result := true result := true
edgeAppPath := utils.GetPath(utils.EdgeAppsPath)
_, err := os.Stat(utils.GetPath("edgeAppsPath") + ID + runnableFilename) _, err := os.Stat(edgeAppPath + ID + runnableFilename)
if os.IsNotExist(err) { if os.IsNotExist(err) {
_, err := os.Create(utils.GetPath("edgeAppsPath") + ID + runnableFilename) _, err := os.Create(edgeAppPath + ID + runnableFilename)
result = true result = true
if err != nil { if err != nil {
@ -153,7 +154,7 @@ func SetEdgeAppInstalled(ID string) bool {
func SetEdgeAppNotInstalled(ID string) bool { func SetEdgeAppNotInstalled(ID string) bool {
result := true result := true
err := os.Remove(utils.GetPath("edgeAppsPath") + ID + runnableFilename) err := os.Remove(utils.GetPath(utils.EdgeAppsPath) + ID + runnableFilename)
if err != nil { if err != nil {
result = false result = false
log.Fatal(err) log.Fatal(err)
@ -172,7 +173,7 @@ func GetEdgeApps() []EdgeApp {
// Building list of available edgeapps in the system with their status // Building list of available edgeapps in the system with their status
files, err := ioutil.ReadDir(utils.GetPath("edgeAppsPath")) files, err := ioutil.ReadDir(utils.GetPath(utils.EdgeAppsPath))
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -237,16 +238,16 @@ func GetEdgeAppStatus(ID string) EdgeAppStatus {
// GetEdgeAppServices : Returns a // GetEdgeAppServices : Returns a
func GetEdgeAppServices(ID string) []EdgeAppService { func GetEdgeAppServices(ID string) []EdgeAppService {
wsPath := utils.GetPath(utils.WsPath)
cmdArgs := []string{"-r", ".services | keys[]", utils.GetPath("edgeAppsPath") + ID + configFilename} cmdArgs := []string{"-r", ".services | keys[]", utils.GetPath(utils.EdgeAppsPath) + ID + configFilename}
servicesString := utils.Exec(utils.GetPath("wsPath"), "yq", cmdArgs) servicesString := utils.Exec(utils.GetPath(utils.WsPath), "yq", cmdArgs)
serviceSlices := strings.Split(servicesString, "\n") serviceSlices := strings.Split(servicesString, "\n")
serviceSlices = utils.DeleteEmptySlices(serviceSlices) serviceSlices = utils.DeleteEmptySlices(serviceSlices)
var edgeAppServices []EdgeAppService var edgeAppServices []EdgeAppService
for _, serviceID := range serviceSlices { for _, serviceID := range serviceSlices {
cmdArgs = []string{"-f", utils.GetPath("wsPath") + "/docker-compose.yml", "exec", "-T", serviceID, "echo", "'Service Check'"} cmdArgs = []string{"-f", wsPath + "/docker-compose.yml", "exec", "-T", serviceID, "echo", "'Service Check'"}
cmdResult := utils.Exec(utils.GetPath("wsPath"), "docker-compose", cmdArgs) cmdResult := utils.Exec(wsPath, "docker-compose", cmdArgs)
isRunning := false isRunning := false
if cmdResult != "" { if cmdResult != "" {
isRunning = true isRunning = true
@ -260,16 +261,14 @@ func GetEdgeAppServices(ID string) []EdgeAppService {
// RunEdgeApp : Run an EdgeApp and return its most current status // RunEdgeApp : Run an EdgeApp and return its most current status
func RunEdgeApp(ID string) EdgeAppStatus { func RunEdgeApp(ID string) EdgeAppStatus {
wsPath := utils.GetPath(utils.WsPath)
services := GetEdgeAppServices(ID) services := GetEdgeAppServices(ID)
cmdArgs := []string{} cmdArgs := []string{}
for _, service := range services { for _, service := range services {
cmdArgs = []string{"-f", utils.GetPath("wsPath") + "/docker-compose.yml", "start", service.ID} cmdArgs = []string{"-f", wsPath + "/docker-compose.yml", "start", service.ID}
utils.Exec(utils.GetPath("wsPath"), "docker-compose", cmdArgs) utils.Exec(wsPath, "docker-compose", cmdArgs)
} }
// Wait for it to settle up before continuing... // Wait for it to settle up before continuing...
@ -281,16 +280,13 @@ func RunEdgeApp(ID string) EdgeAppStatus {
// StopEdgeApp : Stops an EdgeApp and return its most current status // StopEdgeApp : Stops an EdgeApp and return its most current status
func StopEdgeApp(ID string) EdgeAppStatus { func StopEdgeApp(ID string) EdgeAppStatus {
wsPath := utils.GetPath(utils.WsPath)
services := GetEdgeAppServices(ID) services := GetEdgeAppServices(ID)
cmdArgs := []string{} cmdArgs := []string{}
for _, service := range services { for _, service := range services {
cmdArgs = []string{"-f", utils.GetPath("wsPath") + "/docker-compose.yml", "stop", service.ID} cmdArgs = []string{"-f", wsPath + "/docker-compose.yml", "stop", service.ID}
utils.Exec(utils.GetPath("wsPath"), "docker-compose", cmdArgs) utils.Exec(wsPath, "docker-compose", cmdArgs)
} }
// Wait for it to settle up before continuing... // Wait for it to settle up before continuing...
@ -306,7 +302,7 @@ func EnableOnline(ID string, InternetURL string) MaybeEdgeApp {
maybeEdgeApp := GetEdgeApp(ID) maybeEdgeApp := GetEdgeApp(ID)
if maybeEdgeApp.Valid { // We're only going to do this operation if the EdgeApp actually exists. if maybeEdgeApp.Valid { // We're only going to do this operation if the EdgeApp actually exists.
// Create the myedgeapp.env file and add the InternetURL entry to it // Create the myedgeapp.env file and add the InternetURL entry to it
envFilePath := utils.GetPath("edgeAppsPath") + ID + myEdgeAppServiceEnvFilename envFilePath := utils.GetPath(utils.EdgeAppsPath) + ID + myEdgeAppServiceEnvFilename
env, _ := godotenv.Unmarshal("INTERNET_URL=" + InternetURL) env, _ := godotenv.Unmarshal("INTERNET_URL=" + InternetURL)
_ = godotenv.Write(env, envFilePath) _ = godotenv.Write(env, envFilePath)
} }
@ -320,13 +316,13 @@ func EnableOnline(ID string, InternetURL string) MaybeEdgeApp {
// DisableOnline : Removes env files necessary for system external access config. Rebuilds containers in project (in case of change only). // DisableOnline : Removes env files necessary for system external access config. Rebuilds containers in project (in case of change only).
func DisableOnline(ID string) MaybeEdgeApp { func DisableOnline(ID string) MaybeEdgeApp {
envFilePath := utils.GetPath("edgeAppsPath") + ID + myEdgeAppServiceEnvFilename envFilePath := utils.GetPath(utils.EdgeAppsPath) + ID + myEdgeAppServiceEnvFilename
_, err := godotenv.Read(envFilePath) _, err := godotenv.Read(envFilePath)
if err != nil { if err != nil {
log.Println("myedge.app environment file for " + ID + " not found. No need to delete.") log.Println("myedge.app environment file for " + ID + " not found. No need to delete.")
} else { } else {
cmdArgs := []string{envFilePath} cmdArgs := []string{envFilePath}
utils.Exec(utils.GetPath("wsPath"), "rm", cmdArgs) utils.Exec(utils.GetPath(utils.WsPath), "rm", cmdArgs)
} }
buildFrameworkContainers() buildFrameworkContainers()
@ -337,7 +333,7 @@ func DisableOnline(ID string) MaybeEdgeApp {
func EnablePublicDashboard(InternetURL string) bool { func EnablePublicDashboard(InternetURL string) bool {
envFilePath := utils.GetPath("apiPath") + myEdgeAppServiceEnvFilename envFilePath := utils.GetPath(utils.ApiPath) + myEdgeAppServiceEnvFilename
env, _ := godotenv.Unmarshal("INTERNET_URL=" + InternetURL) env, _ := godotenv.Unmarshal("INTERNET_URL=" + InternetURL)
_ = godotenv.Write(env, envFilePath) _ = godotenv.Write(env, envFilePath)
@ -348,28 +344,29 @@ func EnablePublicDashboard(InternetURL string) bool {
} }
func DisablePublicDashboard() bool { func DisablePublicDashboard() bool {
envFilePath := utils.GetPath("apiPath") + myEdgeAppServiceEnvFilename envFilePath := utils.GetPath(utils.ApiPath) + myEdgeAppServiceEnvFilename
if !IsPublicDashboard() { if !IsPublicDashboard() {
log.Println("myedge.app environment file for the dashboard / api not found. No need to delete.") log.Println("myedge.app environment file for the dashboard / api not found. No need to delete.")
return false return false
} }
cmdArgs := []string{envFilePath} cmdArgs := []string{envFilePath}
utils.Exec(utils.GetPath("apiPath"), "rm", cmdArgs) utils.Exec(utils.GetPath(utils.ApiPath), "rm", cmdArgs)
buildFrameworkContainers() buildFrameworkContainers()
return true return true
} }
func IsPublicDashboard() bool { func IsPublicDashboard() bool {
envFilePath := utils.GetPath("apiPath") + myEdgeAppServiceEnvFilename envFilePath := utils.GetPath(utils.ApiPath) + myEdgeAppServiceEnvFilename
_, err := godotenv.Read(envFilePath) _, err := godotenv.Read(envFilePath)
return err == nil return err == nil
} }
func buildFrameworkContainers() { func buildFrameworkContainers() {
cmdArgs := []string{utils.GetPath("wsPath") + "ws", "--build"} wsPath := utils.GetPath(utils.WsPath)
utils.ExecAndStream(utils.GetPath("wsPath"), "sh", cmdArgs) cmdArgs := []string{wsPath + "ws", "--build"}
utils.ExecAndStream(wsPath, "sh", cmdArgs)
time.Sleep(defaultContainerOperationSleepTime) time.Sleep(defaultContainerOperationSleepTime)

View File

@ -224,9 +224,9 @@ func getDevicesSpaceUsage(devices []Device) []Device {
bucketsUsageSplit := (uint64)(0) bucketsUsageSplit := (uint64)(0)
othersUsageSplit := (uint64)(0) othersUsageSplit := (uint64)(0)
edgeappsDirSize, _ := getDirSize(utils.GetPath("edgeAppsPath")) edgeappsDirSize, _ := getDirSize(utils.GetPath(utils.EdgeAppsPath))
// TODO for later: Figure out to get correct paths for each partition... // TODO for later: Figure out to get correct paths for each partition...
wsAppDataDirSize, _ := getDirSize("/home/system/components/ws/appdata") wsAppDataDirSize, _ := getDirSize(utils.GetPath(utils.WsPath) + "/appdata")
if partition.Mountpoint == "/" { if partition.Mountpoint == "/" {
edgeappsUsageSplit = edgeappsDirSize + wsAppDataDirSize edgeappsUsageSplit = edgeappsDirSize + wsAppDataDirSize

View File

@ -7,9 +7,8 @@ import (
"github.com/edgebox-iot/edgeboxctl/internal/utils" "github.com/edgebox-iot/edgeboxctl/internal/utils"
"github.com/shirou/gopsutil/host"
"github.com/joho/godotenv" "github.com/joho/godotenv"
"github.com/shirou/gopsutil/host"
) )
// GetUptimeInSeconds: Returns a value (as string) of the total system uptime // GetUptimeInSeconds: Returns a value (as string) of the total system uptime
@ -29,7 +28,7 @@ func GetUptimeFormatted() string {
return fmt.Sprintf("%d days, %d hours, %d minutes", days, hours, minutes) return fmt.Sprintf("%d days, %d hours, %d minutes", days, hours, minutes)
} }
// GetIP: Returns the ip address of the instance // GetIP: Returns the ip address of the instance
func GetIP() string { func GetIP() string {
ip := "" ip := ""
@ -64,7 +63,8 @@ func GetHostname() string {
func SetupCloudOptions() { func SetupCloudOptions() {
var cloudEnv map[string]string var cloudEnv map[string]string
cloudEnv, err := godotenv.Read(utils.GetPath("cloudEnvFileLocation")) cloudEnvFileLocationPath := utils.GetPath(utils.CloudEnvFileLocation)
cloudEnv, err := godotenv.Read(cloudEnvFileLocationPath)
if err != nil { if err != nil {
fmt.Println("Error loading .env file for cloud version setup") fmt.Println("Error loading .env file for cloud version setup")
@ -83,6 +83,5 @@ func SetupCloudOptions() {
} }
// In the end of this operation takes place, remove the env file as to not overwrite any options once they are set. // In the end of this operation takes place, remove the env file as to not overwrite any options once they are set.
utils.Exec("/", "rm", []string{utils.GetPath("cloudEnvFileLocation")}) utils.Exec("/", "rm", []string{cloudEnvFileLocationPath})
} }

View File

@ -329,14 +329,15 @@ func ExecuteSchedules(tick int) {
func taskSetupTunnel(args taskSetupTunnelArgs) string { func taskSetupTunnel(args taskSetupTunnelArgs) string {
fmt.Println("Executing taskSetupTunnel") fmt.Println("Executing taskSetupTunnel")
wsPath := utils.GetPath(utils.WsPath)
cmdargs := []string{"gen", "--name", args.NodeName, "--token", args.BootnodeToken, args.BootnodeAddress + ":8655", "--prefix", args.AssignedAddress} cmdargs := []string{"gen", "--name", args.NodeName, "--token", args.BootnodeToken, args.BootnodeAddress + ":8655", "--prefix", args.AssignedAddress}
utils.Exec(utils.GetPath("wsPath"), "tinc-boot", cmdargs) utils.Exec(wsPath, "tinc-boot", cmdargs)
cmdargs = []string{"start", "tinc@dnet"} cmdargs = []string{"start", "tinc@dnet"}
utils.Exec(utils.GetPath("wsPath"), "systemctl", cmdargs) utils.Exec(wsPath, "systemctl", cmdargs)
cmdargs = []string{"enable", "tinc@dnet"} cmdargs = []string{"enable", "tinc@dnet"}
utils.Exec(utils.GetPath("wsPath"), "systemctl", cmdargs) utils.Exec(wsPath, "systemctl", cmdargs)
output := "OK" // Better check / logging of command execution result. output := "OK" // Better check / logging of command execution result.
return output return output

View File

@ -81,7 +81,7 @@ func DeleteEmptySlices(s []string) []string {
func GetSQLiteDbConnectionDetails() string { func GetSQLiteDbConnectionDetails() string {
var apiEnv map[string]string var apiEnv map[string]string
apiEnv, err := godotenv.Read(GetPath("apiEnvFileLocation")) apiEnv, err := godotenv.Read(GetPath(ApiEnvFileLocation))
if err != nil { if err != nil {
log.Fatal("Error loading .env file") log.Fatal("Error loading .env file")
@ -100,6 +100,12 @@ func GetSQLiteFormattedDateTime(t time.Time) string {
return formatedDatetime return formatedDatetime
} }
const CloudEnvFileLocation string = "cloudEnvFileLocation"
const ApiEnvFileLocation string = "apiEnvFileLocation"
const ApiPath string = "apiPath"
const EdgeAppsPath string = "edgeAppsPath"
const WsPath string = "wsPath"
// GetPath : Returns either the hardcoded path, or a overwritten value via .env file at project root. Register paths here for seamless working code between dev and prod environments ;) // GetPath : Returns either the hardcoded path, or a overwritten value via .env file at project root. Register paths here for seamless working code between dev and prod environments ;)
func GetPath(pathKey string) string { func GetPath(pathKey string) string {
@ -113,7 +119,7 @@ func GetPath(pathKey string) string {
} }
switch pathKey { switch pathKey {
case "cloudEnvFileLocation": case CloudEnvFileLocation:
if env["CLOUD_ENV_FILE_LOCATION"] != "" { if env["CLOUD_ENV_FILE_LOCATION"] != "" {
targetPath = env["CLOUD_ENV_FILE_LOCATION"] targetPath = env["CLOUD_ENV_FILE_LOCATION"]
@ -121,7 +127,7 @@ func GetPath(pathKey string) string {
targetPath = "/home/system/components/edgeboxctl/cloud.env" targetPath = "/home/system/components/edgeboxctl/cloud.env"
} }
case "apiEnvFileLocation": case ApiEnvFileLocation:
if env["API_ENV_FILE_LOCATION"] != "" { if env["API_ENV_FILE_LOCATION"] != "" {
targetPath = env["API_ENV_FILE_LOCATION"] targetPath = env["API_ENV_FILE_LOCATION"]
@ -129,15 +135,15 @@ func GetPath(pathKey string) string {
targetPath = "/home/system/components/api/edgebox.env" targetPath = "/home/system/components/api/edgebox.env"
} }
case "apiPath": case ApiPath:
if env["API_PATH"] != "" { if env["API_PATH"] != "" {
targetPath = env["APT_PATH"] targetPath = env["API_PATH"]
} else { } else {
targetPath = "/home/system/components/api/" targetPath = "/home/system/components/api/"
} }
case "edgeAppsPath": case EdgeAppsPath:
if env["EDGEAPPS_PATH"] != "" { if env["EDGEAPPS_PATH"] != "" {
targetPath = env["EDGEAPPS_PATH"] targetPath = env["EDGEAPPS_PATH"]
@ -145,7 +151,7 @@ func GetPath(pathKey string) string {
targetPath = "/home/system/components/apps/" targetPath = "/home/system/components/apps/"
} }
case "wsPath": case WsPath:
if env["WS_PATH"] != "" { if env["WS_PATH"] != "" {
targetPath = env["WS_PATH"] targetPath = env["WS_PATH"]

View File

@ -89,8 +89,7 @@ func TestGetPath(t *testing.T) {
t.Fail() t.Fail()
} }
validPathKey := "wsPath" result = GetPath(WsPath)
result = GetPath(validPathKey)
if result != "/home/system/components/ws/" { if result != "/home/system/components/ws/" {
t.Log("Expected /home/system/components/ws/ but got", result) t.Log("Expected /home/system/components/ws/ but got", result)
t.Fail() t.Fail()