This commit is contained in:
crusader 2017-09-21 17:38:05 +09:00
parent b1adb63ea8
commit 726b24f878
22 changed files with 568 additions and 156 deletions

150
auth/auth.go Normal file
View File

@ -0,0 +1,150 @@
package auth
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/url"
"path"
lfcc "git.loafle.net/commons_go/config"
"git.loafle.net/commons_go/logging"
"git.loafle.net/overflow/overflow_probes/central/client"
"git.loafle.net/overflow/overflow_probes/commons"
"git.loafle.net/overflow/overflow_probes/config"
)
const (
noAuthConfigFileName = "noauth.json"
noAuthHeaderNoAuthID = "overFlow-NoAuth-ID"
noAuthHeaderNoAuthRegist = "overFlow-NoAuth-Regist"
noAuthHeaderSetNoAuthID = "overFlow-Set-NoAuth-ID"
)
type AuthHandler interface {
commons.Handler
}
type authHandlers struct {
configDir string
noAuthConfigPath string
noAuthConfig config.NoAuthProbeConfig
entryURL string
c client.Client
}
type NoAuthProbe struct {
APIKey string `json:"apiKey"`
Description NoAuthDescription `json:"description"`
}
type NoAuthDescription struct {
Host *Host `json:"host"`
Network *Network `json:"network"`
}
func New(configDir string) AuthHandler {
h := &authHandlers{
configDir: configDir,
}
var err error
var centralURL *url.URL
var noAuthEntryPoint string
var ok bool
if centralURL, err = url.Parse(config.Config.Central.URL); nil != err {
logging.Logger.Error(fmt.Sprintf("Auth: Central URL[%s] is not valid error[%v]", config.Config.Central.URL, err))
return nil
}
if noAuthEntryPoint, ok = config.Config.Central.EntryPoints["noauth"]; !ok {
logging.Logger.Error("Auth: NoAuth entry point of Central is not exist")
return nil
}
centralURL.Path = path.Join(centralURL.Path, noAuthEntryPoint)
h.entryURL = centralURL.String()
h.noAuthConfigPath = path.Join(configDir, noAuthConfigFileName)
conf := lfcc.New()
if lfcc.Exists(h.noAuthConfigPath) {
if err = conf.Load(&h.noAuthConfig, h.noAuthConfigPath); nil != err {
logging.Logger.Error(fmt.Sprintf("Auth: Loading of NoAuth config file[%s] failed error[%v]", h.noAuthConfigPath, err))
}
} else {
if err = lfcc.Save(h.noAuthConfig, h.noAuthConfigPath, true); nil != err {
logging.Logger.Error(fmt.Sprintf("Auth: Saving of NoAuth config file[%s] failed error[%v]", h.noAuthConfigPath, err))
}
}
return h
}
func (h *authHandlers) Start() error {
var err error
isRegist := true
h.c = client.New()
header := http.Header{}
if "" != h.noAuthConfig.TempID {
isRegist = false
header[noAuthHeaderNoAuthID] = []string{h.noAuthConfig.TempID}
} else {
var enc string
if enc, err = h.getRegistHeader(); nil != err {
return err
}
header[noAuthHeaderNoAuthRegist] = []string{enc}
}
var res *http.Response
if res, err = h.c.Dial(h.entryURL, header, 4096, 4096); nil != err {
return err
}
if isRegist {
noAuthID := res.Header.Get(noAuthHeaderSetNoAuthID)
logging.Logger.Debug(fmt.Sprintf("Auth: NoAuthID: %s", noAuthID))
}
return nil
}
func (h *authHandlers) getRegistHeader() (string, error) {
var err error
nap := NoAuthProbe{
APIKey: config.Config.Domain.APIKey,
}
nad := NoAuthDescription{}
nap.Description = nad
if nad.Host, err = getHost(); nil != err {
return "", err
}
if nad.Network, err = getNetwork(); nil != err {
return "", err
}
var buf []byte
if buf, err = json.Marshal(nap); nil != err {
return "", err
}
enc := base64.StdEncoding.EncodeToString(buf)
return enc, nil
}
func (h *authHandlers) listen() {
// 1. regist
// 2. wait for accept auth
}
func (h *authHandlers) Shutdown(ctx context.Context) error {
return nil
}

View File

@ -1 +0,0 @@
package central

294
central/client/client.go Normal file
View File

