overflow_probes/auth/auth.go
crusader d938e396f9 ing
2017-12-02 01:14:22 +09:00

127 lines
2.5 KiB
Go

package auth
import (
"fmt"
"path"
"sync"
cc "git.loafle.net/commons_go/config"
"git.loafle.net/commons_go/logging"
crr "git.loafle.net/commons_go/rpc/registry"
ooccn "git.loafle.net/overflow/overflow_commons_go/config/noauthprobe"
oogwc "git.loafle.net/overflow/overflow_gateway_websocket/client"
"git.loafle.net/overflow/overflow_probes/auth/client"
oopar "git.loafle.net/overflow/overflow_probes/auth/rpc"
"git.loafle.net/overflow/overflow_probes/config"
)
type Auther interface {
EndableStart(doneChan chan<- error) error
Stop()
}
type auth struct {
doneChan chan<- error
cClient oogwc.Client
configPath string
config ooccn.NoAuthProbeConfig
serviceDoneChan chan error
stopChan chan struct{}
stopWg sync.WaitGroup
}
func New() Auther {
a := &auth{}
return a
}
func (a *auth) EndableStart(doneChan chan<- error) error {
if nil != a.stopChan {
logging.Logger().Panic("Auth: auth is already running. Stop it before starting it again")
}
a.configPath = path.Join(*config.ConfigDir, ooccn.ConfigFileName)
conf := cc.New()
if cc.Exists(a.configPath) {
if err := conf.Load(&a.config, a.configPath); nil != err {
return fmt.Errorf("Auth: Loading of NoAuth config file[%s] failed error[%v]", a.configPath, err)
}
}
if nil != a.config.DenyDate {
return fmt.Errorf("Cannot start because this probe have been denied from overFlow at %s", a.config.DenyDate.String())
}
a.serviceDoneChan = make(chan error, 1)
rpcRegistry := crr.NewRPCRegistry()
napService := &oopar.NoAuthProbeService{
DoneChan: a.serviceDoneChan,
ConfigPath: a.configPath,
Config: a.config,
}
rpcRegistry.RegisterService(napService, "")
ch := client.NewClientHandler(rpcRegistry)
sb := client.NewSocketBuilder(napService)
if nil == sb {
return fmt.Errorf("Auth: Cannot create SocketBuilder")
}
a.cClient = client.NewClient(ch, sb)
a.doneChan = doneChan
a.stopChan = make(chan struct{})
a.stopWg.Add(1)
go a.handleAuth()
return nil
}
func (a *auth) Stop() {
a.destroy(nil)
}
func (a *auth) destroy(err error) {
if a.stopChan == nil {
logging.Logger().Warn("Auth: auth must be started before stopping it")
}
close(a.stopChan)
a.stopWg.Wait()
a.stopChan = nil
a.cClient.Close()
close(a.serviceDoneChan)
logging.Logger().Info(fmt.Sprintf("Auth: stopped"))
a.doneChan <- err
}
func (a *auth) handleAuth() {
var err error
defer func() {
a.stopWg.Done()
a.destroy(err)
}()
if err = a.cClient.Connect(); nil != err {
return
}
for {
select {
case err = <-a.serviceDoneChan:
return
case <-a.stopChan:
return
}
}
}