Author SHA1 Message Date
Malachi Soord 3cb36dff1e Fix tests 2023-11-19 22:38:54 +01:00
Malachi Soord 03f7ac8468 Leverage release as version 2023-11-19 22:33:54 +01:00
Malachi Soord 8be566afb9 Fix up install 2023-11-19 21:46:11 +01:00
Malachi Soord 9c2a0dbefe Tidy repo (#30)
* Tidy repo

* Tidy

* Fix up

* Setup default target
2023-11-19 21:33:18 +01:00
dependabot[bot]anddependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 4e399f63ea Bump actions/setup-go from 3 to 4 (#31)
Bumps [actions/setup-go](https://github.com/actions/setup-go) from 3 to 4.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/setup-go
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-19 12:31:08 +01:00
Paulo Truta e238e9d71d Basic Auth and RemoveApp Support 2023-11-14 21:00:09 +01:00
= db56530311 Don't fail install if service cannot be stopped (does not exist yet) 2023-11-05 12:19:09 +01:00
= 319acbd0e1 Add explicit support for prod amd64 build in Makefile 2023-11-05 11:47:42 +01:00
10 changed files with 363 additions and 262 deletions
+2 -2
View File
@@ -13,9 +13,9 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Set up Go - name: Set up Go
uses: actions/setup-go@v3 uses: actions/setup-go@v4
with: with:
go-version: ^1.15 go-version: '1.20.2'
- name: Check out code - name: Check out code
uses: actions/checkout@v3 uses: actions/checkout@v3
- name: Build - name: Build
+3 -5
View File
@@ -1,11 +1,9 @@
FROM golang:latest FROM golang:1.20.2
WORKDIR /app WORKDIR /app
COPY ./ /app COPY ./ /app
RUN go mod download RUN go install github.com/githubnemo/CompileDaemon@latest
RUN go get github.com/githubnemo/CompileDaemon ENTRYPOINT CompileDaemon --build="make build" --command=./bin/edgeboxctl-$(go env GOOS)-$(go env GOARCH)
ENTRYPOINT CompileDaemon --build="make build" --command=./bin/edgeboxctl
+11 -23
View File
@@ -1,25 +1,18 @@
PROJECT?=github.com/edgebox-iot/edgeboxctl .DEFAULT_GOAL := build
PROJECT ?= github.com/edgebox-iot/edgeboxctl
RELEASE ?= dev RELEASE ?= dev
COMMIT := $(shell git rev-parse --short HEAD) COMMIT := $(shell git rev-parse --short HEAD)
BUILD_DATE := $(shell date -u '+%Y-%m-%d_%H:%M:%S') BUILD_DATE := $(shell date -u '+%Y-%m-%d_%H:%M:%S')
BUILD_DIR = bin BUILD_DIR = bin
GOOS := $(shell go env GOOS)
GOARCH := $(shell go env GOARCH)
build-all:
build-all: clean
GOOS=linux GOARCH=amd64 make build GOOS=linux GOARCH=amd64 make build
GOOS=linux GOARCH=arm make build GOOS=linux GOARCH=arm make build
GOOS=linux GOARCH=arm64 make build
build-prod:
GOOS=linux GOARCH=arm RELEASE=prod make build
build-cloud:
GOOS=linux GOARCH=amd64 RELEASE=cloud make build
build-arm64:
GOOS=linux GOARCH=arm64 RELEASE=prod make build
build-armhf:
GOOS=linux GOARCH=arm RELEASE=prod make build
build: build:
@echo "Building ${GOOS}-${GOARCH}" @echo "Building ${GOOS}-${GOARCH}"
@@ -28,7 +21,6 @@ build:
-X ${PROJECT}/internal/diagnostics.Commit=${COMMIT} \ -X ${PROJECT}/internal/diagnostics.Commit=${COMMIT} \
-X ${PROJECT}/internal/diagnostics.BuildDate=${BUILD_DATE}" \ -X ${PROJECT}/internal/diagnostics.BuildDate=${BUILD_DATE}" \
-o bin/edgeboxctl-${GOOS}-${GOARCH} ${PROJECT}/cmd/edgeboxctl -o bin/edgeboxctl-${GOOS}-${GOARCH} ${PROJECT}/cmd/edgeboxctl
cp ./bin/edgeboxctl-${GOOS}-${GOARCH} ./bin/edgeboxctl
clean: clean:
rm -rf ${BUILD_DIR} rm -rf ${BUILD_DIR}
@@ -41,19 +33,16 @@ test-with-coverage:
go test -tags=unit -timeout=600s -v ./... -coverprofile=coverage.out go test -tags=unit -timeout=600s -v ./... -coverprofile=coverage.out
install: install:
sudo systemctl stop edgeboxctl sudo systemctl stop edgeboxctl || true
sudo rm -rf /usr/local/bin/edgeboxctl /usr/local/sbin/edgeboctl /lib/systemd/system/edgeboxctl.service sudo rm -rf /usr/local/bin/edgeboxctl /usr/local/sbin/edgeboctl /lib/systemd/system/edgeboxctl.service
sudo cp ./bin/edgeboxctl /usr/local/bin/edgeboxctl sudo cp ./bin/edgeboxctl-${GOOS}-${GOARCH} /usr/local/bin/edgeboxctl
sudo cp ./bin/edgeboxctl /usr/local/sbin/edgeboxctl sudo cp ./bin/edgeboxctl-${GOOS}-${GOARCH} /usr/local/sbin/edgeboxctl
sudo cp ./edgeboxctl.service /lib/systemd/system/edgeboxctl.service sudo cp ./edgeboxctl.service /lib/systemd/system/edgeboxctl.service
sudo systemctl daemon-reload sudo systemctl daemon-reload
@echo "Edgeboxctl installed successfully" @echo "Edgeboxctl installed successfully"
@echo "To start edgeboxctl run: systemctl start edgeboxctl" @echo "To start edgeboxctl run: systemctl start edgeboxctl"
install-prod: build-prod install build-install: build install
install-cloud: build-cloud install
install-arm64: build-arm64 install
install-armhf: build-armhf install
start: start:
systemctl start edgeboxctl systemctl start edgeboxctl
@@ -63,4 +52,3 @@ stop:
log: start log: start
journalctl -fu edgeboxctl journalctl -fu edgeboxctl
+7 -12
View File
@@ -8,7 +8,7 @@
<h3 align="center">Edgebox Control Module</h3> <h3 align="center">Edgebox Control Module</h3>
<p align="center"> <p align="center">
A System Control module written in Go. Its resonsability is to configure dependencies and perform system tasks, automatically in a schedule, or by command. A System Control module written in Go. Its responsibility is to configure dependencies and perform system tasks, automatically on a schedule, or on demand.
<br /> <br />
<br /> <br />
<a href="https://github.com/github_username/edgeboxctl/issues">Report Bug</a> <a href="https://github.com/github_username/edgeboxctl/issues">Report Bug</a>
@@ -38,8 +38,6 @@
<!-- ABOUT THE PROJECT --> <!-- ABOUT THE PROJECT -->
## About The Project ## About The Project
[![Edgebox Screen Shot][product-screenshot]](https://edgebox.co)
Edgebox is an easy to configure and use system. It brings powerful features that go alongside or can even completely replace various services that you already use in the day-to-day. Edgebox is an easy to configure and use system. It brings powerful features that go alongside or can even completely replace various services that you already use in the day-to-day.
@@ -58,18 +56,15 @@ To get a local copy up and running follow these simple steps.
### Prerequisites ### Prerequisites
If you're installing this to run natively in the system, you better be doing it inside of the [Development Virtual Machine](https://github.com/edgebox-iot/devm). This software can do destructive action in the system is is running. You've been warned. If you're running for development purposes, a docker container suffices, so make sure you have:
If you're running for development purposes, a Docker container suffices, so make sure you have: * docker
* Docker * docker compose
* Docker Compose
```sh
sudo apt-get install docker docker-compose
```
Check the following links for more info on [Docker](https://www.docker.com/) and [Docker Compose](https://docs.docker.com/compose/). Check the following links for more info on [Docker](https://www.docker.com/) and [Docker Compose](https://docs.docker.com/compose/).
Aditionally, edgeboxctl needs the following bash commands available wherever it runs: Aditionally, `edgeboxctl` needs the following bash commands available wherever it runs:
* `arm-linux-gnueabi-gcc` (`sudo apt-get install gcc-arm*`) * `arm-linux-gnueabi-gcc` (`sudo apt-get install gcc-arm*`)
* `sh` * `sh`
* `rm` * `rm`
@@ -121,4 +116,4 @@ Contributions are what make the open source community such an amazing place to b
<!-- LICENSE --> <!-- LICENSE -->
## License ## License
Distributed under the MIT License. See `LICENSE` for more information. Distributed under the Elastic License 2.0. See `LICENSE` for more information.
-13
View File
@@ -1,18 +1,5 @@
package diagnostics package diagnostics
type ReleaseVersion string
var Version string var Version string
var Commit string var Commit string
var BuildDate string var BuildDate string
const (
DEV_VERSION ReleaseVersion = "dev"
PROD_VERSION ReleaseVersion = "prod"
CLOUD_VERSION ReleaseVersion = "cloud"
OTHER_VERSION ReleaseVersion = "other"
)
func GetReleaseVersion() ReleaseVersion {
return ReleaseVersion(Version)
}
+56 -1
View File
@@ -25,6 +25,7 @@ type EdgeApp struct {
InternetURL string `json:"internet_url"` InternetURL string `json:"internet_url"`
Options []EdgeAppOption `json:"options"` Options []EdgeAppOption `json:"options"`
NeedsConfig bool `json:"needs_config"` NeedsConfig bool `json:"needs_config"`
Login EdgeAppLogin `json:"login"`
} }
// MaybeEdgeApp : Boolean flag for validation of edgeapp existance // MaybeEdgeApp : Boolean flag for validation of edgeapp existance
@@ -55,11 +56,19 @@ type EdgeAppOption struct {
IsInstallLocked bool `json:"is_install_locked"` IsInstallLocked bool `json:"is_install_locked"`
} }
type EdgeAppLogin struct {
Enabled bool `json:"enabled"`
Username string `json:"username"`
Password string `json:"password"`
}
const configFilename = "/edgebox-compose.yml" const configFilename = "/edgebox-compose.yml"
const envFilename = "/edgebox.env" const envFilename = "/edgebox.env"
const optionsTemplateFilename = "/edgeapp.template.env" const optionsTemplateFilename = "/edgeapp.template.env"
const optionsEnvFilename = "/edgeapp.env" const optionsEnvFilename = "/edgeapp.env"
const authEnvFilename = "/auth.env"
const runnableFilename = "/.run" const runnableFilename = "/.run"
const appdataFoldername = "/appdata"
const myEdgeAppServiceEnvFilename = "/myedgeapp.env" const myEdgeAppServiceEnvFilename = "/myedgeapp.env"
const defaultContainerOperationSleepTime time.Duration = time.Second * 10 const defaultContainerOperationSleepTime time.Duration = time.Second * 10
@@ -202,6 +211,21 @@ func GetEdgeApp(ID string) MaybeEdgeApp {
} }
} }
edgeAppBasicAuthEnabled := false
edgeAppBasicAuthUsername := ""
edgeAppBasicAuthPassword := ""
edgeAppAuthEnv, err := godotenv.Read(utils.GetPath(utils.EdgeAppsPath) + ID + authEnvFilename)
if err != nil {
log.Println("No auth.env file found. Login status is disabled.")
} else {
if edgeAppAuthEnv["USERNAME"] != "" && edgeAppAuthEnv["PASSWORD"] != "" {
edgeAppBasicAuthEnabled = true
edgeAppBasicAuthUsername = edgeAppAuthEnv["USERNAME"]
edgeAppBasicAuthPassword = edgeAppAuthEnv["PASSWORD"]
}
}
result = MaybeEdgeApp{ result = MaybeEdgeApp{
EdgeApp: EdgeApp{ EdgeApp: EdgeApp{
ID: ID, ID: ID,
@@ -214,6 +238,8 @@ func GetEdgeApp(ID string) MaybeEdgeApp {
InternetURL: edgeAppInternetURL, InternetURL: edgeAppInternetURL,
Options: edgeAppOptions, Options: edgeAppOptions,
NeedsConfig: needsConfig, NeedsConfig: needsConfig,
Login: EdgeAppLogin{edgeAppBasicAuthEnabled, edgeAppBasicAuthUsername, edgeAppBasicAuthPassword},
}, },
Valid: true, Valid: true,
} }
@@ -268,11 +294,40 @@ func SetEdgeAppInstalled(ID string) bool {
func SetEdgeAppNotInstalled(ID string) bool { func SetEdgeAppNotInstalled(ID string) bool {
// Stop the app first
StopEdgeApp(ID)
// Now remove any files
result := true result := true
err := os.Remove(utils.GetPath(utils.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.Println(err)
}
err = os.Remove(utils.GetPath(utils.EdgeAppsPath) + ID + authEnvFilename)
if err != nil {
result = false
log.Println(err)
}
err = os.RemoveAll(utils.GetPath(utils.EdgeAppsPath) + ID + appdataFoldername)
if err != nil {
result = false
log.Println(err)
}
err = os.Remove(utils.GetPath(utils.EdgeAppsPath) + ID + myEdgeAppServiceEnvFilename)
if err != nil {
result = false
log.Println(err)
}
err = os.Remove(utils.GetPath(utils.EdgeAppsPath) + ID + optionsEnvFilename)
if err != nil {
result = false
log.Println(err)
} }
buildFrameworkContainers() buildFrameworkContainers()
+2 -21
View File
@@ -6,7 +6,6 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/edgebox-iot/edgeboxctl/internal/diagnostics"
"github.com/edgebox-iot/edgeboxctl/internal/utils" "github.com/edgebox-iot/edgeboxctl/internal/utils"
"github.com/shirou/gopsutil/disk" "github.com/shirou/gopsutil/disk"
) )
@@ -75,20 +74,9 @@ const (
DISK_TYPE_VDA DeviceIdentifier = "vda" DISK_TYPE_VDA DeviceIdentifier = "vda"
) )
func GetDeviceIdentifier(release_version diagnostics.ReleaseVersion) DeviceIdentifier {
switch release_version {
case diagnostics.CLOUD_VERSION:
return DISK_TYPE_VDA
case diagnostics.PROD_VERSION:
return DISK_TYPE_MCBLK
}
return DISK_TYPE_SDA
}
// GetDevices : Returns a list of all available sotrage devices in structs filled with information
func GetDevices(release_version diagnostics.ReleaseVersion) []Device {
// GetDevices : Returns a list of all available storage devices in structs filled with information
func GetDevices() []Device {
var devices []Device var devices []Device
cmdArgs := []string{"--raw", "--bytes", "--noheadings"} cmdArgs := []string{"--raw", "--bytes", "--noheadings"}
@@ -100,8 +88,6 @@ func GetDevices(release_version diagnostics.ReleaseVersion) []Device {
firstDevice := true firstDevice := true
currentDeviceInUseFlag := false currentDeviceInUseFlag := false
mainDiskID := GetDeviceIdentifier(release_version)
for scanner.Scan() { for scanner.Scan() {
// 1 Device is represented here. Extract words in order for filling a Device struct // 1 Device is represented here. Extract words in order for filling a Device struct
// Example deviceRawInfo: "mmcblk0 179:0 0 29.7G 0 disk" // Example deviceRawInfo: "mmcblk0 179:0 0 29.7G 0 disk"
@@ -153,14 +139,9 @@ func GetDevices(release_version diagnostics.ReleaseVersion) []Device {
Status: DeviceStatus{ID: 1, Description: "healthy"}, Status: DeviceStatus{ID: 1, Description: "healthy"},
} }
if device.ID == mainDiskID {
device.MainDevice = true
}
currentDevice = device currentDevice = device
} else if isPartition { } else if isPartition {
mountpoint := "" mountpoint := ""
if len(deviceRawInfo) >= 7 { if len(deviceRawInfo) >= 7 {
mountpoint = deviceRawInfo[6] mountpoint = deviceRawInfo[6]
+1 -8
View File
@@ -7,14 +7,7 @@ import (
) )
func TestGetDevices(t *testing.T) { func TestGetDevices(t *testing.T) {
assertGetDevices(GetDevices(), t)
t.Log("Testing with release version dev")
assertGetDevices(GetDevices("dev"), t)
t.Log("Testing with release version prod")
assertGetDevices(GetDevices("prod"), t)
t.Log("Testing with release version cloud")
assertGetDevices(GetDevices("cloud"), t)
} }
func assertGetDevices(devices []Device, t *testing.T) { func assertGetDevices(devices []Device, t *testing.T) {
+1
View File
@@ -82,6 +82,7 @@ func SetupCloudOptions() {
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")
return
} }
if cloudEnv["NAME"] != "" { if cloudEnv["NAME"] != "" {
+280 -177
View File
@@ -39,6 +39,11 @@ type TaskOption struct {
Value string `json:"value"` Value string `json:"value"`
} }
type TaskBasicAuth struct {
Username string `json:"username"`
Password string `json:"password"`
}
type taskSetupTunnelArgs struct { type taskSetupTunnelArgs struct {
DomainName string `json:"domain_name"` DomainName string `json:"domain_name"`
} }
@@ -65,6 +70,15 @@ type taskSetEdgeAppOptionsArgs struct {
Options []TaskOption `json:"options"` Options []TaskOption `json:"options"`
} }
type taskSetEdgeAppBasicAuthArgs struct {
ID string `json:"id"`
Login TaskBasicAuth `json:"login"`
}
type taskRemoveEdgeAppBasicAuthArgs struct {
ID string `json:"id"`
}
type taskEnableOnlineArgs struct { type taskEnableOnlineArgs struct {
ID string `json:"id"` ID string `json:"id"`
InternetURL string `json:"internet_url"` InternetURL string `json:"internet_url"`
@@ -150,189 +164,208 @@ func ExecuteTask(task Task) Task {
log.Fatal(err.Error()) log.Fatal(err.Error())
} }
if diagnostics.GetReleaseVersion() == diagnostics.DEV_VERSION { log.Println("Task: " + task.Task)
log.Printf("Dev environemnt. Not executing tasks.") log.Println("Args: " + task.Args.String)
} else { switch task.Task {
log.Println("Task: " + task.Task) case "setup_backups":
log.Println("Args: " + task.Args.String)
switch task.Task {
case "setup_backups":
log.Println("Setting up Backups Destination...") log.Println("Setting up Backups Destination...")
var args taskSetupBackupsArgs var args taskSetupBackupsArgs
err := json.Unmarshal([]byte(task.Args.String), &args) err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil { if err != nil {
log.Println("Error reading arguments of setup_backups task.") log.Println("Error reading arguments of setup_backups task.")
} else { } else {
taskResult := taskSetupBackups(args) taskResult := taskSetupBackups(args)
taskResultBool := true
// Check if returned taskResult string contains "error"
if strings.Contains(taskResult, "error") {
taskResultBool = false
}
task.Result = sql.NullString{String: taskResult, Valid: taskResultBool}
}
case "start_backup":
log.Println("Backing up Edgebox...")
taskResult := taskBackup()
taskResultBool := true taskResultBool := true
// Check if returned taskResult string contains "error" // Check if returned taskResult string contains "error"
if strings.Contains(taskResult, "error") { if strings.Contains(taskResult, "error") {
taskResultBool = false taskResultBool = false
} }
task.Result = sql.NullString{String: taskResult, Valid: taskResultBool} task.Result = sql.NullString{String: taskResult, Valid: taskResultBool}
case "restore_backup":
log.Println("Attempting to Restore Last Backup to Edgebox")
taskResult := taskRestoreBackup()
taskResultBool := true
// Check if returned taskResult string contains "error"
if strings.Contains(taskResult, "error") {
taskResultBool = false
}
task.Result = sql.NullString{String: taskResult, Valid: taskResultBool}
case "setup_tunnel":
log.Println("Setting up Cloudflare Tunnel...")
var args taskSetupTunnelArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of setup_tunnel task: %s", err)
status := "{\"status\": \"error\", \"message\": \"The Domain Name you are going to Authorize must be provided beforehand! Please insert a domain name and try again.\"}"
utils.WriteOption("TUNNEL_STATUS", status)
} else {
taskResult := taskSetupTunnel(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "start_tunnel":
log.Println("Starting Cloudflare Tunnel...")
taskResult := taskStartTunnel()
task.Result = sql.NullString{String: taskResult, Valid: true}
case "stop_tunnel":
log.Println("Stopping Cloudflare Tunnel...")
taskResult := taskStopTunnel()
task.Result = sql.NullString{String: taskResult, Valid: true}
case "disable_tunnel":
log.Println("Disabling Cloudflare Tunnel...")
taskResult := taskDisableTunnel()
task.Result = sql.NullString{String: taskResult, Valid: true}
case "install_edgeapp":
log.Println("Installing EdgeApp...")
var args taskInstallEdgeAppArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of install_edgeapp task: %s", err)
} else {
taskResult := taskInstallEdgeApp(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "remove_edgeapp":
log.Println("Removing EdgeApp...")
var args taskRemoveEdgeAppArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of remove_edgeapp task: %s", err)
} else {
taskResult := taskRemoveEdgeApp(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "start_edgeapp":
log.Println("Starting EdgeApp...")
var args taskStartEdgeAppArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of start_edgeapp task: %s", err)
} else {
taskResult := taskStartEdgeApp(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "stop_edgeapp":
log.Println("Stopping EdgeApp...")
var args taskStopEdgeAppArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of stop_edgeapp task: %s", err)
} else {
taskResult := taskStopEdgeApp(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "set_edgeapp_options":
log.Println("Setting EdgeApp Options...")
var args taskSetEdgeAppOptionsArgs
// {"id":"podgrab","options":{"PODGRAB_PASSWORD":"fumarmata"}}
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of set_edgeapp_options task: %s", err)
} else {
taskResult := taskSetEdgeAppOptions(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "enable_online":
log.Println("Enabling online access to EdgeApp...")
var args taskEnableOnlineArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of enable_online task: %s", err)
} else {
taskResult := taskEnableOnline(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "disable_online":
log.Println("Disabling online access to EdgeApp...")
var args taskDisableOnlineArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of enable_online task: %s", err)
} else {
taskResult := taskDisableOnline(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "enable_public_dashboard":
log.Println("Enabling online access to Dashboard...")
var args taskEnablePublicDashboardArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of enable_public_dashboard task: %s", err)
} else {
taskResult := taskEnablePublicDashboard(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "disable_public_dashboard":
log.Println("Disabling online access to Dashboard...")
taskResult := taskDisablePublicDashboard()
task.Result = sql.NullString{String: taskResult, Valid: true}
} }
case "start_backup":
log.Println("Backing up Edgebox...")
taskResult := taskBackup()
taskResultBool := true
// Check if returned taskResult string contains "error"
if strings.Contains(taskResult, "error") {
taskResultBool = false
}
task.Result = sql.NullString{String: taskResult, Valid: taskResultBool}
case "restore_backup":
log.Println("Attempting to Restore Last Backup to Edgebox")
taskResult := taskRestoreBackup()
taskResultBool := true
// Check if returned taskResult string contains "error"
if strings.Contains(taskResult, "error") {
taskResultBool = false
}
task.Result = sql.NullString{String: taskResult, Valid: taskResultBool}
case "setup_tunnel":
log.Println("Setting up Cloudflare Tunnel...")
var args taskSetupTunnelArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of setup_tunnel task: %s", err)
status := "{\"status\": \"error\", \"message\": \"The Domain Name you are going to Authorize must be provided beforehand! Please insert a domain name and try again.\"}"
utils.WriteOption("TUNNEL_STATUS", status)
} else {
taskResult := taskSetupTunnel(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "start_tunnel":
log.Println("Starting Cloudflare Tunnel...")
taskResult := taskStartTunnel()
task.Result = sql.NullString{String: taskResult, Valid: true}
case "stop_tunnel":
log.Println("Stopping Cloudflare Tunnel...")
taskResult := taskStopTunnel()
task.Result = sql.NullString{String: taskResult, Valid: true}
case "disable_tunnel":
log.Println("Disabling Cloudflare Tunnel...")
taskResult := taskDisableTunnel()
task.Result = sql.NullString{String: taskResult, Valid: true}
case "install_edgeapp":
log.Println("Installing EdgeApp...")
var args taskInstallEdgeAppArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of install_edgeapp task: %s", err)
} else {
taskResult := taskInstallEdgeApp(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "remove_edgeapp":
log.Println("Removing EdgeApp...")
var args taskRemoveEdgeAppArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of remove_edgeapp task: %s", err)
} else {
taskResult := taskRemoveEdgeApp(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "start_edgeapp":
log.Println("Starting EdgeApp...")
var args taskStartEdgeAppArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of start_edgeapp task: %s", err)
} else {
taskResult := taskStartEdgeApp(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "stop_edgeapp":
log.Println("Stopping EdgeApp...")
var args taskStopEdgeAppArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of stop_edgeapp task: %s", err)
} else {
taskResult := taskStopEdgeApp(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "set_edgeapp_options":
log.Println("Setting EdgeApp Options...")
var args taskSetEdgeAppOptionsArgs
// {"id":"podgrab","options":{"PODGRAB_PASSWORD":"fumarmata"}}
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of set_edgeapp_options task: %s", err)
} else {
taskResult := taskSetEdgeAppOptions(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "set_edgeapp_basic_auth":
log.Println("Settig EdgeApp Basic Authentication...")
var args taskSetEdgeAppBasicAuthArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of set_edgeapp_basic_auth task: %s", err)
} else {
taskResult := taskSetEdgeAppBasicAuth(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "remove_edgeapp_basic_auth":
log.Println("Removing EdgeApp Basic Authentication...")
var args taskRemoveEdgeAppBasicAuthArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of remove_edgeapp_basic_auth task: %s", err)
} else {
taskResult := taskRemoveEdgeAppBasicAuth(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "enable_online":
log.Println("Enabling online access to EdgeApp...")
var args taskEnableOnlineArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of enable_online task: %s", err)
} else {
taskResult := taskEnableOnline(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "disable_online":
log.Println("Disabling online access to EdgeApp...")
var args taskDisableOnlineArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of enable_online task: %s", err)
} else {
taskResult := taskDisableOnline(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "enable_public_dashboard":
log.Println("Enabling online access to Dashboard...")
var args taskEnablePublicDashboardArgs
err := json.Unmarshal([]byte(task.Args.String), &args)
if err != nil {
log.Printf("Error reading arguments of enable_public_dashboard task: %s", err)
} else {
taskResult := taskEnablePublicDashboard(args)
task.Result = sql.NullString{String: taskResult, Valid: true}
}
case "disable_public_dashboard":
log.Println("Disabling online access to Dashboard...")
taskResult := taskDisablePublicDashboard()
task.Result = sql.NullString{String: taskResult, Valid: true}
} }
statement, err = db.Prepare("Update task SET status = ?, result = ?, updated = ? WHERE ID = ?;") // Prepare SQL Statement statement, err = db.Prepare("Update task SET status = ?, result = ?, updated = ? WHERE ID = ?;") // Prepare SQL Statement
if err != nil { if err != nil {
log.Fatal(err.Error()) log.Fatal(err.Error())
@@ -389,10 +422,9 @@ func ExecuteSchedules(tick int) {
// }) // })
// } // }
if diagnostics.GetReleaseVersion() == diagnostics.CLOUD_VERSION {
log.Println("Setting up cloud version options (name, email, api token)") log.Println("Setting up cloud version options (name, email, api token)")
taskSetupCloudOptions() taskSetupCloudOptions()
}
// Executing on startup (first tick). Schedules run before tasks in the SystemIterator // Executing on startup (first tick). Schedules run before tasks in the SystemIterator
uptime := taskGetSystemUptime() uptime := taskGetSystemUptime()
@@ -986,6 +1018,77 @@ func taskSetEdgeAppOptions(args taskSetEdgeAppOptionsArgs) string {
return string(resultJSON) return string(resultJSON)
} }
func taskSetEdgeAppBasicAuth(args taskSetEdgeAppBasicAuthArgs) string {
// Id is the edgeapp id
appID := args.ID
// Open the file to write the options,
// it is an env file in /home/system/components/apps/<app_id>/auth.env
// Get the path to the auth.env file
edgeappAuthEnvPath := "/home/system/components/apps/" + appID + "/auth.env"
// If the file does not exist, create it
if _, err := os.Stat(edgeappAuthEnvPath); os.IsNotExist(err) {
// Create the file
_, err := os.Create(edgeappAuthEnvPath)
if err != nil {
log.Printf("Error creating auth.env file: %s", err)
}
}
// It is an env file, so we can use go-dotenv to write the options
// Open the file
edgeappAuthEnvFile, err := os.OpenFile(edgeappAuthEnvPath, os.O_WRONLY, 0600)
if err != nil {
log.Printf("Error opening auth.env file: %s", err)
}
// Write the login values to the file
_, err = edgeappAuthEnvFile.WriteString("USERNAME=" + args.Login.Username + "\n" + "PASSWORD=" + args.Login.Password + "\n")
if err != nil {
log.Printf("Error writing credentials to auth.env file: %s", err)
}
// Close the file
err = edgeappAuthEnvFile.Close()
if err != nil {
log.Printf("Error closing auth.env file: %s", err)
}
result := edgeapps.GetEdgeAppStatus(appID)
resultJSON, _ := json.Marshal(result)
system.StartWs()
taskGetEdgeApps() // This task will imediatelly update the entry in the api database.
return string(resultJSON)
}
func taskRemoveEdgeAppBasicAuth(args taskRemoveEdgeAppBasicAuthArgs) string {
// Id is the edgeapp id
appID := args.ID
// Get the path to the auth.env file
edgeappAuthEnvFile := "/auth.env"
fmt.Println("Removing auth.env file" + edgeappAuthEnvFile)
err := os.Remove(utils.GetPath(utils.EdgeAppsPath) + args.ID + edgeappAuthEnvFile)
if err != nil {
log.Fatal(err)
}
result := edgeapps.GetEdgeAppStatus(appID)
resultJSON, _ := json.Marshal(result)
system.StartWs()
taskGetEdgeApps() // This task will imediatelly update the entry in the api database.
return string(resultJSON)
}
func taskEnableOnline(args taskEnableOnlineArgs) string { func taskEnableOnline(args taskEnableOnlineArgs) string {
fmt.Println("Executing taskEnableOnline for " + args.ID) fmt.Println("Executing taskEnableOnline for " + args.ID)
@@ -1087,7 +1190,7 @@ func taskGetSystemUptime() string {
func taskGetStorageDevices() string { func taskGetStorageDevices() string {
fmt.Println("Executing taskGetStorageDevices") fmt.Println("Executing taskGetStorageDevices")
devices := storage.GetDevices(diagnostics.GetReleaseVersion()) devices := storage.GetDevices()
devicesJSON, _ := json.Marshal(devices) devicesJSON, _ := json.Marshal(devices)
utils.WriteOption("STORAGE_DEVICES_LIST", string(devicesJSON)) utils.WriteOption("STORAGE_DEVICES_LIST", string(devicesJSON))