@ -0,0 +1,294 @@
package client
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"sync"
"git.loafle.net/commons_go/logging"
"git.loafle.net/overflow/overflow_probes/central/client/protocol"
"github.com/gorilla/websocket"
)
const (
ProtocolName = "RPC/1.0"
)
type (
OnNotifyFunc func(params interface{})
)
type ServerError string
func (e ServerError) Error() string {
return string(e)
}
var ErrShutdown = errors.New("connection is shut down")
type Call struct {
Method string // The name of the service and method to call.
Args interface{} // The argument to the function (*struct).
Result interface{} // The reply from the function (*struct).
Error error // After completion, the error status.
Done chan *Call // Strobes when call is complete.
}
func (c *Call) done() {
select {
case c.Done <- c:
// ok
default:
// We don't want to block here. It is the caller's responsibility to make
// sure the channel has enough buffer space. See comment in Go().
logging.Logger.Debug("Client: discarding Call reply due to insufficient Done chan capacity")
}
}
type Client interface {
Dial(url string, header http.Header, readBufSize int, writeBufSize int) (*http.Response, error)
Call(method string, args interface{}, result interface{}) error
Notify(method string, args interface{}) error
OnNotify(method string, cb OnNotifyFunc)
Shutdown(ctx context.Context) error
}
type client struct {
conn *websocket.Conn
sendMutex sync.Mutex
request protocol.Request
notification protocol.Notification
mutex sync.Mutex
requestID uint64
pending map[uint64]*Call
closing bool // user has called Close
shutdown bool // server has told us to stop
onNotifyHandlers map[string][]OnNotifyFunc
}
func New() Client {
c := &client{
requestID: 0,
pending: make(map[uint64]*Call),
onNotifyHandlers: make(map[string][]OnNotifyFunc),
}
return c
}
func (c *client) Dial(url string, header http.Header, readBufSize int, writeBufSize int) (*http.Response, error) {
var err error
var res *http.Response
dialer := websocket.Dialer{
ReadBufferSize: readBufSize,
WriteBufferSize: writeBufSize,
}
if c.conn, res, err = dialer.Dial(url, header); nil != err {
return nil, err
}
go c.input()
return res, nil
}
func (c *client) Call(method string, args interface{}, result interface{}) error {
call := <-c.goCall(method, args, result, make(chan *Call, 1)).Done
return call.Error
}
func (c *client) Notify(method string, args interface{}) error {
c.sendMutex.Lock()
defer c.sendMutex.Unlock()
c.notification.Protocol = ProtocolName
c.notification.Method = method
c.notification.Params = args
if err := c.conn.WriteJSON(c.notification); nil != err {
return err
}
return nil
}
func (c *client) OnNotify(method string, cb OnNotifyFunc) {
var hs []OnNotifyFunc
var ok bool
if hs, ok = c.onNotifyHandlers[method]; !ok {
hs = make([]OnNotifyFunc, 1)
c.onNotifyHandlers[method] = hs
}
hs = append(hs, cb)
}
func (c *client) Shutdown(ctx context.Context) error {
c.mutex.Lock()
if c.closing {
c.mutex.Unlock()
return ErrShutdown
}
c.closing = true
c.mutex.Unlock()
return c.conn.Close()
}
// Go invokes the function asynchronously. It returns the Call structure representing
// the invocation. The done channel will signal when the call is complete by returning
// the same Call object. If done is nil, Go will allocate a new channel.
// If non-nil, done must be buffered or Go will deliberately crash.
func (c *client) goCall(method string, args interface{}, result interface{}, done chan *Call) *Call {
call := new(Call)
call.Method = method
call.Args = args
call.Result = result
if done == nil {
done = make(chan *Call, 10) // buffered.
} else {
// If caller passes done != nil, it must arrange that
// done has enough buffer for the number of simultaneous
// RPCs that will be using that channel. If the channel
// is totally unbuffered, it's best not to run at all.
if cap(done) == 0 {
logging.Logger.Panic("Client: done channel is unbuffered")
}
}
call.Done = done
c.sendCall(call)
return call
}
func (c *client) sendCall(call *Call) {
c.sendMutex.Lock()
defer c.sendMutex.Unlock()
// Register this call.
c.mutex.Lock()
if c.shutdown || c.closing {
call.Error = ErrShutdown
c.mutex.Unlock()
call.done()
return
}
c.requestID++
id := c.requestID
c.pending[id] = call
c.mutex.Unlock()
// Encode and send the request.
c.request.Protocol = ProtocolName
c.request.Method = call.Method
c.request.Params = call.Args
c.request.ID = id
if err := c.conn.WriteJSON(c.request); nil != err {
c.mutex.Lock()
call = c.pending[id]
delete(c.pending, id)
c.mutex.Unlock()
if call != nil {
call.Error = err
call.done()
}
}
}
func (c *client) input() {
var err error
var res protocol.Response
var noti protocol.Notification
var messageType int
var reader io.Reader
for err == nil {
res = protocol.Response{}
if messageType, reader, err = c.conn.NextReader(); nil != err {
break
}
logging.Logger.Debug(fmt.Sprintf("Client: messageType:%d", messageType))
if err = json.NewDecoder(reader).Decode(res); nil != err {
noti = protocol.Notification{}
if err = json.NewDecoder(reader).Decode(noti); nil != err {
break
} else {
err = c.onNotification(noti)
}
} else {
err = c.onResponse(res)
}
}
// Terminate pending calls.
c.sendMutex.Lock()
c.mutex.Lock()
c.shutdown = true
closing := c.closing
if err == io.EOF {
if closing {
err = ErrShutdown
} else {
err = io.ErrUnexpectedEOF
}
}
for _, call := range c.pending {
call.Error = err
call.done()
}
c.mutex.Unlock()
c.sendMutex.Unlock()
if err != io.EOF && !closing {
logging.Logger.Debug(fmt.Sprintf("Client: client protocol error:%v", err))
}
}
func (c *client) onResponse(res protocol.Response) error {
var err error
id := res.ID
c.mutex.Lock()
call := c.pending[id]
delete(c.pending, id)
c.mutex.Unlock()
switch {
case call == nil:
case res.Error != nil:
// We've got an error response. Give this to the request;
// any subsequent requests will get the ReadResponseBody
// error if there is one.
if protocol.ProtocolErrorCodeInternal == res.Error.Code {
if nil != res.Error.Message {
call.Error = ServerError(*res.Error.Message)
}
}
call.done()
default:
if err = json.Unmarshal(*res.Result, call.Result); nil != err {
call.Error = errors.New("reading body " + err.Error())
}
call.done()
}
return err
}
func (c *client) onNotification(noti protocol.Notification) error {
var err error
var hs []OnNotifyFunc
var ok bool
if hs, ok = c.onNotifyHandlers[noti.Method]; ok {
for _, h := range hs {
h(noti.Params)
}
}
return err
}

