From b1adb63ea86f4dd7e4eb3d9306ff333b2c9d807f Mon Sep 17 00:00:00 2001 From: crusader Date: Mon, 18 Sep 2017 18:21:58 +0900 Subject: [PATCH] ing --- .gitignore | 68 ++++++++++ .vscode/launch.json | 32 +++++ .vscode/settings.json | 3 + central/client.go | 1 + config.json | 9 ++ glide.yaml | 11 ++ logging.json | 27 ++++ main.go | 179 +++++++++++++++++++++++++++ probe.json | 3 + probe/handler/auth/auth_handler.go | 63 ++++++++++ probe/handler/auth/host.go | 32 +++++ probe/handler/auth/network.go | 64 ++++++++++ probe/handler/handler.go | 8 ++ probe/handler/probe/probe_handler.go | 22 ++++ probe/probe.go | 75 +++++++++++ 15 files changed, 597 insertions(+) create mode 100644 .gitignore create mode 100644 .vscode/launch.json create mode 100644 .vscode/settings.json create mode 100644 central/client.go create mode 100644 config.json create mode 100644 glide.yaml create mode 100644 logging.json create mode 100644 main.go create mode 100644 probe.json create mode 100644 probe/handler/auth/auth_handler.go create mode 100644 probe/handler/auth/host.go create mode 100644 probe/handler/auth/network.go create mode 100644 probe/handler/handler.go create mode 100644 probe/handler/probe/probe_handler.go create mode 100644 probe/probe.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3733e36 --- /dev/null +++ b/.gitignore @@ -0,0 +1,68 @@ +# Created by .ignore support plugin (hsz.mobi) +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.xml +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties +### Go template +# Binaries for programs and plugins +*.exe +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 +.glide/ +.idea/ +*.iml + +vendor/ +glide.lock +.DS_Store +dist/ +debug diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..2ca2b1d --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,32 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Debug", + "type": "go", + "request": "launch", + "mode": "debug", + "remotePath": "", + "port": 2345, + "host": "127.0.0.1", + "program": "${workspaceRoot}/main.go", + "env": {}, + "args": [], + "showLog": true + }, + { + "name": "File Debug", + "type": "go", + "request": "launch", + "mode": "debug", + "remotePath": "", + "port": 2345, + "host": "127.0.0.1", + "program": "${fileDirname}", + "env": {}, + "args": [], + "showLog": true + } + + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..20af2f6 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +// Place your settings in this file to overwrite default and user settings. +{ +} \ No newline at end of file diff --git a/central/client.go b/central/client.go new file mode 100644 index 0000000..4df274a --- /dev/null +++ b/central/client.go @@ -0,0 +1 @@ +package central diff --git a/config.json b/config.json new file mode 100644 index 0000000..c26389a --- /dev/null +++ b/config.json @@ -0,0 +1,9 @@ +{ + "domain": { + "apikey": "" + }, + "central": { + "url": "ws://192.168.1.50:19190", + "tls": false + } +} \ No newline at end of file diff --git a/glide.yaml b/glide.yaml new file mode 100644 index 0000000..61be519 --- /dev/null +++ b/glide.yaml @@ -0,0 +1,11 @@ +package: git.loafle.net/overflow/overflow_probes +import: +- package: git.loafle.net/commons_go/config +- package: git.loafle.net/commons_go/logging +- package: github.com/gorilla/websocket + version: v1.2.0 +- package: git.loafle.net/commons_go/util +- package: github.com/shirou/gopsutil + version: v2.17.08 +- package: github.com/takama/daemon + version: 0.9.1 diff --git a/logging.json b/logging.json new file mode 100644 index 0000000..bfe748f --- /dev/null +++ b/logging.json @@ -0,0 +1,27 @@ +{ + "level": "debug", + "development": true, + "disableCaller": true, + "disableStacktrace": true, + "sampling": { + "initial": 100, + "thereafter": 100 + }, + "encoding": "console", + "encoderConfig": { + "messageKey": "message", + "levelKey": "level", + "timeKey": "time", + "nameKey": "name", + "callerKey": "caller", + "stacktraceKey": "stacktrace", + "lineEnding": "\n", + "levelEncoder": "color", + "timeEncoder": "ISO8601", + "durationEncoder": "string", + "callerEncoder": "full", + "nameEncoder": "full" + }, + "outputPaths": ["stdout", "/tmp/logs"], + "errorOutputPaths": ["stderr"] +} \ No newline at end of file diff --git a/main.go b/main.go new file mode 100644 index 0000000..e6117a7 --- /dev/null +++ b/main.go @@ -0,0 +1,179 @@ +package main + +import ( + "context" + "flag" + "fmt" + "os" + "os/signal" + "syscall" + "time" + + "git.loafle.net/commons_go/logging" + "git.loafle.net/overflow/overflow_probes/probe" + "github.com/takama/daemon" +) + +const ( + version = "1.0.0" + website = "https://www.overflow.cloud" + banner = ` + + ██████╗ ██╗ ██╗███████╗██████╗ ███████╗██╗ ██████╗ ██╗ ██╗ +██╔═══██╗██║ ██║██╔════╝██╔══██╗██╔════╝██║ ██╔═══██╗██║ ██║ +██║ ██║██║ ██║█████╗ ██████╔╝█████╗ ██║ ██║ ██║██║ █╗ ██║ +██║ ██║╚██╗ ██╔╝██╔══╝ ██╔══██╗██╔══╝ ██║ ██║ ██║██║███╗██║ +╚██████╔╝ ╚████╔╝ ███████╗██║ ██║██║ ███████╗╚██████╔╝╚███╔███╔╝ + ╚═════╝ ╚═══╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚══════╝ ╚═════╝ ╚══╝╚══╝ + +` +) + +const ( + // name of the service + serviceName = "Probe" + serviceDescription = "Probe Service of overFlow" +) + +type daemonHandler struct { + daemon.Daemon +} + +// Manage by daemon commands or run the daemon +// cmd install -config=./path +// cmd install +// cmd remove +// cmd start +// cmd stop +// cmd status +// cmd -config=./path +// cmd +func (d *daemonHandler) Manage() (isRunning bool, status string, err error) { + + isRunning = true + + if nil != probe.Args.Daemon { + switch *probe.Args.Daemon { + case "install": + var runArgs = []string{} + runArgs = append(runArgs, fmt.Sprintf("-config=%s", *probe.Args.ConfigPath)) + + isRunning = false + status, err = d.Install(runArgs...) + case "remove": + isRunning = false + status, err = d.Remove() + case "start": + isRunning = false + status, err = d.Start() + case "stop": + isRunning = false + status, err = d.Stop() + case "status": + isRunning = false + status, err = d.Status() + } + } + + return +} + +func init() { + flag.Usage = func() { + fmt.Printf("Usage of %s\n", os.Args[0]) + fmt.Printf(" [install | remove | start | stop | status]\n") + flag.PrintDefaults() + } + + if len(os.Args) > 1 { + command := os.Args[1] + switch command { + case "install", "remove", "start", "stop", "status": + *probe.Args.Daemon = command + } + } + + probe.Args.ConfigPath = flag.String("config", ".", "The path of config") + flag.Parse() + +} + +func main() { + var err error + var srv daemon.Daemon + var status string + isRunning := true + + defer logging.Logger.Sync() + + fmt.Println(banner) + fmt.Printf("Version: %s\n", version) + fmt.Printf("URL: %s\n", website) + fmt.Println() + + if srv, err = daemon.New(serviceName, serviceDescription); nil != err { + logging.Logger.Panic(fmt.Sprintf("Probe: %v", err)) + } + + s := &daemonHandler{srv} + if isRunning, status, err = s.Manage(); nil != err { + logging.Logger.Error(fmt.Sprintf("Probe: status[%s] error: %v", status, err)) + os.Exit(1) + } + + if !isRunning { + logging.Logger.Info(fmt.Sprintf("Probe: status[%s]", status)) + os.Exit(0) + } + + // // Do something, call your goroutines, etc + p := probe.New() + + go func() { + if err := p.Start(); err != nil { + logging.Logger.Error(fmt.Sprintf("Probe: cannot start probe error: %v", err)) + } + }() + + // // Set up channel on which to send signal notifications. + // // We must use a buffered channel or risk missing the signal + // // if we're not ready to receive when the signal is sent. + interrupt := make(chan os.Signal, 1) + signal.Notify(interrupt, + syscall.SIGKILL, + syscall.SIGSTOP, + syscall.SIGHUP, + syscall.SIGINT, + syscall.SIGTERM, + syscall.SIGQUIT) + + <-interrupt + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := p.Shutdown(ctx); err != nil { + logging.Logger.Error(fmt.Sprintf("Probe: status[%s] error: %v", status, err)) + } + + // // loop work cycle with accept connections or interrupt + // // by system signal + // ListenLoop: + // for { + // select { + // case s := <-interrupt: + // logging.Logger.Info(fmt.Sprintf("Probe: signal[%v]", s)) + // ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + // defer cancel() + // if err := p.Shutdown(ctx); err != nil { + // logging.Logger.Error(fmt.Sprintf("Probe: status[%s] error: %v", status, err)) + // } + + // if s == os.Interrupt { + // logging.Logger.Info("Probe was interruped by system signal") + // } else { + // logging.Logger.Info("Probe was killed") + // } + // break ListenLoop + // } + // } + +} diff --git a/probe.json b/probe.json new file mode 100644 index 0000000..2d9b595 --- /dev/null +++ b/probe.json @@ -0,0 +1,3 @@ +{ + "id": "" +} \ No newline at end of file diff --git a/probe/handler/auth/auth_handler.go b/probe/handler/auth/auth_handler.go new file mode 100644 index 0000000..4e8e5d9 --- /dev/null +++ b/probe/handler/auth/auth_handler.go @@ -0,0 +1,63 @@ +package auth + +import ( + "context" + "encoding/json" + "fmt" + + "git.loafle.net/commons_go/logging" + "git.loafle.net/overflow/overflow_probes/probe/handler" + + "github.com/gorilla/websocket" +) + +type AuthHandler interface { + handler.Handler +} + +type authHandlers struct { + c *websocket.Conn + apiKey *string + tempKey *string +} + +type NoAuthProbe struct { + Host *Host `json:"host"` + Network *Network `json:"network"` +} + +func NewHandler() AuthHandler { + h := &authHandlers{} + return h +} + +func (h *authHandlers) Start() { + // c, _, err := websocket.DefaultDialer.Dial("ws://192.168.1.50:19190/auth", nil) + // if err != nil { + // logging.Logger.Fatal(fmt.Sprintf("auth: %v", err)) + // } + // h.c = c + p := &NoAuthProbe{} + + if h, err := getHost(); nil == err { + p.Host = h + } + + if n, err := getNetwork(); nil == err { + p.Network = n + } + + if buf, err := json.Marshal(*p); nil == err { + logging.Logger.Debug(fmt.Sprintf("p: %s", string(buf))) + } + +} + +func (h *authHandlers) listen() { + // 1. regist + // 2. wait for accept auth +} + +func (h *authHandlers) Shutdown(ctx context.Context) { + +} diff --git a/probe/handler/auth/host.go b/probe/handler/auth/host.go new file mode 100644 index 0000000..a49d3db --- /dev/null +++ b/probe/handler/auth/host.go @@ -0,0 +1,32 @@ +package auth + +import ( + "github.com/shirou/gopsutil/host" +) + +type Host struct { + Name string `json:"name"` + OS string `json:"os"` + Platform string `json:"paltform"` + PlatformFamily string `json:"platformFamily"` + PlatformVersion string `json:"platformVersion"` + KernelVersion string `json:"kernelVersion"` + HostID string `json:"hostID"` +} + +func getHost() (*Host, error) { + h := &Host{} + + if i, err := host.Info(); nil == err { + h.Name = i.Hostname + h.OS = i.OS + h.Platform = i.Platform + h.PlatformFamily = i.PlatformFamily + h.KernelVersion = i.KernelVersion + h.HostID = i.HostID + } else { + return nil, err + } + + return h, nil +} diff --git a/probe/handler/auth/network.go b/probe/handler/auth/network.go new file mode 100644 index 0000000..b1ee26a --- /dev/null +++ b/probe/handler/auth/network.go @@ -0,0 +1,64 @@ +package auth + +import ( + "bytes" + "net" + + "git.loafle.net/commons_go/util/net/gateway" +) + +type Network struct { + Name string `json:"name"` + Address string `json:"address"` + Gateway string `json:"gateway"` + MacAddress string `json:"macAddress"` +} + +func getNetwork() (*Network, error) { + var ip net.IP + var iface string + var err error + if ip, iface, err = gateway.DiscoverGateway(); nil != err { + return nil, err + } + + interfaces, err := net.Interfaces() + if err != nil { + return nil, err + } + + idx := -1 + + for _idx, i := range interfaces { + if i.Name == iface { + idx = _idx + break + } + } + + if -1 == idx { + return nil, nil + } + + n := &Network{} + i := interfaces[idx] + + n.Name = i.Name + n.MacAddress = i.HardwareAddr.String() + n.Gateway = ip.String() + + if addrs, err := i.Addrs(); nil == err { + var buffer bytes.Buffer + for _idx, a := range addrs { + if 0 < _idx { + buffer.WriteString("|") + } + buffer.WriteString(a.String()) + } + n.Address = buffer.String() + } else { + return nil, err + } + + return n, nil +} diff --git a/probe/handler/handler.go b/probe/handler/handler.go new file mode 100644 index 0000000..7bcf09f --- /dev/null +++ b/probe/handler/handler.go @@ -0,0 +1,8 @@ +package handler + +import "context" + +type Handler interface { + Start() + Shutdown(ctx context.Context) +} diff --git a/probe/handler/probe/probe_handler.go b/probe/handler/probe/probe_handler.go new file mode 100644 index 0000000..1c625be --- /dev/null +++ b/probe/handler/probe/probe_handler.go @@ -0,0 +1,22 @@ +package handler + +import ( + "context" + + "git.loafle.net/overflow/overflow_probes/probe/handler" +) + +type ProbeHandler interface { + handler.Handler +} + +type probeHandlers struct { +} + +func (h *probeHandlers) Start() { + +} + +func (h *probeHandlers) Shutdown(ctx context.Context) { + +} diff --git a/probe/probe.go b/probe/probe.go new file mode 100644 index 0000000..4c89efc --- /dev/null +++ b/probe/probe.go @@ -0,0 +1,75 @@ +package probe + +import ( + "context" + + "git.loafle.net/commons_go/config" + "git.loafle.net/overflow/overflow_probes/probe/handler" + "git.loafle.net/overflow/overflow_probes/probe/handler/auth" +) + +type Arguments struct { + Daemon *string + ConfigPath *string +} + +var Args Arguments + +func New() Probe { + p := &probe{} + + return p +} + +type Probe interface { + Start() error + Shutdown(ctx context.Context) error +} + +type probe struct { + handler handler.Handler + probeConfig config.Configurator +} + +func (p *probe) Start() error { + // conf := loadConfig(*configPath) + probeConf := loadProbeConfig(*Args.ConfigPath) + + probeID := probeConf.GetString("id") + + if "" == probeID { + a := auth.NewHandler() + a.Start() + } else { + + } + + return nil +} + +func (p *probe) Shutdown(ctx context.Context) error { + + return nil +} + +func loadConfig(path string) config.Configurator { + conf := config.New() + conf.SetConfigName("config") + conf.AddConfigPath(path) + err := conf.ReadInConfig() + if nil != err { + panic(err) + } + return conf +} + +func loadProbeConfig(path string) config.Configurator { + conf := config.New() + conf.SetConfigName("probe") + conf.AddConfigPath(path) + err := conf.ReadInConfig() + if nil != err { + panic(err) + } + return conf +}