From 40309b8efdfddb5398cf55afec17bbe544be9f5c Mon Sep 17 00:00:00 2001 From: asandikci Date: Sat, 9 Sep 2023 19:48:04 +0300 Subject: [PATCH] son commit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - en son unload ile uğraşıyordum ama eksik kaldı... - windows/wine üzerinde sıkıntı çıkmakta - plugin check fonksiyonu implemente edilmedi - unload edilirken hata veriyo --- Makefile | 184 +++++++++++++++++++++--------- cmd/ahenk-go/ahenk-go.go | 38 +++++- cmd/plugin/check.go | 16 ++- cmd/plugin/jitconf_linux.go | 2 +- cmd/plugin/jitconf_windows.go | 2 +- cmd/plugin/load.go | 17 ++- cmd/plugin/manager.go | 53 ++------- cmd/plugin/manager_goloader.go | 41 +++++++ cmd/plugin/manager_safeplugins.go | 27 +++++ cmd/plugin/unload.go | 3 - cmd/plugin/unload_goloader.go | 34 ++++++ cmd/plugin/unload_safeplugins.go | 9 ++ go.mod | 17 ++- go.sum | 33 +++++- pkg/confdir/confdir.go | 14 +-- pkg/confdir/confdir_windows.go | 10 +- pkg/osinfo/cpu.go | 32 ------ pkg/osinfo/cpu_linux.go | 20 ++++ pkg/osinfo/cpu_windows.go | 14 +++ pkg/osinfo/disk.go | 47 -------- pkg/osinfo/disk_linux.go | 47 ++++++++ pkg/osinfo/disk_windows.go | 52 +++++++++ pkg/osinfo/kernel.go | 24 ---- pkg/osinfo/kernel_linux.go | 25 ++++ pkg/osinfo/kernel_windows.go | 8 ++ pkg/osinfo/memory.go | 25 ---- pkg/osinfo/memory_linux.go | 22 ++++ pkg/osinfo/memory_windows.go | 16 +++ pkg/osinfo/node.go | 25 ---- pkg/osinfo/node_linux.go | 26 +++++ pkg/osinfo/node_windows.go | 8 ++ plugins/resources/main.go | 8 +- 32 files changed, 604 insertions(+), 295 deletions(-) create mode 100644 cmd/plugin/manager_goloader.go create mode 100644 cmd/plugin/manager_safeplugins.go delete mode 100644 cmd/plugin/unload.go create mode 100644 cmd/plugin/unload_goloader.go create mode 100644 cmd/plugin/unload_safeplugins.go create mode 100644 pkg/osinfo/cpu_linux.go create mode 100644 pkg/osinfo/cpu_windows.go create mode 100644 pkg/osinfo/disk_linux.go create mode 100644 pkg/osinfo/disk_windows.go create mode 100644 pkg/osinfo/kernel_linux.go create mode 100644 pkg/osinfo/kernel_windows.go create mode 100644 pkg/osinfo/memory_linux.go create mode 100644 pkg/osinfo/memory_windows.go create mode 100644 pkg/osinfo/node_linux.go create mode 100644 pkg/osinfo/node_windows.go diff --git a/Makefile b/Makefile index 67bf1a2..73204ed 100644 --- a/Makefile +++ b/Makefile @@ -1,75 +1,145 @@ +SHELL := /bin/bash +STARSHIP_SHELL := /bin/bash REPO_NAME=ahenk-go REPO_LINK=https://git.aliberksandikci.com.tr/liderahenk/${REPO_NAME} -DAEMON_NAME=ahenk-go -OLD_DAEMON_NAME=ahenkd-go -PYTHON_DAEMON_NAME=ahenkd +# These variables imported from pkg/confdir/confdir_linux.go +PATH_PROGRAM=/usr/bin/${REPO_NAME} +PATH_USER_CONFIG=$([ -n "${XDG_CONFIG_HOME}" ] && echo "${XDG_CONFIG_HOME}" || echo "${HOME}/.config") # FIXME not working ? +PATH_DATA=/etc/${REPO_NAME}/ +PATH_PLUGINS={PATH_DATA}plugins/ +PATH_LOGS=${PATH_DATA}logs/ +PATH_PID=/run/ahenk-go.pid +PATH_VERSION=${PATH_DATA}version +GO_ARCH=amd64 + +# Wine variables for users. STATIC! change if these paths not fits for you +WINE_USER=${USER} +WINE_C=~/.wine/drive_c/ +WINE_PATH_PROGRAM=${WINE_C}Program\ Files/${REPO_NAME}/ +WINE_PATH_EXE=${WINE_PATH_PROGRAM}${REPO_NAME}.exe +WINE_PATH_USER_CONFIG=${WINE_C}/users/${WINE_USER}/AppData/Local/ +WINE_PATH_DATA=${WINE_C}ProgramData/${REPO_NAME}/ +WINE_PATH_PLUGINS=${WINE_PATH_DATA}plugins/ +WINE_PATH_LOGS=${WINE_PATH_DATA}logs/ +WINE_PATH_VERSION=${PATH_DATA}version +WINE_GO_ARCH=amd64 + -DATA_DIR=/etc/ahenk-go/ -LIB_DIR=/usr/share/ahenk-go/ -PLUGIN_DIR=${LIB_DIR}/plugins/ -TEMP_DIR=$(mktemp -d) -MAIN_DIR=${TEMP_DIR}/${REPO_NAME}/ info: @echo "Made by Aliberk Sandıkçı - 2023" - @echo "preclean: for cleaning old files, configurations" - @echo "TODO test: Test go files" - @echo "install: Build and install ahenk-go to DESTDIR" - @echo "uninstall: Uninstall ahenk-go from DESTDIR" + @echo "-- GENERAL USAGE ---" + @echo "install: install binary and copy plugins,packages,files" + @echo "uninstall: remove files, program and daemon" -preclean: - sudo rm -rf /usr/bin/$(DAEMON_NAME) - sudo rm -rf /usr/bin/${OLD_DAEMON_NAME} - sudo rm -rf /usr/bin/${PYTHON_DAEMON_NAME} - - # @# TODO systemd control for both three process for docker - # @# REVIEW are both killall and systemctl commands running? - # @pgrep -x ${DAEMON_NAME} && (sudo killall "${DAEMON_NAME}" || sudo systemctl disable "${DAEMON_NAME}" || sudo systemctl stop "${DAEMON_NAME}") || echo "no ${DAEMON_NAME} found" - # @pgrep -x ${OLD_DAEMON_NAME} && (sudo killall "${OLD_DAEMON_NAME}" || sudo systemctl disable "${OLD_DAEMON_NAME}" || sudo systemctl stop "${OLD_DAEMON_NAME}") || echo "no ${OLD_DAEMON_NAME} found" + @echo "-- LOCAL DEVELOPMENT ----" + @echo "test: Test go files ,not implemented yet" + @echo "local: install + systemd daemon" + @echo "local_wine: install on wine with build windows&amd64" + @echo "local_safeplugins: install with imported safeplugins, do not start systemd daemon" + @echo "local_wine_safeplugins: install on wine with build windows&amd64 and imported safeplugins" + +# +# --- GENERAL USAGE --- +# + +install: + sudo go build -o ${DESTDIR}${PATH_PROGRAM} ./cmd/${REPO_NAME}/ + @sudo mkdir -p "${DESTDIR}${PATH_DATA}" + + @echo "copying necessary plugins and packages" + @sleep 1 + sudo cp -r ./plugins "${DESTDIR}${PATH_DATA}" + sudo cp -r ./pkg "${DESTDIR}${PATH_DATA}" + + @echo "copying necessary files" + @sleep 1 + sudo cp go.mod "${DESTDIR}${PATH_DATA}" + sudo cp go.sum "${DESTDIR}${PATH_DATA}" + sudo cp version "${DESTDIR}${PATH_DATA}" + +uninstall: + @echo "removing systemd daemon" + sudo systemctl stop ${REPO_NAME} + sudo systemctl disable ${REPO_NAME} + sudo rm -f "${DESTDIR}/etc/systemd/system/${REPO_NAME}.service" + sudo systemctl daemon-reload + + @echo "WARNING: uninstall option removes all ${DESTDIR}${PATH_DATA} !!!" + @echo "waiting 10 seconds, abort if you don't want to remove this dir" + @sleep 10 + sudo rm -rf "${DESTDIR}${PATH_DATA}" + sudo rm -rf "${DESTDIR}${PATH_PROGRAM}" + + +# +# --- LOCAL DEVELOPMENT --- +# - # @# TODO - # @# echo -e "Do you want to remove python implementation of ahenk if installed in system?" - # @# read -rp "(Y/N) " input - - # @pgrep -x ${PYTHON_DAEMON_NAME} && (sudo killall "${PYTHON_DAEMON_NAME}" || sudo systemctl disable "${PYTHON_DAEMON_NAME}" || sudo systemctl stop "${PYTHON_DAEMON_NAME}") || echo "no ${PYTHON_DAEMON_NAME} found" - - # sudo systemctl daemon-reload - sudo rm -rf ${DATA_DIR} - @echo -e "PRE-CLENING DONE\n" test: @echo -e "Testing go files not implemented yet!" -install: - sudo go build -o ${DESTDIR}/usr/bin/${REPO_NAME} ./cmd/ahenk-go/ - @sudo mkdir -p "${DESTDIR}/${LIB_DIR}" - @sudo mkdir -p "${DESTDIR}/${PLUGIN_DIR}" - sudo go build -buildmode=plugin -o ${DESTDIR}/${PLUGIN_DIR}/resources.so ./plugins/resources - sudo go build -buildmode=plugin -o ${DESTDIR}/${PLUGIN_DIR}/tmptest.so ./plugins/tmptest - @sudo mkdir -p "${DESTDIR}/${DATA_DIR}" +local: i_local_configure_paths i_local_build i_local_system_reload -linux_goloader_install: -# NEXT - sudo go build -o ${DESTDIR}/usr/bin/${REPO_NAME} ./cmd/ahenk-go/ +local_wine: i_local_wine_configure_paths i_local_wine_build i_local_wine_link - @echo "linux_goloader_install option also removes all datadir!" - @sudo rm -rf "${DESTDIR}/${DATA_DIR}" +local_safeplugins: i_local_configure_paths i_local_build_safeplugins - @sudo mkdir -p "${DESTDIR}/${DATA_DIR}" - sudo cp -r ./plugins "${DESTDIR}/${DATA_DIR}/" - sudo cp -r ./pkg "${DESTDIR}/${DATA_DIR}/" - sudo cp go.mod "${DESTDIR}/${DATA_DIR}/" - sudo cp go.sum "${DESTDIR}/${DATA_DIR}/" - sudo cp version "${DESTDIR}/${DATA_DIR}/" +local_wine_safeplugins: i_local_wine_configure_paths i_local_wine_build_safeplugins i_local_wine_link -windows_install: - sudo env GOOS=windows GOARCH=amd64 go build -o ${DESTDIR}/usr/bin/${REPO_NAME} ./cmd/ahenk-go/ - @sudo mkdir -p "${DESTDIR}/${LIB_DIR}" - @sudo mkdir -p "${DESTDIR}/${PLUGIN_DIR}" - sudo GOOS=windows GOARCH=amd64 go build -buildmode=plugin -o ${DESTDIR}/${PLUGIN_DIR}/resources.so ./plugins/resources - sudo GOOS=windows GOARCH=amd64 go build -buildmode=plugin -o ${DESTDIR}/${PLUGIN_DIR}/tmptest.so ./plugins/tmptest - @sudo mkdir -p "${DESTDIR}/${DATA_DIR}" -uninstall: - @sudo rm -rf ${DESTDIR}/usr/bin/${REPO_NAME} +# +# --- IMPORTED BY OTHER --- +# + +# --> i_local +i_local_configure_paths: + sudo rm -rf "${DESTDIR}${PATH_DATA}" + sudo rm -rf ${DESTDIR}${PATH_PROGRAM} + + sudo mkdir -p "${DESTDIR}${PATH_DATA}" + + sudo cp -r ./plugins "${DESTDIR}${PATH_DATA}" + sudo cp -r ./pkg "${DESTDIR}${PATH_DATA}" + sudo cp go.mod "${DESTDIR}${PATH_DATA}" + sudo cp go.sum "${DESTDIR}${PATH_DATA}" + sudo cp version "${DESTDIR}${PATH_DATA}" + +i_local_build: + sudo env GOARCH=${GO_ARCH} go build -o ${DESTDIR}${PATH_PROGRAM} ./cmd/${REPO_NAME}/ + +i_local_build_safeplugins: + sudo env GOARCH=${GO_ARCH} go build -tags safeplugins -o ${DESTDIR}${PATH_PROGRAM} ./cmd/${REPO_NAME}/ + +i_local_system_reload: + @echo "configuring systemd daemon" + sudo cp ./debian/${REPO_NAME}.service /etc/systemd/system + sudo systemctl daemon-reload + sudo systemctl enable ${REPO_NAME} + sudo systemctl start ${REPO_NAME} + +# --> i_local_wine +i_local_wine_configure_paths: + sudo rm -rf ${DESTDIR}${WINE_PATH_DATA} + sudo rm -rf ${DESTDIR}${WINE_PATH_PROGRAM} + sudo rm -rf ${DESTDIR}${PATH_PROGRAM} + + mkdir -p ${DESTDIR}${WINE_PATH_DATA} + mkdir -p ${DESTDIR}${WINE_PATH_PROGRAM} + + cp -r ./plugins ${DESTDIR}${WINE_PATH_DATA} + cp -r ./pkg ${DESTDIR}${WINE_PATH_DATA} + cp go.mod ${DESTDIR}${WINE_PATH_DATA} + cp go.sum ${DESTDIR}${WINE_PATH_DATA} + cp version ${DESTDIR}${WINE_PATH_DATA} + +i_local_wine_build: + sudo env GOOS=windows GOARCH=${WINE_GO_ARCH} go build -o ${DESTDIR}${WINE_PATH_EXE} ./cmd/${REPO_NAME}/ + +i_local_wine_build_safeplugins: + sudo env GOOS=windows GOARCH=${WINE_GO_ARCH} go build -tags safeplugins -o ${DESTDIR}${WINE_PATH_EXE} ./cmd/${REPO_NAME}/ + +i_local_wine_link: + sudo ln -svf ${DESTDIR}${WINE_PATH_EXE} ${DESTDIR}${PATH_PROGRAM} \ No newline at end of file diff --git a/cmd/ahenk-go/ahenk-go.go b/cmd/ahenk-go/ahenk-go.go index e2ce317..eee8521 100644 --- a/cmd/ahenk-go/ahenk-go.go +++ b/cmd/ahenk-go/ahenk-go.go @@ -4,6 +4,7 @@ import ( "log" "os" "os/user" + "runtime" "time" "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/cmd/plugin" @@ -17,9 +18,12 @@ import ( // Main Function that starts daemon and controls arguments func main() { confdir.GetPaths() - if len(os.Args) == 2 && slices.Contains([]string{"start", "stop", "restart", "nodaemon", "tmptest"}, os.Args[1]) { + if len(os.Args) == 2 && slices.Contains([]string{"start", "stop", "restart", "nodaemon", "tmptest", "winsafe"}, os.Args[1]) { switch os.Args[1] { case "start": + if runtime.GOOS == "windows" { + panic("start argument is not compatible with windows right now") // TODO + } utils.CreatePath(confdir.Paths.Data) utils.CreatePath(confdir.Paths.Logs) cntxt := &daemon.Context{ @@ -57,12 +61,36 @@ func main() { case "tmptest": log.Print("TEMPORARY TEST STARTED, log files are NOT redirecting!") - plugFunctions := []string{"tmptest", "resources"} - plugin.ConnectPlugins(plugFunctions) + plugNames := []string{"tmptest"} + plugin.ConnectPlugins(plugNames) plugin.Tmptest.TmpTest() - plugin.LogPlugin("Agent Info", plugin.Resources.AgentInfo(), true) - plugin.LogPlugin("Resource Usage", plugin.Resources.ResourceUsage(), true) + // if a, b := plugin.Resources.AgentInfo(); b == nil { + // plugin.LogPlugin("Agent Info", a, true) + // } + // if a, b := plugin.Resources.ResourceUsage(); b == nil { + // plugin.LogPlugin("Agent Info", a, true) + // } + + log.Println("waiting...") + time.Sleep(5 * time.Second) + + plugin.UnloadPlugins(plugNames) + log.Println("Plugins unloaded succesfully, following lines should be give error!") + // err := plugin.Tmptest.TmpTest() + // if err != nil { + // log.Println("Plugin was not loaded or already unloaded !: ", err) + // } + // if a, err := plugin.Resources.AgentInfo(); err == nil { + // plugin.LogPlugin("Agent Info", a, true) + // } else { + // log.Println("Plugin was not loaded or already unloaded !: ", err) + // } + // if a, err := plugin.Resources.ResourceUsage(); err == nil { + // plugin.LogPlugin("Agent Info", a, true) + // } else { + // log.Println("Plugin was not loaded or already unloaded !: ", err) + // } // comment these if you want to run usual code after tmptest log.Println("exiting before making usual code") diff --git a/cmd/plugin/check.go b/cmd/plugin/check.go index bfcd4a9..d0ed1e2 100644 --- a/cmd/plugin/check.go +++ b/cmd/plugin/check.go @@ -1,3 +1,17 @@ package plugin -// NEXT +import "log" + +// Checks plugin status +func checkPlugin(plugVal interface{}) { + if plugVal == nil { + log.Fatal("Plugin loaded but there is no value!") + } else { + plugInfo := plugVal.(PlugGeneral).Info() + log.Printf("Plugin \"%v\" loaded and ready to use with version \"%v\" ", plugInfo["name"], plugInfo["version"]) + } +} + +func checkExist() { + +} diff --git a/cmd/plugin/jitconf_linux.go b/cmd/plugin/jitconf_linux.go index 9afa4b1..a6f0587 100644 --- a/cmd/plugin/jitconf_linux.go +++ b/cmd/plugin/jitconf_linux.go @@ -6,7 +6,7 @@ import "github.com/eh-steve/goloader/jit" func getJITConf() jit.BuildConfig { return jit.BuildConfig{ - KeepTempFiles: true, // Files are copied/written to a temp dir to ensure it is writable. This retains the temporary copies + KeepTempFiles: false, // Files are copied/written to a temp dir to ensure it is writable. This retains the temporary copies ExtraBuildFlags: []string{"-x"}, // Flags passed to go build command BuildEnv: []string{"GOOS=linux"}, // Env vars to set for go build toolchain TmpDir: "", // To control where temporary files are copied diff --git a/cmd/plugin/jitconf_windows.go b/cmd/plugin/jitconf_windows.go index 43b355d..6749c3e 100644 --- a/cmd/plugin/jitconf_windows.go +++ b/cmd/plugin/jitconf_windows.go @@ -6,7 +6,7 @@ import "github.com/eh-steve/goloader/jit" func getJITConf() jit.BuildConfig { return jit.BuildConfig{ - KeepTempFiles: true, // Files are copied/written to a temp dir to ensure it is writable. This retains the temporary copies + KeepTempFiles: false, // Files are copied/written to a temp dir to ensure it is writable. This retains the temporary copies ExtraBuildFlags: []string{"-x"}, // Flags passed to go build command BuildEnv: []string{"GOOS=windows"}, // Env vars to set for go build toolchain TmpDir: "", // To control where temporary files are copied diff --git a/cmd/plugin/load.go b/cmd/plugin/load.go index 2cb2b9a..803a827 100644 --- a/cmd/plugin/load.go +++ b/cmd/plugin/load.go @@ -1,18 +1,26 @@ +//go:build !safeplugins + package plugin import ( "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/pkg/confdir" "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/pkg/utils" + "github.com/eh-steve/goloader" "github.com/eh-steve/goloader/jit" ) -// Load Plugin placed in confdir.Paths.Plugins, returns empty interface with channel +type PluginModule struct { + plugin interface{} + module *goloader.CodeModule +} + +// Load Plugin placed in confdir.Paths.Plugins, returns interface with channel // // Do not forget to cast in plugin manager -func LoadPlugin(plugName string, conf jit.BuildConfig, chn chan interface{}) { +func LoadPlugin(plugName string, conf jit.BuildConfig) PluginModule { // TODO if error caugth try without relative path, this will be good for local testing - loadable, err := jit.BuildGoPackage(conf, confdir.Paths.Plugins+plugName+"/") + loadable, err := jit.BuildGoPackage(conf, confdir.Paths.Plugins+plugName) utils.Check(err) module, err := loadable.Load() @@ -25,5 +33,6 @@ func LoadPlugin(plugName string, conf jit.BuildConfig, chn chan interface{}) { panic("There is no exported symbol in " + plugName) } - chn <- plugOut + myPlugin := PluginModule{plugin: plugOut, module: module} + return myPlugin } diff --git a/cmd/plugin/manager.go b/cmd/plugin/manager.go index 3c17568..7fff5e6 100644 --- a/cmd/plugin/manager.go +++ b/cmd/plugin/manager.go @@ -13,19 +13,23 @@ type PlugGeneral interface { Info() map[string]interface{} } +type PlugUnloaded interface { + error +} + // plugins/resources type ResourcesI interface { // Get Agent Info, see plugins/resources for more information - AgentInfo() map[string]interface{} // LINK plugins/resources/main.go#AgentInfo + AgentInfo() (map[string]interface{}, error) // LINK plugins/resources/main.go#AgentInfo // Get Resource Usage, see plugins/resources for more information - ResourceUsage() map[string]interface{} // LINK plugins/resources/main.go#ResourceUsage + ResourceUsage() (map[string]interface{}, error) // LINK plugins/resources/main.go#ResourceUsage } // plugins/tmptest type TmpTestI interface { // Run temporary tests - TmpTest() // LINK plugins/tmptest/main.go#TmpTest + TmpTest() error // LINK plugins/tmptest/main.go#TmpTest } // FILLME[epic=new-plugin-template] @@ -44,28 +48,11 @@ var Resources ResourcesI // // Gets plugin names as string slice func ConnectPlugins(params []string) { + connectPlugins(params) +} - conf := getJITConf() - chanPlug := make(chan interface{}) - - for _, v := range params { - go LoadPlugin(v, conf, chanPlug) - plug, ok := <-chanPlug - - switch v { - case "tmptest": - Tmptest = plug.(TmpTestI) - checkPlugin(Tmptest, ok) - case "resources": - Resources = plug.(ResourcesI) - checkPlugin(Resources, ok) - - // FILLME[epic=new-plugin-template] - // case "pluginname": - // Pluginname = plug.(NewPluginInterfaceI) - // checkPlugin(Pluginname, ok) - } - } +func UnloadPlugins(params []string) { + unloadPlugins(params) } // Logs plugin outputs. @@ -82,24 +69,6 @@ func LogPlugin(title string, mp map[string]interface{}, toJson bool) { } } -// Checks plugin status -func checkPlugin(plugVal interface{}, status bool) { - if status { - if plugVal == nil { - log.Fatal("Plugin loaded but there is no value!") - } else { - plugInfo := plugVal.(PlugGeneral).Info() - log.Printf("Plugin \"%v\" loaded and ready to use with version \"%v\" ", plugInfo["name"], plugInfo["version"]) - } - } else { - if plugVal == nil { - log.Fatal("Plugin closed and there is no value! ") - } else { - log.Fatal("Plugin closed or there is an error") - } - } -} - // // TODO response to Lider // func createResponse() { diff --git a/cmd/plugin/manager_goloader.go b/cmd/plugin/manager_goloader.go new file mode 100644 index 0000000..e14e251 --- /dev/null +++ b/cmd/plugin/manager_goloader.go @@ -0,0 +1,41 @@ +//go:build !safeplugins + +package plugin // pluginmanager + +type Unloadable interface { + Unload() error +} + +var TmpTestModule Unloadable +var ResourcesModule Unloadable + +// Connect plugins to main code +// +// Gets plugin names as string slice +func connectPlugins(params []string) { + + conf := getJITConf() + + var pluginM PluginModule + + for _, v := range params { + pluginM = LoadPlugin(v, conf) + plug := pluginM.plugin + + switch v { + case "tmptest": + Tmptest = plug.(TmpTestI) + TmpTestModule = pluginM.module + checkPlugin(Tmptest) + case "resources": + Resources = plug.(ResourcesI) + ResourcesModule = pluginM.module + checkPlugin(Resources) + + // FILLME[epic=new-plugin-template] + // case "pluginname": + // Pluginname = plug.(NewPluginInterfaceI) + // checkPlugin(Pluginname, ok) + } + } +} diff --git a/cmd/plugin/manager_safeplugins.go b/cmd/plugin/manager_safeplugins.go new file mode 100644 index 0000000..2b461ee --- /dev/null +++ b/cmd/plugin/manager_safeplugins.go @@ -0,0 +1,27 @@ +//go:build safeplugins + +// IMPORTED SAFE PLUGINS, TEST PURPOSE + +package plugin + +import ( + "fmt" + "os" + + "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/plugins/resources" + "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/plugins/tmptest" +) + +func connectPlugins(params []string) { + // INFO + tmptest.TmptestConnect.Info() + resources.ResourcesConnect.Info() + + // FUNCTIONS + tmptest.TmptestConnect.TmpTest() + LogPlugin("Agent Info - SAFE", resources.ResourcesConnect.AgentInfo(), true) + LogPlugin("Resource Usage - SAFE", resources.ResourcesConnect.ResourceUsage(), true) + + fmt.Println("THERE WAS NO ERROR, RUN make local OR make local_wine NOW FOR CONTINUE TESTING WITH GOLADER PLUGIN LOGIC") + os.Exit(0) +} diff --git a/cmd/plugin/unload.go b/cmd/plugin/unload.go deleted file mode 100644 index bfcd4a9..0000000 --- a/cmd/plugin/unload.go +++ /dev/null @@ -1,3 +0,0 @@ -package plugin - -// NEXT diff --git a/cmd/plugin/unload_goloader.go b/cmd/plugin/unload_goloader.go new file mode 100644 index 0000000..6e2dec1 --- /dev/null +++ b/cmd/plugin/unload_goloader.go @@ -0,0 +1,34 @@ +//go:build !safeplugins + +package plugin + +import "log" + +func unloadPlugins(params []string) { + + for _, v := range params { + switch v { + case "tmptest": + err := TmpTestModule.Unload() + unloaded, ok := Tmptest.(PlugUnloaded) + if ok { + log.Printf("Succesfully unloaded tmptest: %v - %v", unloaded, err) + } else { + log.Fatalf("There was an error while unloading tmptest: %v - %v", unloaded, err) + } + case "resources": + err := ResourcesModule.Unload() + unloaded, ok := Resources.(PlugUnloaded) + if ok { + log.Printf("Succesfully unloaded resources: %v - %v", unloaded, err) + } else { + log.Fatalf("There was an error while unloading resources: %v - %v", unloaded, err) + } + + // FILLME[epic=new-plugin-template] + // case "pluginname": + // PluginnameModule.Unload() + // TODO proper template + } + } +} diff --git a/cmd/plugin/unload_safeplugins.go b/cmd/plugin/unload_safeplugins.go new file mode 100644 index 0000000..7f8a09b --- /dev/null +++ b/cmd/plugin/unload_safeplugins.go @@ -0,0 +1,9 @@ +//go:build safeplugins + +package plugin + +import "log" + +func unloadPlugins(params []string) { + log.Println("You can not unload plugins in safeplugin build/logic, skipping...") +} diff --git a/go.mod b/go.mod index 39b9a17..6c7df75 100644 --- a/go.mod +++ b/go.mod @@ -4,23 +4,28 @@ go 1.21 require ( github.com/sevlyar/go-daemon v0.1.6 + github.com/shirou/gopsutil v3.21.11+incompatible github.com/zcalusic/sysinfo v1.0.1 - golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63 + golang.org/x/exp v0.0.0-20230905200255-921286631fa9 golang.org/x/text v0.13.0 ) require ( - github.com/eh-steve/goloader v0.0.0-20230731163325-b789213e8550 // indirect - github.com/go-ole/go-ole v1.3.0 // indirect - github.com/stretchr/testify v1.8.4 // indirect + github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect + github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect github.com/tklauser/go-sysconf v0.3.12 // indirect github.com/tklauser/numcpus v0.6.1 // indirect +) + +require ( + github.com/eh-steve/goloader v0.0.0-20230906184435-2b17d7cb91a3 // direct + github.com/go-ole/go-ole v1.3.0 // indirect + github.com/shirou/gopsutil/v3 v3.23.8 // direct github.com/yusufpapurcu/wmi v1.2.3 // indirect ) require ( - github.com/eh-steve/goloader/jit v0.0.0-20230731163325-b789213e8550 + github.com/eh-steve/goloader/jit v0.0.0-20230906184435-2b17d7cb91a3 github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 // indirect - github.com/shirou/gopsutil v3.21.11+incompatible // direct golang.org/x/sys v0.12.0 // direct ) diff --git a/go.sum b/go.sum index a183255..76085c5 100644 --- a/go.sum +++ b/go.sum @@ -1,9 +1,10 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/eh-steve/goloader v0.0.0-20230731163325-b789213e8550 h1:8yXPOoUPeKZmC3QfqUY0wkerRf5OQ8YeCgSodrcC8J8= -github.com/eh-steve/goloader v0.0.0-20230731163325-b789213e8550/go.mod h1:k7xs3CUwCvOU9aw851I6AEb6ZzZJ3nos5dZ6A/2ewM0= -github.com/eh-steve/goloader/jit v0.0.0-20230731163325-b789213e8550 h1:clY7T47fFZdFcILcu7uksS7FStRaKMssCYGW0l/AoMo= -github.com/eh-steve/goloader/jit v0.0.0-20230731163325-b789213e8550/go.mod h1:p18VKcPYO8oWGYcQt/K5EGIGqak0ZT5HwVirGpUGZBg= +github.com/eh-steve/goloader v0.0.0-20230906184435-2b17d7cb91a3 h1:FxN0V4SdkJoD1K98g3H2zbMaxc81JVbxl+EiMOMmack= +github.com/eh-steve/goloader v0.0.0-20230906184435-2b17d7cb91a3/go.mod h1:k7xs3CUwCvOU9aw851I6AEb6ZzZJ3nos5dZ6A/2ewM0= +github.com/eh-steve/goloader/jit v0.0.0-20230906184435-2b17d7cb91a3 h1:XDTVGrGD4LL7eCBFSBn1AxcFL2fwUAscn8ma6sab6/s= +github.com/eh-steve/goloader/jit v0.0.0-20230906184435-2b17d7cb91a3/go.mod h1:p18VKcPYO8oWGYcQt/K5EGIGqak0ZT5HwVirGpUGZBg= github.com/eh-steve/goloader/jit/testdata v0.0.0-20230730231803-5c95d7a5f4e2 h1:pulprUBu3Rncam2xFKzaUTf8SlbaoOHtNocYBSbvprI= github.com/eh-steve/goloader/jit/testdata v0.0.0-20230730231803-5c95d7a5f4e2/go.mod h1:GyUY1mfY7NCdoVRo5H8+kmhLa/xE418ZcjfDfgwicXw= github.com/eh-steve/goloader/unload v0.0.0-20230730231803-5c95d7a5f4e2 h1:XBYe9gRPYpfxBRO9kBeep/FZrbeIuxPn5d6dun2oLQU= @@ -11,16 +12,32 @@ github.com/eh-steve/goloader/unload v0.0.0-20230730231803-5c95d7a5f4e2/go.mod h1 github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= +github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0 h1:iQTw/8FWTuc7uiaSepXwyf3o52HaUYcV+Tu66S3F5GA= github.com/kardianos/osext v0.0.0-20190222173326-2bc1f35cddc0/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8= +github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4= +github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I= github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw= +github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/sevlyar/go-daemon v0.1.6 h1:EUh1MDjEM4BI109Jign0EaknA2izkOyi0LV3ro3QQGs= github.com/sevlyar/go-daemon v0.1.6/go.mod h1:6dJpPatBT9eUwM5VCw9Bt6CdX9Tk6UWvhW3MebLDRKE= github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= +github.com/shirou/gopsutil/v3 v3.23.8 h1:xnATPiybo6GgdRoC4YoGnxXZFRc3dqQTGi73oLvvBrE= +github.com/shirou/gopsutil/v3 v3.23.8/go.mod h1:7hmCaBn+2ZwaZOr6jmPBZDfawwMGuo1id3C6aM8EDqQ= +github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ= +github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU= @@ -31,9 +48,10 @@ github.com/yusufpapurcu/wmi v1.2.3 h1:E1ctvB7uKFMOJw3fdOW32DwGE9I7t++CRUEMKvFoFi github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= github.com/zcalusic/sysinfo v1.0.1 h1:cVh8q3codjh43AGRTa54dJ2Zq+qPejv8n2VWpxKViwc= github.com/zcalusic/sysinfo v1.0.1/go.mod h1:LxwKwtQdbTIQc65drhjQzYzt0o7jfB80LrrZm7SWn8o= -golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63 h1:m64FZMko/V45gv0bNmrNYoDEq8U5YUhetc9cBWKS1TQ= -golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63/go.mod h1:0v4NqG35kSWCMzLaMeX+IQrlSnVE/bqGSyC2cz/9Le8= +golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g= +golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -41,5 +59,8 @@ golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/pkg/confdir/confdir.go b/pkg/confdir/confdir.go index 32ff6f2..9d24750 100644 --- a/pkg/confdir/confdir.go +++ b/pkg/confdir/confdir.go @@ -1,13 +1,13 @@ package confdir type Path struct { - Program string `json:"Program"` - UserConfig string `json:"User Config"` - Data string `json:"Data"` - Plugins string `json:"Plugins"` - Logs string `json:"Logs"` - Pid string `json:"pid"` - Version string `json:"version"` + Program string `json:"Program"` // executable path + UserConfig string `json:"User Config"` // user config directory path + Data string `json:"Data"` // program data directory path + Plugins string `json:"Plugins"` // plugin directory path + Logs string `json:"Logs"` // log directory path + Pid string `json:"pid"` // linux pid file path + Version string `json:"version"` // version file path } var Paths Path diff --git a/pkg/confdir/confdir_windows.go b/pkg/confdir/confdir_windows.go index 507b9db..41b0839 100644 --- a/pkg/confdir/confdir_windows.go +++ b/pkg/confdir/confdir_windows.go @@ -6,11 +6,11 @@ import "os" func getPaths() Path { var path Path - path.Program = "TODO" + path.Program = "C:\\Program Files\\ahenk-go\\ahenk-go.exe" path.UserConfig, _ = os.UserConfigDir() - path.Data = "TODO" - path.Plugins = path.Data + "plugins/" - path.Logs = path.Data + "logs/" - path.Pid = "TODO" + path.Data = "C:\\ProgramData\\ahenk-go\\" + path.Plugins = path.Data + "plugins\\" + path.Logs = path.Data + "logs\\" + path.Version = path.Data + "version" return path } diff --git a/pkg/osinfo/cpu.go b/pkg/osinfo/cpu.go index d7b8131..bdd00d7 100644 --- a/pkg/osinfo/cpu.go +++ b/pkg/osinfo/cpu.go @@ -1,13 +1,5 @@ package osinfo -import ( - "runtime" - - "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/pkg/utils" - "github.com/shirou/gopsutil/cpu" - "github.com/zcalusic/sysinfo" -) - type CPU struct { Vendor string `json:"vendor,omitempty"` Model string `json:"model,omitempty"` @@ -17,27 +9,3 @@ type CPU struct { Cores uint `json:"cores,omitempty"` // number of physical CPU cores Threads uint `json:"threads,omitempty"` // number of logical (HT) CPU cores } - -func (h *System) getCPUInfo() { - if runtime.GOOS == "linux" { - var si sysinfo.SysInfo - si.GetSysInfo() - - h.CPU.Vendor = si.CPU.Vendor - h.CPU.Model = si.CPU.Model - h.CPU.Speed = si.CPU.Speed - h.CPU.Cache = si.CPU.Cache - h.CPU.Cpus = si.CPU.Cpus - h.CPU.Cores = si.CPU.Cores - h.CPU.Threads = si.CPU.Threads - } else { - cpuInfo, err := cpu.Info() - utils.Check(err) - h.CPU.Vendor = cpuInfo[0].VendorID - h.CPU.Vendor = cpuInfo[0].Model - // h.CPU.Vendor = cpuInfo[0].Speed // TODO - - } -} - -// REVIEW Windows compatibility and separate files diff --git a/pkg/osinfo/cpu_linux.go b/pkg/osinfo/cpu_linux.go new file mode 100644 index 0000000..ee85231 --- /dev/null +++ b/pkg/osinfo/cpu_linux.go @@ -0,0 +1,20 @@ +//go:build linux && !windows + +package osinfo + +import ( + "github.com/zcalusic/sysinfo" +) + +func (h *System) getCPUInfo() { + var si sysinfo.SysInfo + si.GetSysInfo() + + h.CPU.Vendor = si.CPU.Vendor + h.CPU.Model = si.CPU.Model + h.CPU.Speed = si.CPU.Speed + h.CPU.Cache = si.CPU.Cache + h.CPU.Cpus = si.CPU.Cpus + h.CPU.Cores = si.CPU.Cores + h.CPU.Threads = si.CPU.Threads +} diff --git a/pkg/osinfo/cpu_windows.go b/pkg/osinfo/cpu_windows.go new file mode 100644 index 0000000..23d26be --- /dev/null +++ b/pkg/osinfo/cpu_windows.go @@ -0,0 +1,14 @@ +//go:build windows + +package osinfo + +// TODO Get windows cpu information +// FIXME Causes error on windows(wine) +func (h *System) getCPUInfo() { + // var cpuInfo []cpu.InfoStat + // var err error + // cpuInfo, err = cpu.Info() + // utils.Check(err) + // h.CPU.Vendor = cpuInfo[0].VendorID + // h.CPU.Vendor = cpuInfo[0].Model +} diff --git a/pkg/osinfo/disk.go b/pkg/osinfo/disk.go index 219b6f8..8892500 100644 --- a/pkg/osinfo/disk.go +++ b/pkg/osinfo/disk.go @@ -1,55 +1,8 @@ package osinfo -import ( - "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/pkg/utils" - "github.com/shirou/gopsutil/disk" -) - type Disk struct { Devices string `json:"devices,omitempty"` // physical disk devices as string Total float64 `json:"total,omitempty"` // Total Disk size in GiB Used float64 `json:"used,omitempty"` // Used Disk size in GiB Free float64 `json:"free,omitempty"` // Free Disk size in GiB } - -func (h *System) getDiskInfo() { - - for _, v := range GetDisks() { - h.Disk.Devices += v.Device + ", " - } - h.Disk.Total = GetDiskUsage()["spaceTotal"] - h.Disk.Used = GetDiskUsage()["usedTotal"] - h.Disk.Free = GetDiskUsage()["usedFree"] -} - -// return all physical disks, USB and CD-ROM devices -// -// An example output: -// device: /dev/example, mountpoint: /, fstype: ext4, opts:rw,noatime -func GetDisks() []disk.PartitionStat { - parts, err := disk.Partitions(false) - utils.Check(err) - return parts -} - -// return disk usage as GiB -// -// TODO different functions for all disks / a specified disk? -// FIXME Wrong Disk values for docker !!! (probably because counting also virtual mountpoints?) -func GetDiskUsage() map[string]float64 { - var totalSize, freeSize, usedSize uint64 - for _, part := range GetDisks() { - u, err := disk.Usage(part.Mountpoint) - utils.Check(err) - totalSize += u.Total - freeSize += u.Free - usedSize += u.Used - } - return map[string]float64{ - "spaceTotal": utils.Byte2GiB(totalSize), - "freeTotal": utils.Byte2GiB(freeSize), - "usedTotal": utils.Byte2GiB(usedSize), - } -} - -// REVIEW Windows compatibility and separate files diff --git a/pkg/osinfo/disk_linux.go b/pkg/osinfo/disk_linux.go new file mode 100644 index 0000000..c8d0e58 --- /dev/null +++ b/pkg/osinfo/disk_linux.go @@ -0,0 +1,47 @@ +//go:build linux && !windows + +package osinfo + +import ( + "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/pkg/utils" + "github.com/shirou/gopsutil/disk" +) + +func (h *System) getDiskInfo() { + + for _, v := range GetDisks() { + h.Disk.Devices += v.Device + ", " + } + h.Disk.Total = GetDiskUsage()["spaceTotal"] + h.Disk.Used = GetDiskUsage()["usedTotal"] + h.Disk.Free = GetDiskUsage()["usedFree"] +} + +// return all physical disks, USB and CD-ROM devices +// +// An example output: +// device: /dev/example, mountpoint: /, fstype: ext4, opts:rw,noatime +func GetDisks() []disk.PartitionStat { + parts, err := disk.Partitions(false) + utils.Check(err) + return parts +} + +// return disk usage as GiB +// +// TODO different functions for all disks / a specified disk? +// FIXME Wrong Disk values for docker !!! (probably because counting also virtual mountpoints?) +func GetDiskUsage() map[string]float64 { + var totalSize, freeSize, usedSize uint64 + for _, part := range GetDisks() { + u, _ := disk.Usage(part.Mountpoint) + totalSize += u.Total + freeSize += u.Free + usedSize += u.Used + } + return map[string]float64{ + "spaceTotal": utils.Byte2GiB(totalSize), + "freeTotal": utils.Byte2GiB(freeSize), + "usedTotal": utils.Byte2GiB(usedSize), + } +} diff --git a/pkg/osinfo/disk_windows.go b/pkg/osinfo/disk_windows.go new file mode 100644 index 0000000..1066d3e --- /dev/null +++ b/pkg/osinfo/disk_windows.go @@ -0,0 +1,52 @@ +//go:build windows + +package osinfo + +import ( + "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/pkg/utils" + "github.com/shirou/gopsutil/v3/disk" +) + +func (h *System) getDiskInfo() { + + for _, v := range GetDisks() { + h.Disk.Devices += v.Device + ", " + } + h.Disk.Total = GetDiskUsage()["spaceTotal"] + h.Disk.Used = GetDiskUsage()["usedTotal"] + h.Disk.Free = GetDiskUsage()["usedFree"] +} + +// return all physical disks, USB and CD-ROM devices +// +// An example output: +// device: /dev/example, mountpoint: /, fstype: ext4, opts:rw,noatime +func GetDisks() []disk.PartitionStat { + parts, err := disk.Partitions(false) + utils.Check(err) + return parts +} + +// return disk usage as GiB +// +// TODO different functions for all disks / a specified disk? +// FIXME Wrong Disk values for docker !!! (probably because counting also virtual mountpoints?) +func GetDiskUsage() map[string]float64 { + var totalSize, freeSize, usedSize uint64 + for _, part := range GetDisks() { + u, _ := disk.Usage(part.Mountpoint) + + // FIXME paths other than C: gives error in windows(wine) + if part.Mountpoint != "C:" { + continue + } + totalSize += u.Total + freeSize += u.Free + usedSize += u.Used + } + return map[string]float64{ + "spaceTotal": utils.Byte2GiB(totalSize), + "freeTotal": utils.Byte2GiB(freeSize), + "usedTotal": utils.Byte2GiB(usedSize), + } +} diff --git a/pkg/osinfo/kernel.go b/pkg/osinfo/kernel.go index 459ba79..13272af 100644 --- a/pkg/osinfo/kernel.go +++ b/pkg/osinfo/kernel.go @@ -1,32 +1,8 @@ package osinfo -import ( - "syscall" - - "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/pkg/utils" - "github.com/zcalusic/sysinfo" -) - type Kernel struct { Sysname string `json:"sysname,omitempty"` Release string `json:"release,omitempty"` Version string `json:"version,omitempty"` Arch string `json:"arch,omitempty"` } - -func (h *System) getKernelInfo() { - - var si sysinfo.SysInfo - si.GetSysInfo() - - var uname syscall.Utsname - if err := syscall.Uname(&uname); err != nil { - panic(err) - } - h.Kernel.Sysname = utils.Byte2String(uname.Sysname[:]) - h.Kernel.Release = si.Kernel.Release - h.Kernel.Version = si.Kernel.Version - h.Kernel.Arch = si.Kernel.Architecture -} - -// REVIEW Windows compatibility diff --git a/pkg/osinfo/kernel_linux.go b/pkg/osinfo/kernel_linux.go new file mode 100644 index 0000000..68de739 --- /dev/null +++ b/pkg/osinfo/kernel_linux.go @@ -0,0 +1,25 @@ +//go:build linux && !windows + +package osinfo + +import ( + "syscall" + + "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/pkg/utils" + "github.com/zcalusic/sysinfo" +) + +func (h *System) getKernelInfo() { + + var si sysinfo.SysInfo + si.GetSysInfo() + + var uname syscall.Utsname + if err := syscall.Uname(&uname); err != nil { + panic(err) + } + h.Kernel.Sysname = utils.Byte2String(uname.Sysname[:]) + h.Kernel.Release = si.Kernel.Release + h.Kernel.Version = si.Kernel.Version + h.Kernel.Arch = si.Kernel.Architecture +} diff --git a/pkg/osinfo/kernel_windows.go b/pkg/osinfo/kernel_windows.go new file mode 100644 index 0000000..e18ef8b --- /dev/null +++ b/pkg/osinfo/kernel_windows.go @@ -0,0 +1,8 @@ +//go:build windows + +package osinfo + +// TODO how to get windows kernel information ? +func (h *System) getKernelInfo() { + +} diff --git a/pkg/osinfo/memory.go b/pkg/osinfo/memory.go index d07431d..38efa6a 100644 --- a/pkg/osinfo/memory.go +++ b/pkg/osinfo/memory.go @@ -1,33 +1,8 @@ package osinfo -import ( - "runtime" - - "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/pkg/utils" - "github.com/shirou/gopsutil/mem" - "github.com/zcalusic/sysinfo" -) - type Memory struct { Type string `json:"type,omitempty"` Speed uint `json:"speed,omitempty"` // RAM data rate in MT/s Total float64 `json:"total,omitempty"` // Total RAM size in GiB Used float64 `json:"used,omitempty"` // Used RAM size in GiB } - -func (h *System) getMemoryInfo() { // TODO also implement swap usage - memInfo, err := mem.VirtualMemory() - utils.Check(err) - h.Memory.Used = utils.Byte2GiB(memInfo.Used) - h.Memory.Total = utils.Byte2GiB(memInfo.Total) - - if runtime.GOOS == "linux" { - var si sysinfo.SysInfo - si.GetSysInfo() - - h.Memory.Type = si.Memory.Type - h.Memory.Speed = si.Memory.Speed - } -} - -// REVIEW Windows compatibility and separate files diff --git a/pkg/osinfo/memory_linux.go b/pkg/osinfo/memory_linux.go new file mode 100644 index 0000000..9ea1f76 --- /dev/null +++ b/pkg/osinfo/memory_linux.go @@ -0,0 +1,22 @@ +//go:build linux && !windows + +package osinfo + +import ( + "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/pkg/utils" + "github.com/shirou/gopsutil/v3/mem" + "github.com/zcalusic/sysinfo" +) + +func (h *System) getMemoryInfo() { // TODO also implement swap usage + var si sysinfo.SysInfo + si.GetSysInfo() + + memInfo, err := mem.VirtualMemory() + utils.Check(err) + + h.Memory.Type = si.Memory.Type + h.Memory.Speed = si.Memory.Speed + h.Memory.Used = utils.Byte2GiB(memInfo.Used) + h.Memory.Total = utils.Byte2GiB(memInfo.Total) +} diff --git a/pkg/osinfo/memory_windows.go b/pkg/osinfo/memory_windows.go new file mode 100644 index 0000000..5059afb --- /dev/null +++ b/pkg/osinfo/memory_windows.go @@ -0,0 +1,16 @@ +//go:build windows + +package osinfo + +import ( + "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/pkg/utils" + "github.com/shirou/gopsutil/v3/mem" +) + +// TODO also implement cached usage +func (h *System) getMemoryInfo() { + memInfo, err := mem.VirtualMemory() + utils.Check(err) + h.Memory.Used = utils.Byte2GiB(memInfo.Used) + h.Memory.Total = utils.Byte2GiB(memInfo.Total) +} diff --git a/pkg/osinfo/node.go b/pkg/osinfo/node.go index d351c38..1580efc 100644 --- a/pkg/osinfo/node.go +++ b/pkg/osinfo/node.go @@ -1,12 +1,5 @@ package osinfo -import ( - "syscall" - - "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/pkg/utils" - "github.com/zcalusic/sysinfo" -) - type Node struct { Domainname string `json:"domainname,omitempty"` Hostname string `json:"hostname,omitempty"` @@ -14,21 +7,3 @@ type Node struct { Hypervisor string `json:"hypervisor,omitempty"` Timezone string `json:"timezone,omitempty"` } - -func (h *System) getNodeInfo() { - var si sysinfo.SysInfo - si.GetSysInfo() - - var uname syscall.Utsname - if err := syscall.Uname(&uname); err != nil { - panic(err) - } - - h.Node.Domainname = utils.Byte2String(uname.Domainname[:]) - h.Node.Hostname = si.Node.Hostname - h.Node.MachineID = si.Node.MachineID - h.Node.Hypervisor = si.Node.Hypervisor - h.Node.Timezone = si.Node.Timezone -} - -// REVIEW Windows compatibility diff --git a/pkg/osinfo/node_linux.go b/pkg/osinfo/node_linux.go new file mode 100644 index 0000000..2f6c183 --- /dev/null +++ b/pkg/osinfo/node_linux.go @@ -0,0 +1,26 @@ +//go:build linux && !windows + +package osinfo + +import ( + "syscall" + + "git.aliberksandikci.com.tr/Liderahenk/ahenk-go/pkg/utils" + "github.com/zcalusic/sysinfo" +) + +func (h *System) getNodeInfo() { + var si sysinfo.SysInfo + si.GetSysInfo() + + var uname syscall.Utsname + if err := syscall.Uname(&uname); err != nil { + panic(err) + } + + h.Node.Domainname = utils.Byte2String(uname.Domainname[:]) + h.Node.Hostname = si.Node.Hostname + h.Node.MachineID = si.Node.MachineID + h.Node.Hypervisor = si.Node.Hypervisor + h.Node.Timezone = si.Node.Timezone +} diff --git a/pkg/osinfo/node_windows.go b/pkg/osinfo/node_windows.go new file mode 100644 index 0000000..001a4bc --- /dev/null +++ b/pkg/osinfo/node_windows.go @@ -0,0 +1,8 @@ +//go:build windows + +package osinfo + +// TODO how to get windows node information +func (h *System) getNodeInfo() { + +} diff --git a/plugins/resources/main.go b/plugins/resources/main.go index dbc8f54..5c976c9 100644 --- a/plugins/resources/main.go +++ b/plugins/resources/main.go @@ -15,7 +15,7 @@ type plug string var ResourcesConnect plug // return instant resource usage information -func (p plug) ResourceUsage() map[string]interface{} { // ANCHOR[id=ResourceUsage] +func (p plug) ResourceUsage() (map[string]interface{}, error) { // ANCHOR[id=ResourceUsage] var system osinfo.System system.GetSystemInfo() @@ -35,14 +35,14 @@ func (p plug) ResourceUsage() map[string]interface{} { // ANCHOR[id=ResourceUsag "Total Disk": system.Disk.Total, "Usage Disk": system.Disk.Used, "Device": system.Disk.Devices, - } + }, nil // see https://github.com/Pardus-LiderAhenk/ahenk/blob/master/src/plugins/resource-usage/resource_info_fetcher.py } // return general Agent system information // // these values changes rarely, see ResourceUsage() function for instant resource usage information -func (p plug) AgentInfo() map[string]interface{} { // ANCHOR[id=AgentInfo] +func (p plug) AgentInfo() (map[string]interface{}, error) { // ANCHOR[id=AgentInfo] var system osinfo.System system.GetSystemInfo() ver, err := os.ReadFile(confdir.Paths.Version) @@ -62,6 +62,6 @@ func (p plug) AgentInfo() map[string]interface{} { // ANCHOR[id=AgentInfo] "DiskSpaceTotal": system.Disk.Total, "MemoryTotal": system.Memory.Total, - } + }, nil // see https://github.com/Pardus-LiderAhenk/ahenk/blob/master/src/plugins/resource-usage/agent_info.py }