package box import ( "beetai_lattepanda/file" "bufio" "bytes" "encoding/json" "fmt" //"github.com/eclipse/paho.mqtt.golang" "io" // "log" "io/ioutil" "net" "net/http" "os" "os/exec" "time" //"path/filepath" "strconv" // convert string to int "strings" ) // go.lintOnSave": "off" // scp -P 2224 -r -o 'ProxyJump dh.duyhai@ssh_tunnel.beetai.com' a.txt admin@localhost:/admin/monitor/1/ var Debug = 0 var Key = "V7kls@&@IP*fl7R" var Setup_stt = false // var last_msg_time = time.Now().UnixNano() / 1000000 var state_read_ecf = false //Khai bao //IP var ip = "" var ip_public = "" var ether = "" //Mem var mem = "" var sum_mem = "" // Cpu var user = 0 var system = 0 var idle = 0 var avg = 0 // Storage var box_stg = "" var sum_storage = "" //Boot_storage var boot_stg = "" var sum_boot_stg = "" //temp var temp = "" //engine var sts_engine = 0 // var pass string = "" // var passwd_str string = "echo -e " + pass + "\n" + pass + "| passwd admin" // id camera var id_cam = "" const SD_CARD_DEFAULT = 0 // Ver_Ubuntu_ : 0 - Server / 1 - Desktop // const VER_UBUNTU_DEFAUT = 0 var name_dir_engine = "" //var path_base = "/home/aibox/monitor" // var path_base = "/home/ubuntu/monitor" // var path_base = "/home/administrator/monitor" var path_base = "/home/svr-bi-security/monitor" var Path_base_engine = path_base + "/engine/" + name_dir_engine //"count_people_face" // Name dir engine var Path_log_engine = path_base + "/log/log_engine" var Path_log_luncher = path_base + "/log/log_launcher" var Path_engine_config = path_base + "/setup/engine.json" // dia chi duoi file Config.txt // var Path_config = Path_base_engine + "/data/Config.txt" var Path_config = Path_base_engine + "/data/config.json" var Path_backup = path_base + "/backup" var Path_upgrade = path_base + "/upgrade" var Path_engine_update = Path_upgrade + "/engine_update.json" var time_run = "5:23:" // Server var Url = "http://api.cms.beetai.com/api/box/getConfig" //"http://www.mocky.io/v2/5cdd0a163000000f25e2343e" //---------------------------------------------------- // Create struct file config engine.json // message : Cho engine.json confix var message Message // messageUpdate : Cho message update engine var messageUpdate Message type Message struct { Error_code int `json:"error_code"` Data Datas `json:"data"` SD_CARD int `json:"sd_card"` } // message.Data.Engines[i].IsConfig // User struct which contains a name // a type and a list of social links type Datas struct { Box_id int `json:"box_id"` // Box_name string `json:"box_name"` Engines []Engine `json:"engines"` } type Engine struct { IsConfig string `json:"isConfig,omitempty"` Active int `json:"active"` Engine_id int `json:"engine_id"` Id int `json:"id"` Link string `json:"link"` Name string `json:"name"` Path string `json:"path"` Version string `json:"version"` //PortStream int `json:"portstream,omitempty"` Time_run string `json:"time_run,omitempty"` } //---------------------------------------------------- // Create struct Message Payload pub MQTT var payload Payload type Payload struct { Box_id int `json:"box_id"` Ip_private string `json:"ip_private"` Ip_public string `json:"ip_public"` Mac_address string `json:"mac_address"` Boot_storage string `json:"boot_storage"` Boot_storage_usage string `json:"boot_storage_usage"` Memory string `json:"memory"` Memory_usage string `json:"memory_usage"` Storage string `json:"storage"` Storage_usage string `json:"storage_usage"` Cpu_usage string `json:"cpu_usage"` Temperature string `json:"temperature"` Engines_pub []Engine_pub `json:"engines_pub"` } type Engine_pub struct { Name string `json:"name"` Status int `json:"status"` Engine_id int `json:"engine_id"` } //==================== FUNCTION ============================== func GetDir() { if file.ReadFile("/admin/ver_sys.txt") == "1" { path_base = "/home/aibox/Documents/monitor" } } func RunCheck() { if Status_Checkengine() == 0 { fmt.Println("Function RunCheck ()") //cmd := "sudo " + path_base + "/check/run_check.sh" //chmod 777 /var/run/screen && // cmd := "sudo " + path_base + "/check/Check_engine >/dev/null 2>&1 &" // cd /home/aibox/monitor/check/&& ./Check_engine >/dev/null 2>&1 & cmd := "cd " + path_base + "/check/&& ./Check_engine >/dev/null 2>&1 &" fmt.Println("CMD run check_engine:" + cmd) _, err := exec.Command("sh", "-c", cmd).Output() if err != nil { file.Write_log("RunCheck () "+err.Error(), Path_log_luncher) fmt.Println("RunCheck() error ") } else { fmt.Println("RunCheck() ok ") file.Write_log("RunCheck() ok ", Path_log_luncher) } } else { //file.Println("===>Check_engine is running<====") } } func Status_Checkengine() int { file.Println("Function Status_Checkengine ()") var stt int = 0 var cmd string = "ps -A | grep Check_engine" out, err := exec.Command("sh", "-c", cmd).Output() if err != nil { //file.Println(err) file.Write_log("Status_Checkengine () "+err.Error(), Path_log_luncher) } if len(out) == 0 { stt = 0 file.Println("====>>>>Check_engine not run\n") file.Write_log("====>>>>Check_engine not run\n", Path_log_luncher) } else { file.Println("===>Check_engine is running<====") file.Println("\n") stt = 1 } return stt } func SetUp() bool { Request_msg(Url) // Request down load engine, tạo engine.json fmt.Println("Request_msg done") LoadConfig(Path_engine_config) // Get thong tin tu file engine.json luu thong so vao struct, add them truong time run //UpdateDirEngine() fmt.Println("LoadConfig done") fmt.Println(message.Error_code) if message.Error_code == 10000 { Dowload_engine() // Down load cac engine duoc respon tu server tra ve UpdateConfig(Path_engine_config) // Cap nhat thong tin name engine cho engine.json file.Println("Dowload_engine done") file.Println("Replace_id done") //Set_autorun() // Thiet lap engine auto run sau khi reset(Set up thong so Url, do phan giai, ) file.Write_log("AIBOX Reset\n", Path_log_luncher) Setup_stt = true } else { Setup_stt = false file.DeleteFile(Path_engine_config) } return Setup_stt } func Set_autorun() { _, err := exec.Command("sh", "-c", "sed -i -e '$i \\sudo "+path_base+"/run_cms.sh > dev/null 2>&1 &\n' /etc/rc.local").Output() if err != nil { file.Println("Error Set Auto run CMS Local") } else { file.Println("Done Set Auto run CMS Local") } // For Check_engine _, err_1 := exec.Command("sh", "-c", "sed -i -e '$i \\screen -dm -S Check_engine sudo "+path_base+"/Check_engine >/dev/null 2>&1 &\n' /etc/rc.local").Output() if err_1 != nil { file.Println("Error Set Auto run Check_engine") } else { file.Println("Done Set Auto run Check_engine") } } func GetIndex(message Message, value string) int { var k = -1 for i := 0; i < len(message.Data.Engines); i++ { if message.Data.Engines[i].Name == value { k = i } } return k } func DowloadEngineUpdate(name string, link string, version string, id int) { file.Println("Name: " + name) file.Println("Version: " + version) file.Println("Link: " + link) var index = GetIndex(message, name) if index != -1 { if link != "" { var cmd_link string = "wget -O " + "" + path_base + "/engine/" + name + ".tar.gz " + link file.Println(cmd_link) _, err := exec.Command("sh", "-c", cmd_link).Output() if err != nil { file.Println("Dowload_engine: " + name + ":" + version + "Faild.!") file.Println("-------------------------------") } } //var list = strings.Split(message.Data.Engines[i].Link, "/") //var name_engine = list[len(list)-1] var cmd = "tar zxvf " + "" + path_base + "/engine/" + name + ".tar.gz " + " --one-top-level=" + path_base + "/engine/" + name + "_" + strconv.Itoa(id) file.Println(cmd) _, err := exec.Command("sh", "-c", cmd).Output() if err != nil { file.Println("Giai nen Error") file.Println("-------------------------------") } else { file.Println("Giai nen thanh cong") file.Println("-------------------------------") } var cmd1 = "mv " + "" + path_base + "/engine/" + name + "_" + strconv.Itoa(id) + "/build/" + name + " " + path_base + "/engine/" + name + "_" + strconv.Itoa(id) + "/build/" + name + "_" + strconv.Itoa(id) file.Println(cmd1) _, err1 := exec.Command("sh", "-c", cmd1).Output() if err1 != nil { file.Println("Loi doi ten thu muc con ") file.Println("-------------------------------") } else { file.Println("Doi ten thu muc con thanh cong") file.Println("-------------------------------") } var cmd2 = "mv " + "" + path_base + "/engine/" + name + "_" + strconv.Itoa(id) + "/build/" + name + "_" + strconv.Itoa(id) + "/" + name + " " + path_base + "/engine/" + name + "_" + strconv.Itoa(id) + "/build/" + name + "_" + strconv.Itoa(id) + "/" + name + "_" + strconv.Itoa(id) file.Println(cmd2) _, err2 := exec.Command("sh", "-c", cmd2).Output() if err2 != nil { file.Println("Loi doi ten engine ") file.Println("-------------------------------") } else { file.Println("Doi ten engine thanh cong") file.Println("-------------------------------") } // Remove file nen _, err_1 := exec.Command("sh", "-c", "rm "+path_base+"/engine/*.tar.gz").Output() if err_1 != nil { file.Println("Error Clear file .tar.gz ") } else { file.Println("Done Clear file .tar.gz") } // Update path engine and replace id_cam on file config file.Println("Update path engine and replace id_cam on file config") message.Data.Engines[index].Name = name + "_" + strconv.Itoa(id) message.Data.Engines[index].Path = "" + path_base + "/engine/" + message.Data.Engines[index].Name file.Println(message.Data.Engines[index].Name) file.Println(message.Data.Engines[index].Path) var id_val = strconv.Itoa(message.Data.Engines[index].Id) var path_val = message.Data.Engines[index].Path + "/data/Config.txt" fmt.Println("ID new: ", id_val) fmt.Println("Path config:", path_val) Replace_id(path_val, id_val) // Cap nhap ID BOX cho file config.txt trong engine // Do cap nhat chua biet port dang nao la bao nhieu len ko set dc //ChangePort(path_val, port) // Change portstream local cho cac engine thanh khac nhau file.Println("---------------------------------------------------") } } // End for array engine func Dowload_engine() { file.Println("Function Dowload_engine") for i := 0; i < len(message.Data.Engines); i++ { file.Println("Name: " + message.Data.Engines[i].Name) file.Println("Version: " + message.Data.Engines[i].Version) file.Println("Link: " + message.Data.Engines[i].Link) if message.Data.Engines[i].Link != "" { var link string = "wget -O " + "" + path_base + "/engine/" + message.Data.Engines[i].Name + ".tar.gz " + message.Data.Engines[i].Link file.Println(link) _, err := exec.Command("sh", "-c", link).Output() if err != nil { file.Println("Dowload_engine: " + message.Data.Engines[i].Name + ":" + message.Data.Engines[i].Version + "Faild.!") file.Println("-------------------------------") } } //var list = strings.Split(message.Data.Engines[i].Link, "/") //var name_engine = list[len(list)-1] var cmd = "tar zxvf " + "" + path_base + "/engine/" + message.Data.Engines[i].Name + ".tar.gz " + " --one-top-level=" + path_base + "/engine/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) file.Println(cmd) _, err := exec.Command("sh", "-c", cmd).Output() if err != nil { file.Println("Giai nen Error") file.Println("-------------------------------") } else { file.Println("Giai nen thanh cong") file.Println("-------------------------------") } var cmd1 = "mv " + "" + path_base + "/engine/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + "/build/" + message.Data.Engines[i].Name + " " + path_base + "/engine/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + "/build/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) file.Println(cmd1) _, err1 := exec.Command("sh", "-c", cmd1).Output() if err1 != nil { file.Println("Loi doi ten thu muc con ") file.Println("-------------------------------") } else { file.Println("Doi ten thu muc con thanh cong") file.Println("-------------------------------") } var cmd2 = "mv " + "" + path_base + "/engine/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + "/build/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + "/" + message.Data.Engines[i].Name + " " + path_base + "/engine/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + "/build/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) + "/" + message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) file.Println(cmd2) _, err2 := exec.Command("sh", "-c", cmd2).Output() if err2 != nil { file.Println("Loi doi ten engine ") file.Println("-------------------------------") } else { file.Println("Doi ten engine thanh cong") file.Println("-------------------------------") } // Remove file nen _, err_1 := exec.Command("sh", "-c", "rm "+path_base+"/engine/*.tar.gz").Output() if err_1 != nil { file.Println("Error Clear file .tar.gz ") } else { file.Println("Done Clear file .tar.gz") } // Update path engine and replace id_cam on file config file.Println("Update path engine and replace id_cam on file config") message.Data.Engines[i].Name = message.Data.Engines[i].Name + "_" + strconv.Itoa(message.Data.Engines[i].Id) message.Data.Engines[i].Path = "" + path_base + "/engine/" + message.Data.Engines[i].Name file.Println(message.Data.Engines[i].Name) file.Println(message.Data.Engines[i].Path) var id_val = strconv.Itoa(message.Data.Engines[i].Id) var path_val = message.Data.Engines[i].Path + "/data/Config.txt" fmt.Println("ID new: ", id_val) fmt.Println("Path config:", path_val) Replace_id(path_val, id_val) // Cap nhap ID BOX cho file config.txt trong engine // message.Data.Engines[i].PortStream = ChangePort(path_val, i) fmt.Println(ChangePort(path_val, i)) // Change portstream local cho cac engine thanh khac nhau file.Println("---------------------------------------------------") } // End for array engine1612 // Cap nhat name engine trong file engine.json } func FormRequest(Url string) string { // var ip_s string = "" // var ip_ps string = "" var mac_s string = "" var respon_msg string = "" file.Create_file(Path_engine_config) GetOutboundIP() mac_s = Get_mac() //mac_s = "c4:2a:fe:37:35:11" // `{" private_key": "V7kls@&@IP*fl7R", "mac_address":"c4:6e:00:02:cb:14 "}` var msg string = "{" + "\"private_key\":" + "\"" + Key + "\"" + "," + "\"mac_address\":" + "\"" + mac_s + "\"" + "}" if Debug == 1 { fmt.Printf("Payload = %v\n\n", msg) } payload := []byte(msg) resp, err := http.Post(Url, "application/json", bytes.NewBuffer(payload)) if err != nil { file.Write_log("Request_msg() Faild", Path_log_luncher) //file.Println("Request_msg() Faild") } else { defer resp.Body.Close() } body, err := ioutil.ReadAll(resp.Body) if err != nil { file.Write_log("ioutil.ReadAll(resp.Body) Faild", Path_log_luncher) //file.Println("ioutil.ReadAll(resp.Body) Faild") } respon_msg = string(body) return respon_msg } func RequestUpdate(Url string) { var respon_msg = FormRequest(Url) file.Println(respon_msg) json.Unmarshal([]byte(respon_msg), &messageUpdate) for i := 0; i < len(messageUpdate.Data.Engines); i++ { messageUpdate.Data.Engines[i].Time_run = time_run messageUpdate.Data.Engines[i].IsConfig = "0" } //fmt.Println("<<<<-------------------- messageUpdate --------------------->>>>") //fmt.Println(messageUpdate) //fmt.Println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++") //fmt.Println(message) //fmt.Println("<<<<-------------------- END messageUpdate --------------------->>>>") // Tao maang so sanh engine config cu voi engine config moi arrcompare := make([]int, len(message.Data.Engines)) for i := 0; i < len(messageUpdate.Data.Engines); i++ { var k = 0 for j := 0; j < len(message.Data.Engines); j++ { if message.Data.Engines[j].Name == messageUpdate.Data.Engines[i].Name+"_"+strconv.Itoa(messageUpdate.Data.Engines[i].Id) { if message.Data.Engines[j].Version != messageUpdate.Data.Engines[i].Version { // Backup file config.txt vao thu muc backup file.CoppyFile(message.Data.Engines[j].Path+"/data/Config.txt", message.Data.Engines[j].Id) // Delete foder engine old file.DeleteForder(message.Data.Engines[j].Path) message.Data.Engines[j] = messageUpdate.Data.Engines[i] DowloadEngineUpdate(messageUpdate.Data.Engines[i].Name, messageUpdate.Data.Engines[i].Link, messageUpdate.Data.Engines[i].Version, messageUpdate.Data.Engines[i].Id) arrcompare[j] = 2 + arrcompare[j] } else { message.Data.Engines[i].Active = messageUpdate.Data.Engines[j].Active message.Data.Engines[i].IsConfig = "1" arrcompare[j] = 1 + arrcompare[j] } } else { arrcompare[j] = 0 + arrcompare[j] k = k + 1 } } if k == len(message.Data.Engines) { messageUpdate.Data.Engines[i].Time_run = time_run messageUpdate.Data.Engines[i].IsConfig = "0" message.Data.Engines = append(message.Data.Engines, messageUpdate.Data.Engines[i]) //DowloadEngineUpdate(name string, link string, version string, id int) DowloadEngineUpdate(messageUpdate.Data.Engines[i].Name, messageUpdate.Data.Engines[i].Link, messageUpdate.Data.Engines[i].Version, messageUpdate.Data.Engines[i].Id) } } for i := 0; i < len(arrcompare); i++ { if arrcompare[i] == 0 { message.Data.Engines[i].Name = "null" } } for { var ss = false for i, _ := range message.Data.Engines { if message.Data.Engines[i].Name == "null" { //fmt.Println("--------------------- Delete file --------------------") file.DeleteForder(message.Data.Engines[i].Path) //fmt.Println("--------------------- ++++++++++++++ --------------------") message.Data.Engines = RemoveIndex(message.Data.Engines, i) ss = true } } if ss == false { break } } UpdateConfig(Path_engine_config) } func RemoveIndex(s []Engine, index int) []Engine { return append(s[:index], s[index+1:]...) } func Request_msg(Url string) { var respon_msg = FormRequest(Url) file.Println(respon_msg) file.Write_file(respon_msg, Path_engine_config) } func UpdateConfig(path string) { //fmt.Println("---------------------------------- Function Update Config ---------------------------") //fmt.Println(message) e, err := json.Marshal(message) if err != nil { if Debug == 1 { fmt.Println(err) } } file.Println(string(e)) err = ioutil.WriteFile(path, []byte(string(e)), 0) if err != nil { //panic(err) } //file.Printf("Message: \n", message) file.Println("\nError_code: " + strconv.Itoa(message.Error_code)) file.Println("Box_id: " + strconv.Itoa(message.Data.Box_id)) // file.Println("---------------------------------------------") // List engine for i := 0; i < len(message.Data.Engines); i++ { file.Println("IsConfig: " + message.Data.Engines[i].IsConfig) file.Println("Active: " + strconv.Itoa(message.Data.Engines[i].Active)) file.Println("Engine_id: " + strconv.Itoa(message.Data.Engines[i].Engine_id)) file.Println("Id: " + strconv.Itoa(message.Data.Engines[i].Id)) file.Println("Link: " + message.Data.Engines[i].Link) file.Println("Name: " + message.Data.Engines[i].Name) file.Println("Path: " + message.Data.Engines[i].Path) file.Println("Version: " + message.Data.Engines[i].Version) file.Println("Time_run: " + message.Data.Engines[i].Time_run) file.Println("---------------------------------------------") } state_read_ecf = true } func LoadConfig(path string) { //fmt.Println("---------------------------------- Function Load Config 123 ---------------------------") //fmt.Println(message) // Open our jsonFile jsonFile, err := os.Open(path) // if we os.Open returns an error then handle it if err != nil { file.Write_log("LoadConfig Faild", Path_log_luncher) //file.Println(err) } file.Println("Successfully Opened engine.json") file.Println("\n") defer jsonFile.Close() byteValue, _ := ioutil.ReadAll(jsonFile) json.Unmarshal(byteValue, &message) for i := 0; i < len(message.Data.Engines); i++ { message.Data.Engines[i].Time_run = time_run message.Data.Engines[i].IsConfig = "0" } message.SD_CARD = SD_CARD_DEFAULT //fmt.Println(message) //payload.Engines_pub = make([]Engine_pub, len(message.Data.Engines)) // Convert Struct to Json e, err := json.Marshal(message) if err != nil { if Debug == 1 { fmt.Println(err) } } //file.Println(string(e)) err = ioutil.WriteFile(path, []byte(string(e)), 0) if err != nil { //panic(err) } //file.Printf("Message: \n", message) file.Println("\nError_code: " + strconv.Itoa(message.Error_code)) file.Println("Box_id: " + strconv.Itoa(message.Data.Box_id)) // file.Println("---------------------------------------------") // List engine for i := 0; i < len(message.Data.Engines); i++ { file.Println("IsConfig: " + message.Data.Engines[i].IsConfig) file.Println("Active: " + strconv.Itoa(message.Data.Engines[i].Active)) file.Println("Engine_id: " + strconv.Itoa(message.Data.Engines[i].Engine_id)) file.Println("Id: " + strconv.Itoa(message.Data.Engines[i].Id)) file.Println("Link: " + message.Data.Engines[i].Link) file.Println("Name: " + message.Data.Engines[i].Name) file.Println("Path: " + message.Data.Engines[i].Path) file.Println("Version: " + message.Data.Engines[i].Version) file.Println("Time_run: " + message.Data.Engines[i].Time_run) file.Println("---------------------------------------------") } payload.Engines_pub = make([]Engine_pub, len(message.Data.Engines)) state_read_ecf = true // if Debug == 2 { // file.Println(file.ReadFile(Path_engine_config)) // } } func Get_version() string { return message.Data.Engines[0].Version } // func UpdateDirEngine() { // if state_read_ecf == true { // name_dir_engine = strings.Replace(message.Data.Engines[0].Path, ".zip", "", -1) // if Debug == 1 { // file.Printf("Name_dir_engine :" + name_dir_engine + "\t") // } // Path_base_engine = path_base + "/engine/" + name_dir_engine // Path_config = Path_base_engine + "/data/Config.txt" // //file.Println("Path_base_engine :" + Path_base_engine) // } // } func Read_engine_config(path string) { //fmt.Println("---------------------------------- Read_engine_config ---------------------------") //fmt.Println(message) //.Println("<--------------------------------------------------------------->") // Open our jsonFile jsonFile, err := os.Open(path) // if we os.Open returns an error then handle it if err != nil { //file.Println(err) } file.Println("Successfully Opened engine.json") file.Println("\n") defer jsonFile.Close() byteValue, _ := ioutil.ReadAll(jsonFile) json.Unmarshal(byteValue, &message) payload.Engines_pub = make([]Engine_pub, len(message.Data.Engines)) state_read_ecf = true file.Println("\nError_code: " + strconv.Itoa(message.Error_code)) file.Println("Box_id: " + strconv.Itoa(message.Data.Box_id)) // file.Println("---------------------------------------------") // List engine for i := 0; i < len(message.Data.Engines); i++ { file.Println("IsConfig: " + message.Data.Engines[i].IsConfig) file.Println("Active: " + strconv.Itoa(message.Data.Engines[i].Active)) file.Println("Engine_id: " + strconv.Itoa(message.Data.Engines[i].Engine_id)) file.Println("Id: " + strconv.Itoa(message.Data.Engines[i].Id)) file.Println("Link: " + message.Data.Engines[i].Link) file.Println("Name: " + message.Data.Engines[i].Name) file.Println("Path: " + message.Data.Engines[i].Path) file.Println("Version: " + message.Data.Engines[i].Version) file.Println("Time_run: " + message.Data.Engines[i].Time_run) file.Println("---------------------------------------------") } //fmt.Println(message) //fmt.Println("<--------------------------------------------------------------->") } func Check_dir(path string) int { var file1, err = os.OpenFile(path, os.O_RDWR, 0644) if err != nil { file.Println("Open file error") } else { defer file1.Close() } // if Debug == 1 { // file.Printf("Kieu file:%T", file) // file.Printf("value file:%v", file) // } if file1 != nil { //dir_status = 1 file.Println(" FILE EXITS") return 1 } else { file.Println(" FILE NOT EXITS") return 0 } //return dir_status } // func Update_id() { // for i := 0; i < len(message.Data.Engines); i++ { // x := GetIDEngine(Path_config) // if Debug == 1 { // file.Printf("Engine id: %v\t", x) // } // message.Data.Engines[i].Id, _ = strconv.Atoi(x) // //file.Printf("message.Data.Engines[i].Id =%v\n ", message.Data.Engines[i].Id) // } // e, err := json.Marshal(message) // if err != nil { // file.Write_log("json.Marshal(message) of func Update_id Error", Path_log_luncher) // //file.Println(err) // } // //file.Println(string(e)) // err = ioutil.WriteFile(Path_engine_config, []byte(string(e)), 0) // if err != nil { // //panic(err) // if Debug == 1 { // file.Println(err) // } // } // } //ChangePort () : Thay the port stream local vào file Config.txt func ChangePort(path string, k int) int { file.Println("Function ChangePort") file.Println("Path : " + path) var p_n = 0 var msg string = "" var file_r, err = os.OpenFile(path, os.O_RDWR, 0644) if err != nil { file.Println(" Open file error") } else { stat, err := file_r.Stat() if err != nil { if Debug == 1 { fmt.Println(err) } } if Debug == 1 { //file.Printf("Kieu stat.Size : %T \n", stat.Size()) fmt.Println(stat.Size()) } // read file, line by line var text = make([]byte, stat.Size()) for { _, err = file_r.Read(text) // break if finally arrived at end of file if err == io.EOF { break } // break if error occured if err != nil && err != io.EOF { //file.IsError(err) break } } msg = string(text) } defer file_r.Close() i := strings.Index(msg, "portstream:") //file.Println("Index: ", i) if i > -1 { index := msg[i+11:] //fmt.Println() //fmt.Println(msg[i+7:]) list := strings.Split(index, "\n") file.Println(list[0]) //fmt.Println(list[0]) //fmt.Println() var p = list[0] if Debug == 1 { fmt.Println("Port old: ", p) } // Replace var c, _ = strconv.Atoi(p) p_n = c + k fmt.Println("Port new:" + strconv.Itoa(p_n)) newConfig := strings.Replace(msg, "portstream:"+p, "portstream:"+strconv.Itoa(p_n), -1) err = ioutil.WriteFile(path, []byte(newConfig), 0) if err != nil { //panic(err) } } else { file.Write_log("Port not found", Path_log_luncher) //file.Println("cam_id not found") } return p_n } //Replace_id () : Thay the id engine vào file config func Replace_id(path string, id_box string) { file.Println("Function Replace_id") file.Println("Path : " + path) file.Println("Id_box: " + id_box) var msg string = "" var file_r, err = os.OpenFile(path, os.O_RDWR, 0644) if err != nil { file.Println(" Open file error") } else { stat, err := file_r.Stat() if err != nil { if Debug == 1 { fmt.Println(err) } } if Debug == 1 { //file.Printf("Kieu stat.Size : %T \n", stat.Size()) fmt.Println(stat.Size()) } // read file, line by line var text = make([]byte, stat.Size()) for { _, err = file_r.Read(text) // break if finally arrived at end of file if err == io.EOF { break } // break if error occured if err != nil && err != io.EOF { //file.IsError(err) break } } msg = string(text) } defer file_r.Close() i := strings.Index(msg, "cam_id:") //file.Println("Index: ", i) if i > -1 { index := msg[i+7:] //fmt.Println() //fmt.Println(msg[i+7:]) list := strings.Split(index, "\n") file.Println(list[0]) //fmt.Println(list[0]) //fmt.Println() var id = list[0] if Debug == 1 { fmt.Println("id_cam old: ", id) } // Replace newConfig := strings.Replace(msg, "cam_id:"+id, "cam_id:"+id_box, -1) err = ioutil.WriteFile(path, []byte(newConfig), 0) if err != nil { //panic(err) } } else { file.Write_log("cam_id not found", Path_log_luncher) //file.Println("cam_id not found") } } // List function func GetIDEngine(path string) string { var id string = "" str := file.ReadFile(path) i := strings.Index(str, "cam_id:") //file.Println("Index: ", i) if i > -1 { index := str[i+7:] list := strings.Split(index, "\n") file.Println(list[0]) id = list[0] } else { file.Write_log("cam_id not found", Path_log_luncher) //file.Println("cam_id not found") } return id } func Update_firmware() { file.Println("Update_firmware V1.0\n") } func Ssh_open(port string) { //autossh -M 0 -f -N -R 2235:localhost:22 boxai@ssh_tunnel.beetai.com //_, err := exec.Command("sh", "-c", "sudo "+path_base+"/ssh/open_ssh.sh").Output() var cmd = "autossh -M 0 -f -N -R " + port + ":localhost:22 boxai@ssh_tunnel.beetai.com > /dev/null 2>&1 &" file.Write_log("Cmd openssh :"+cmd+" \n", Path_log_luncher) fmt.Println("Command ssh:", cmd) _, err := exec.Command("sh", "-c", cmd).Output() if err != nil { //log.Fatal(err) file.Write_log("ssh_open() Error", Path_log_luncher) } } func Cmd_Box(cmd string) string { out, err := exec.Command("sh", "-c", cmd).Output() if err != nil { //log.Fatal(err) file.Write_log("ssh_open() Error", Path_log_luncher) } file.Write_log("CMD from Server:"+cmd, Path_log_luncher) if Debug == 1 { fmt.Println(out) } return string(out) } func Ssh_close() { //_, err := exec.Command("sh", "-c", "kill $(pgrep sshd)").Output() file.Write_log("Cmd close :kill $(pgrep autossh)\n", Path_log_luncher) _, err := exec.Command("sh", "-c", "kill $(pgrep autossh)").Output() if err != nil { //log.Fatal(err) file.Write_log("kill_ssh() Error", Path_log_luncher) } } func Stop_check_engine() { file.Println("Stop Check_engine") file.Write_log("Stop Check_engine \n", Path_log_luncher) file.Println("Stop_check_engine()\n") _, err := exec.Command("sh", "-c", "kill $(pgrep Check_engine)").Output() if err != nil { //log.Fatal(err) } file.Println("Stop engine") file.Write_log("Stop Engine \n", Path_log_luncher) } func Stop_engine() { for i := 0; i < len(message.Data.Engines); i++ { //var cmd string = "ps -A | grep " + message.Data.Engines[i].Name var cmd string = "sudo kill -9 $(pidof " + message.Data.Engines[i].Name + ")" out2, err := exec.Command("sh", "-c", cmd).Output() if err != nil { //file.Println(err) file.Write_log("Stop_engine()"+err.Error(), Path_log_luncher) } if len(out2) != 0 { // sudo kill $(pgrep FaceRecognition) var cmd string = "sudo kill $(pgrep " + message.Data.Engines[i].Name + ")" //file.Println("CMD Kill_engine:" + cmd) _, err := exec.Command("sh", "-c", cmd).Output() // kill $(pgrep FaceRecognition) //log.Fatal(err) if err != nil { file.Write_log("sudo kill engine of Stop engine() Error \n", Path_log_luncher) //file.Println("sudo kill engine of Stop engine() Error") } } else { file.Println("Engine kill") } out1, _ := exec.Command("sh", "-c", "ps -A | grep loop_run").Output() if len(out1) != 0 { _, err := exec.Command("sh", "-c", " sudo kill $(pgrep loop_run)").Output() if err != nil { file.Write_log("sudo kill $(pgrep loop_run) of Check Stop engine() \n", Path_log_luncher) } //log.Fatal(err) } else { file.Println("loop_run kill") } } } func Status_engine() { file.Println("Function Status_engine") //fmt.Println(message) //payload.Engines_pub = make([]Engine_pub, len(message.Data.Engines)]) for i := 0; i < len(message.Data.Engines); i++ { if message.Data.Engines[i].Active == 1 { payload.Engines_pub[i].Name = message.Data.Engines[i].Name payload.Engines_pub[i].Engine_id = message.Data.Engines[i].Engine_id //var cmd string = "ps -A | grep " + message.Data.Engines[i].Name var cmd string = "pidof " + message.Data.Engines[i].Name file.Println("Check status engine :" + cmd) file.Println(cmd) out, err := exec.Command("sh", "-c", cmd).Output() if err != nil { fmt.Println(err) } if len(out) == 0 { sts_engine = 0 payload.Engines_pub[i].Status = 0 file.Println("Engine Running") } else { sts_engine = 1 payload.Engines_pub[i].Status = 1 file.Println("Engine Stop") } } } } func Tranfer_engine() { file.Println("Tranfer_engine()\n") file.Write_log("Tranfer_engine()\n", Path_log_luncher) file.Check_path(Path_backup) // Xoa file engine cu trong backup _, err0 := exec.Command("sh", "-c", "cd "+path_base+"/backup/").Output() if err0 == nil { _, err1 := exec.Command("sh", "-c", "rm -rf "+path_base+"/backup/").Output() if err1 != nil { file.Write_log("Loi Xoa file engine cu trong backup \n", Path_log_luncher) //file.Printf("Loi Xoa file engine cu trong backup \n") } } _, err2 := exec.Command("sh", "-c", "mv "+path_base+"/face_recognition/ "+path_base+"/backup/").Output() if err2 != nil { //log.Fatal(err2) file.Println("Move mv " + path_base + "/face_recognition/ " + path_base + "/backup/ error\n") } // file.Printf("Done copy\n") } func Backup_engine() { file.Println("Backup_engine()\n") _, err := exec.Command("sh", "-c", "rm -rf "+path_base+"/face_recognition/").Output() if err != nil { //log.Fatal(err) } else { _, err1 := exec.Command("sh", "-c", "mv "+path_base+"/backup/face_recognition/ "+path_base+"/").Output() if err1 != nil { //log.Fatal(err1) } else { _, err2 := exec.Command("sh", "-c", "sudo chmod +x "+path_base+"/face_recognition/build/FaceRecognition/FaceRecognition").Output() if err2 != nil { //log.Fatal(err2) } else { //Start_engine() } } } //file.Printf("Done Backup_engine \n") } //------------------------------------------------------------------------------ func Set_passwd(pwd string) { passwd_str := "echo -e " + pwd + `"\n"` + pwd + " | passwd admin" file.Println(passwd_str) _, err := exec.Command("sh", "-c", passwd_str).Output() if err != nil { if Debug == 1 { fmt.Printf("Error:%v\n", err) } } else { file.Println("Changed password") } } func FloatToString(input_num float64) string { // to convert a float number to a string return strconv.FormatFloat(input_num, 'f', 3, 64) } func Get_idBox() string { if state_read_ecf == false { Read_engine_config(Path_engine_config) // UpdateDirEngine() //Update_id() state_read_ecf = true } return (strconv.Itoa(message.Data.Box_id)) } func Get_id() string { if state_read_ecf == false { Read_engine_config(Path_engine_config) // UpdateDirEngine() //Update_id() state_read_ecf = true } var id_aibox string = "" str := file.ReadFile(Path_config) i := strings.Index(str, "cam_id:") //file.Println("Index: ", i) if i > -1 { index := str[i+7:] list := strings.Split(index, "\n") //file.Println(list[0]) id_aibox = list[0] } else { file.Println("cam_id not found") } return id_aibox } func Message_pub() string { file.Println("Message_pub()") Read_engine_config(Path_engine_config) //LoadConfig(Path_engine_config) // if state_read_ecf == false { // Read_engine_config(Path_engine_config) // } file.Println("**************1***************") //id_cam = Get_id() payload.Box_id = message.Data.Box_id file.Println("Box_id:" + strconv.Itoa(payload.Box_id)) file.Println("**************2***************") //GetOutboundIP() payload.Ip_private, _ = GetOutboundIP() file.Println("Ip_private:" + payload.Ip_private) file.Println("**************3***************") //ip_public = Get_ip_public() payload.Ip_public = Get_ip_public() file.Println("Ip_public" + payload.Ip_public) file.Println("**************4***************") //temp = Get_temp() //payload.Temperature = Get_temp() payload.Temperature = "50" file.Println("Temperature:" + payload.Temperature) file.Println("***************5**************") //sum_mem, mem = Get_Mem() payload.Memory, payload.Memory_usage = Get_Mem() file.Println("Memory_usage:" + payload.Memory_usage) file.Println("Memory:" + payload.Memory) file.Println("****************6*************") //ether = Get_mac() payload.Mac_address = Get_mac() file.Println("Mac_address:" + payload.Mac_address) file.Println("*****************7************") //Get_cpu() payload.Cpu_usage = Get_cpu() file.Println("Cpu_usage:" + payload.Cpu_usage) file.Println("*****************8************") Status_engine() file.Println("*****************9************") if message.SD_CARD == 1 { //Get_storage(message.SD_CARD) //Get_boot_stg() //Get_storage(message.SD_CARD) payload.Storage, payload.Storage_usage = Get_storage(message.SD_CARD) file.Println("Storage:" + payload.Storage) file.Println("Storage_usage:" + payload.Storage_usage) file.Println("*****************10************") payload.Boot_storage, payload.Boot_storage_usage = Get_boot_stg() file.Println("Boot_storage:" + payload.Boot_storage) file.Println("Boot_storage_usage:" + payload.Boot_storage_usage) file.Println("*****************11************") } else { //Get_storage(message.SD_CARD) payload.Storage, payload.Storage_usage = Get_storage(message.SD_CARD) file.Println("Storage:" + payload.Storage) file.Println("Storage_usage:" + payload.Storage_usage) file.Println("*****************10************") } if strconv.Itoa(payload.Box_id) == "" { payload.Box_id = 0 file.Write_log("=============>>Get Id_BOX Emty<<============", Path_log_engine) file.Println("=============>>Get Id_BOX Emty<<============") } if Debug == 1 { fmt.Print("Payload: ") fmt.Println(payload) } msg, err := json.Marshal(payload) if err != nil { if Debug == 1 { fmt.Println(err) } } //var msg string = "{" + "\"ip_private\":" + "\"" + ip + "\"" + "," + "\"box_id\":" + "\"" + id_cam + "\"" + "," + "\"engine_status\":" + "\"" + strconv.Itoa(sts_engine) + "\"" + "," + "\"temperature\":" + "\"" + temp + "\"" + "," + "\"ip_public\":" + "\"" + ip_public + "\"" + "," + "\"mac_address\":" + "\"" + ether + "\"" + "," + "\"boot_storage\":" + "\"" + sum_boot_stg + "\"" + "," + "\"boot_storage_usage\":" + "\"" + boot_stg + "\"" + "," + "\"memory\":" + "\"" + sum_mem + "\"" + "," + "\"memory_usage\":" + "\"" + mem + "\"" + "," + "\"cpu_usage\":" + "\"" + strconv.Itoa(avg) + "\"" + "," + "\"storage_usage\":" + "\"" + box_stg + "\"" + "," + "\"storage\":" + "\"" + sum_storage + "\"" + "}" return string(msg) } func GetOutboundIP() (string, net.IP) { var ip string conn, err := net.Dial("udp", "8.8.8.8:80") if err != nil { //log.Fatal(err) file.Write_log("GetOutboundIP() Error ", Path_log_luncher) } defer conn.Close() localAddr := conn.LocalAddr().(*net.UDPAddr) ip = localAddr.IP.String() ip = strings.Replace(ip, "\n", "", -1) //file.Printf(ip) return ip, localAddr.IP } //get Memory func Get_ip_public() string { var value string = "" _, err_0 := exec.Command("ping", "opendns.com", "-c 5", "-i 0.2", "-w 5").Output() if err_0 != nil { file.Println("Not network internet") fmt.Println("Not network internet") } else { out, err := exec.Command("sh", "-c", "dig +short myip.opendns.com @resolver1.opendns.com").Output() if err != nil { //log.Fatal(err) file.Write_log(" Get_ip_public() Error", Path_log_luncher) } value = string(out) value = strings.Replace(value, "\n", "", -1) } return value //file.Printf(ip_public) } func Get_temp() string { var value string = "" out, err := exec.Command("sh", "-c", "cat /sys/devices/virtual/thermal/thermal_zone0/temp").Output() if err != nil { //log.Fatal(err) file.Write_log("Get_temp() Error", Path_log_luncher) } var out1 = string(out) var list = strings.Split(out1, " ") str := strings.Split(list[0], "\n") x, _ := strconv.Atoi(str[0]) t := int(x) / 1000 value = strconv.Itoa(t) //file.Printf("TEMPRATURE : %T \t %v \n",temp,temp) return value } func Reboot_box() { file.Println("Function Reboot_box()") _, err := exec.Command("sh", "-c", "reboot").Output() if err == nil { file.Write_log("Reboot_box()", Path_log_luncher) } if Debug == 1 { file.Println("End Function Reboot_box()") } } func Get_Mem() (string, string) { // (sum_mem,mem %) file.Println("Function Get_Mem() ") memory, err := Get() if err != nil { if Debug == 1 { fmt.Fprintf(os.Stderr, "%s\n", err) } } var total float64 = memory.Total var used float64 = memory.Used sum := strconv.Itoa(int(total)) //sum_mem = FloatToString(total / 1024 / 1024) // MB ram := (used / total) * 100 if ram < 0 { if Debug == 1 { file.Println("Ram < 0") } Reboot_box() } per := strconv.Itoa(int(ram)) //mem = FloatToString(ram) //FloatToString file.Println("Mem total: " + sum) file.Println("Percent Mem: " + per) return sum, per } // Get storage func Get_storage(sd_card int) (string, string) { var out1 string = "" if sd_card == 1 { out, err := exec.Command("sh", "-c", " df |grep /dev/mmcblk1p2").Output() if err != nil { //file.Write_log("get_storage() Error", Path_log_luncher) } out1 = string(out) } else { out, err := exec.Command("sh", "-c", " df |grep /dev/data").Output() if err != nil { //log.Fatal(err) //file.Write_log("get_storage() Error", Path_log_luncher) } out1 = string(out) } var stg = strings.Split(out1, " ") var stg_arr [5]string var k int = 0 for i := 0; i < len(stg); i++ { if stg[i] != "" { stg_arr[k] = stg[i] if Debug == 1 { fmt.Printf("%v_%v_%v\n", i, stg[i], k) } // k = k + 1 } if k == 5 { break } } //sum_storage = stg_arr[1] sum := stg_arr[1] var per = strings.Replace(stg_arr[4], "%", "", -1) //box_stg = per if Debug == 1 { fmt.Printf("\n box_stg : %v ", sum) fmt.Printf("\n sum_storage : %v\n ", per) } return sum, per } // func Get_storage(sd_card int) { // var out1 string = "" // if sd_card == 1 { // out, err := exec.Command("sh", "-c", " df |grep /dev/mmcblk1p2").Output() // if err != nil { // file.Write_log("get_storage() Error", Path_log_luncher) // } // out1 = string(out) // } else { // out, err := exec.Command("sh", "-c", " df |grep /dev/data").Output() // if err != nil { // //log.Fatal(err) // file.Write_log("get_storage() Error", Path_log_luncher) // } // out1 = string(out) // } // var stg = strings.Split(out1, " ") // if Debug == 1 { // file.Printf("Get_storage Function\n") // file.Printf("Storage : %v\n", stg) // for i := 0; i < len(stg); i++ { // file.Print(i) // file.Print("_") // file.Println(stg[i]) // } // } // if sd_card == 1 { // sum_storage = string(stg[2]) // file.Printf("sum_storage = %v\n", sum_storage) // conv, _ := strconv.Atoi(string(stg[2])) // file.Printf("conv = %v\n", conv) // if conv == 0 { // sum_storage = string(stg[3]) // var x = strings.Replace(stg[9], "%", "", -1) // box_stg = x // } else { // var x = strings.Replace(stg[7], "%", "", -1) // box_stg = x // } // } else { // sum_storage = string(stg[8]) // var x = strings.Replace(stg[15], "%", "", -1) // conv, _ := strconv.Atoi(x) // if conv == 0 { // var x = strings.Replace(stg[14], "%", "", -1) // box_stg = x // } else { // box_stg = x // } // } // if Debug == 1 { // file.Printf("\n box_stg : %v ", box_stg) // file.Printf("\n sum_storage : %v ", sum_storage) // } // } // Get ether func Get_mac() string { var stt = true var x = "" file.Println("Get_mac Function\n") out, err := exec.Command("sh", "-c", "ifconfig | grep 'HWaddr'").Output() if err != nil { //log.Fatal(err) //file.Write_log("get_ether() grep 'HWaddr' Error", Path_log_luncher) stt = false } var out1 = string(out) var stg = strings.Split(out1, " ") if Debug == 1 { fmt.Printf(" \n Mac address : %v", stg) for i := 0; i < len(stg); i++ { fmt.Print(i) fmt.Print("_") fmt.Println(stg[i]) } } for j := 0; j < len(stg); j++ { if stg[j] == "HWaddr" { x = strings.Replace(stg[j+1], "%", "", -1) if Debug == 1 { fmt.Println("------------------------------------") fmt.Printf("Kieu mac : %T\t, Gia tri cua mac : %v\n", stg[j+1], stg[j+1]) fmt.Printf("Mac_address:%v\n ", x) } break } } if stt == false { out, err := exec.Command("sh", "-c", "ifconfig | grep 'ether'").Output() if err != nil { //log.Fatal(err) file.Write_log("get_ether() grep 'ether' Error", Path_log_luncher) } var out1 = string(out) var stg = strings.Split(out1, " ") if Debug == 1 { fmt.Printf(" \n Mac address : %v", stg) for i := 0; i < len(stg); i++ { fmt.Print(i) fmt.Print("_") fmt.Println(stg[i]) } } for j := 0; j < len(stg); j++ { if stg[j] == "ether" { x = strings.Replace(stg[j+1], "%", "", -1) if Debug == 1 { fmt.Println("------------------------------------") fmt.Printf("Kieu mac : %T\t, Gia tri cua mac : %v\n", stg[j+1], stg[j+1]) fmt.Printf("Mac_address:%v\n ", x) } break } } } return x } func Get_boot_stg() (string, string) { //file.Println("Function Get_boot_stg()") out, err := exec.Command("sh", "-c", " df |grep /dev/mmcblk1p1").Output() if err != nil { //log.Fatal(err) file.Write_log("get_boot_stg() Error", Path_log_luncher) } var out1 = string(out) var stg = strings.Split(out1, " ") var stg_arr [5]string var k int = 0 for i := 0; i < len(stg); i++ { if stg[i] != "" { stg_arr[k] = stg[i] //file.Printf("%v_%v_%v\n", i, stg[i], k) k = k + 1 } if k == 5 { break } } //sum_boot_stg = stg_arr[1] sum := stg_arr[1] var per = strings.Replace(stg_arr[4], "%", "", -1) //boot_stg = per if Debug == 1 { fmt.Printf("Boot Storage: %v \n ", sum) fmt.Printf("Sum_boot_storage:%v \n ", per) } return sum, per } // Get cpu AWS var avg_old int func Get_cpu() string { //file.Println("Function Get_cpu") out, err := exec.Command("sh", "-c", " cat /proc/stat | grep 'cpu '").Output() if err != nil { //file.Println(err) file.Write_log("Get_cpu() Error", Path_log_luncher) } var out1 = string(out) var cpu = strings.Split(out1, " ") //file.Printf("cpu : %q\n", cpu) //file.Printf("Old : %v\t%v\t%v\n",user, system,idle) x, _ := strconv.Atoi(cpu[2]) user = x - user y, _ := strconv.Atoi(cpu[4]) system = y - system z, _ := strconv.Atoi(cpu[5]) idle = z - idle k := user + system + idle if k == 0 { file.Println("user + system + idle = 0 of Function Get_cpu()") file.Write_log("user + system + idle = 0 of Function Get_cpu()", Path_log_luncher) avg = avg_old } else { avg = ((user + system) * 100) / k avg_old = avg } user = x system = y idle = z per := strconv.Itoa(avg) return per } func Check_path(path string) { // Check directory ? _, err := exec.Command("sh", "-c", "cd "+path).Output() if err != nil { //file.Printf(path + " not Exits\n") file.Write_log(path+" not Exits\n", Path_log_luncher) _, err1 := exec.Command("sh", "-c", "mkdir "+path).Output() if err1 != nil { //file.Printf(" Cant create " + path) file.Write_log("Cant create "+path, Path_log_luncher) } else { //file.Printf(" Create forder " + path) file.Write_log("Create forder"+path, Path_log_luncher) } } else { // file.Printf(path + " ok \n") file.Write_log(path+" ok \n", Path_log_luncher) } } func Get() (*Stats, error) { file, err := os.Open("/proc/meminfo") if err != nil { return nil, err } defer file.Close() return CollectMemoryStats(file) } type Stats struct { Total, Used, Buffers, Cached, Free float64 MemAvailableEnabled bool } func CollectMemoryStats(out io.Reader) (*Stats, error) { scanner := bufio.NewScanner(out) var memory Stats memStats := map[string]*float64{ "MemTotal": &memory.Total, "MemFree": &memory.Free, "Buffers": &memory.Buffers, "Cached": &memory.Cached, } for scanner.Scan() { line := scanner.Text() i := strings.IndexRune(line, ':') if i < 0 { continue } fld := line[:i] if ptr := memStats[fld]; ptr != nil { val := strings.TrimSpace(strings.TrimRight(line[i+1:], "kB")) if v, err := strconv.ParseFloat(val, 64); err == nil { *ptr = v * 1024 } if fld == "MemAvailable" { memory.MemAvailableEnabled = true } } } if err := scanner.Err(); err != nil { fmt.Printf("scan error for /proc/meminfo: %s", err) } memory.Used = memory.Total - memory.Free - memory.Buffers - memory.Cached return &memory, nil } func Sleep_ms(ms time.Duration) { time.Sleep(time.Millisecond * ms) // sleep(nano second) }