This commit is contained in:
crusader 2017-09-18 18:21:58 +09:00
commit b1adb63ea8
15 changed files with 597 additions and 0 deletions

68
.gitignore vendored Normal file
View File

@ -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

32
.vscode/launch.json vendored Normal file
View File

@ -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
}
]
}

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
// Place your settings in this file to overwrite default and user settings.
{
}

1
central/client.go Normal file
View File

@ -0,0 +1 @@
package central

9
config.json Normal file
View File

@ -0,0 +1,9 @@
{
"domain": {
"apikey": ""
},
"central": {
"url": "ws://192.168.1.50:19190",
"tls": false
}
}

11
glide.yaml Normal file
View File

@ -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

27
logging.json Normal file
View File

@ -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"]
}

179
main.go Normal file
View File

@ -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
// }
// }
}

3
probe.json Normal file
View File

@ -0,0 +1,3 @@
{
"id": ""
}

View File

@ -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) {
}

View File

@ -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
}

View File

@ -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
}

8
probe/handler/handler.go Normal file
View File

@ -0,0 +1,8 @@
package handler
import "context"
type Handler interface {
Start()
Shutdown(ctx context.Context)
}

View File

@ -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) {
}

75
probe/probe.go Normal file
View File

@ -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
}