View File

@ -0,0 +1,5 @@
package protocol
type Header struct {
Protocol string `json:"protocol"`
}

View File

@ -0,0 +1,7 @@
package protocol
type Notification struct {
Header
Method string `json:"method"`
Params interface{} `json:"params,omitempty"`
}

View File

@ -0,0 +1,19 @@
package protocol
type ProtocolErrorCode int
const (
ProtocolErrorCodeParse ProtocolErrorCode = -32700
ProtocolErrorCodeInvalidRequest ProtocolErrorCode = -32600
ProtocolErrorCodeNotFoundMethod ProtocolErrorCode = -32601
ProtocolErrorCodeInvalidParams ProtocolErrorCode = -32602
ProtocolErrorCodeInternal ProtocolErrorCode = -32603
// -32000 ~ -32099
ProtocolErrorCodeServer ProtocolErrorCode = -32000
)
type ProtocolError struct {
Code ProtocolErrorCode `json:"code"`
Message *string `json:"message"`
Data interface{} `json:"data"`
}

View File

@ -0,0 +1,6 @@
package protocol
type Request struct {
Notification
ID uint64 `json:"id,omitempty"`
}

View File

@ -0,0 +1,10 @@
package protocol
import "encoding/json"
type Response struct {
Header
ID uint64 `json:"id"`
Result *json.RawMessage `json:"result,omitempty"`
Error *ProtocolError `json:"error,omitempty"`
}

8
commons/handler.go Normal file
View File

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

View File

@ -1,9 +1,12 @@
{
"domain": {
"apikey": ""
"apikey": "asdfsafsdfsfadsakakdsfladsfgk"
},
"central": {
"url": "ws://192.168.1.50:19190",
"tls": false
"url": "ws://127.0.0.1:19190",
"entryPoints": {
"noauth": "/auth",
"probe": "/probe"
}
}
}

6
config/central.go Normal file
View File

@ -0,0 +1,6 @@
package config
type CentralConfig struct {
URL string `json:"url" yaml:"url" toml:"url"`
EntryPoints map[string]string `json:"entryPoints" yaml:"entryPoints" toml:"entryPoints"`
}

8
config/config.go Normal file
View File

@ -0,0 +1,8 @@
package config
var Config AllConfig
type AllConfig struct {
Domain DomainConfig `json:"domain" yaml:"domain" toml:"domain"`
Central CentralConfig `json:"central" yaml:"central" toml:"central"`
}

