From f52281ff1e9d0b5f54e47f4bd5a4b68665ac547a Mon Sep 17 00:00:00 2001 From: Paulo Truta Date: Thu, 17 Jun 2021 13:38:34 +0000 Subject: [PATCH] Added utils.getIP function, set to run as a 60 tick scheduled task --- internal/system/system.go | 29 +++++++++++++++++++++++++++++ internal/tasks/tasks.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/internal/system/system.go b/internal/system/system.go index f8c2610..38e66c8 100644 --- a/internal/system/system.go +++ b/internal/system/system.go @@ -3,6 +3,9 @@ package system import ( "fmt" "strconv" + "strings" + + "github.com/edgebox-iot/edgeboxctl/internal/utils" "github.com/shirou/gopsutil/host" ) @@ -21,3 +24,29 @@ func GetUptimeFormatted() string { minutes := ((uptime - (days * 60 * 60 * 24)) - (hours * 60 * 60)) / 60 return fmt.Sprintf("%d days, %d hours, %d minutes", days, hours, minutes) } + +func GetIP() string { + ip := "" + + // Trying to find a valid IP (For direct connection, not tunneled) + ethResult := utils.ExecAndGetLines("/", "ip", []string{"-o", "-4", "addr", "list", "eth0"}) + for ethResult.Scan() { + adapterRawInfo := strings.Fields(ethResult.Text()) + if ip == "" { + ip = strings.Split(adapterRawInfo[3], "/")[0] + } + } + + // If no IP was found yet, try wlan0 + if ip == "" { + wlanResult := utils.ExecAndGetLines("/", "ip", []string{"-o", "-4", "addr", "list", "wlan0"}) + for wlanResult.Scan() { + adapterRawInfo := strings.Fields(wlanResult.Text()) + if ip == "" { + ip = strings.Split(adapterRawInfo[3], "/")[0] + } + } + } + + return ip +} diff --git a/internal/tasks/tasks.go b/internal/tasks/tasks.go index 235bc83..3d9adb1 100644 --- a/internal/tasks/tasks.go +++ b/internal/tasks/tasks.go @@ -250,6 +250,9 @@ func ExecuteSchedules(tick int) { if tick == 1 { + ip := taskGetSystemIP() + log.Println("System IP is: " + ip) + release := taskSetReleaseVersion() log.Println("Setting api option flag for Edgeboxctl (" + release + " version)") @@ -274,6 +277,11 @@ func ExecuteSchedules(tick int) { } + if tick%60 == 0 { + ip := taskGetSystemIP() + log.Println("System IP is: " + ip) + } + // Just add a schedule here if you need a custom one (every "tick hour", every "tick day", etc...) } @@ -498,3 +506,31 @@ func taskGetStorageDevices() string { return string(devicesJSON) } + +func taskGetSystemIP() string { + fmt.Println("Executing taskGetStorageDevices") + + ip := system.GetIP() + + db, err := sql.Open("sqlite3", utils.GetSQLiteDbConnectionDetails()) + + if err != nil { + log.Fatal(err.Error()) + } + + statement, err := db.Prepare("REPLACE into option (name, value, created, updated) VALUES (?, ?, ?, ?);") // Prepare SQL Statement + if err != nil { + log.Fatal(err.Error()) + } + + formatedDatetime := utils.GetSQLiteFormattedDateTime(time.Now()) + + _, err = statement.Exec("IP_ADDRESS", ip, formatedDatetime, formatedDatetime) // Execute SQL Statement + if err != nil { + log.Fatal(err.Error()) + } + + db.Close() + + return ip +}