5
config/domain.go Normal file
View File

@ -0,0 +1,5 @@
package config
type DomainConfig struct {
APIKey string `json:"apiKey" yaml:"apiKey" toml:"apiKey"`
}

5
config/noauth.go Normal file
View File

@ -0,0 +1,5 @@
package config
type NoAuthProbeConfig struct {
TempID string `json:"tempID" yaml:"tempID" toml:"tempID"`
}

44
main.go
View File

@ -9,8 +9,11 @@ import (
"syscall"
"time"
lfcc "git.loafle.net/commons_go/config"
"git.loafle.net/commons_go/logging"
"git.loafle.net/overflow/overflow_probes/probe"
"git.loafle.net/overflow/overflow_probes/auth"
"git.loafle.net/overflow/overflow_probes/commons"
"git.loafle.net/overflow/overflow_probes/config"
"github.com/takama/daemon"
)
@ -52,11 +55,11 @@ func (d *daemonHandler) Manage() (isRunning bool, status string, err error) {
isRunning = true
if nil != probe.Args.Daemon {
switch *probe.Args.Daemon {
if nil != daemonCommand {
switch *daemonCommand {
case "install":
var runArgs = []string{}
runArgs = append(runArgs, fmt.Sprintf("-config=%s", *probe.Args.ConfigPath))
runArgs = append(runArgs, fmt.Sprintf("-configDir=%s", *configDir))
isRunning = false
status, err = d.Install(runArgs...)
@ -78,6 +81,11 @@ func (d *daemonHandler) Manage() (isRunning bool, status string, err error) {
return
}
var (
daemonCommand *string
configDir *string
)
func init() {
flag.Usage = func() {
fmt.Printf("Usage of %s\n", os.Args[0])
@ -89,11 +97,11 @@ func init() {
command := os.Args[1]
switch command {
case "install", "remove", "start", "stop", "status":
*probe.Args.Daemon = command
*daemonCommand = command
}
}
probe.Args.ConfigPath = flag.String("config", ".", "The path of config")
configDir = flag.String("config-dir", ".", "The directory of config")
flag.Parse()
}
@ -102,7 +110,9 @@ func main() {
var err error
var srv daemon.Daemon
var status string
var handler commons.Handler
isRunning := true
var confDir string
defer logging.Logger.Sync()
@ -111,6 +121,19 @@ func main() {
fmt.Printf("URL: %s\n", website)
fmt.Println()
if dir, err := lfcc.ABSPathify(*configDir); nil != err {
logging.Logger.Panic(fmt.Sprintf("Probe: config path[%s] is not valid", *configDir))
} else {
logging.Logger.Debug(fmt.Sprintf("Probe: config path[%s]", dir))
confDir = dir
}
conf := lfcc.New()
conf.SetConfigPath(*configDir)
if err := conf.Load(&config.Config, "config.json"); nil != err {
logging.Logger.Panic(fmt.Sprintf("Probe: config is not valid error[%v]", err))
}
if srv, err = daemon.New(serviceName, serviceDescription); nil != err {
logging.Logger.Panic(fmt.Sprintf("Probe: %v", err))
}
@ -126,12 +149,11 @@ func main() {
os.Exit(0)
}
// // Do something, call your goroutines, etc
p := probe.New()
handler = auth.New(confDir)
go func() {
if err := p.Start(); err != nil {
logging.Logger.Error(fmt.Sprintf("Probe: cannot start probe error: %v", err))
if err := handler.Start(); err != nil {
logging.Logger.Error(fmt.Sprintf("Probe: cannot start authenticator error: %v", err))
}
}()
@ -150,7 +172,7 @@ func main() {
<-interrupt
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := p.Shutdown(ctx); err != nil {
if err := handler.Shutdown(ctx); err != nil {
logging.Logger.Error(fmt.Sprintf("Probe: status[%s] error: %v", status, err))
}

1
noauth.json Normal file
View File

@ -0,0 +1 @@
{"tempID":""}

View File

@ -1,63 +0,0 @@
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

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

View File

@ -1,22 +0,0 @@
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) {
}

View File

@ -2,21 +2,12 @@ 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{}
func New(configDir string) Probe {
p := &probe{
configDir: configDir,
}
return p
}
@ -27,22 +18,10 @@ type Probe interface {
}
type probe struct {
handler handler.Handler
probeConfig config.Configurator
configDir string
}
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
}
@ -51,25 +30,3 @@ 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
}