overflow_commons_go/util/executer.go

109 lines
2.2 KiB
Go
Raw Normal View History

2018-03-26 09:40:49 +00:00
package util
import (
"context"
"fmt"
"reflect"
"time"
oocmci "git.loafle.net/overflow/overflow_commons_go/modules/commons/interfaces"
)
func ExecuteStarters(instances []interface{}, targetTypes []reflect.Type, reverse bool) error {
ilen := len(instances)
tlen := len(targetTypes)
if 0 == ilen || 0 == tlen {
return nil
}
if reverse {
2018-03-26 15:15:09 +00:00
for indexI := tlen - 1; indexI >= 0; indexI-- {
2018-03-26 09:40:49 +00:00
if err := executeStarter(instances, targetTypes[indexI]); nil != err {
return err
}
}
} else {
2018-03-26 15:15:09 +00:00
for indexI := 0; indexI < tlen; indexI++ {
2018-03-26 09:40:49 +00:00
if err := executeStarter(instances, targetTypes[indexI]); nil != err {
return err
}
}
}
return nil
}
func executeStarter(instances []interface{}, t reflect.Type) error {
i := findInstanceByType(instances, t)
if nil == i {
return fmt.Errorf("Cannot find instance[%s]", t.String())
}
s, ok := i.(oocmci.Starter)
if !ok {
return fmt.Errorf("Instance is not Starter[%s]", t.String())
}
if err := s.Start(); nil != err {
return err
}
return nil
}
func ExecuteStoppers(instances []interface{}, targetTypes []reflect.Type, reverse bool) error {
ilen := len(instances)
tlen := len(targetTypes)
if 0 == ilen || 0 == tlen {
return nil
}
if reverse {
2018-03-26 15:15:09 +00:00
for indexI := tlen - 1; indexI >= 0; indexI-- {
2018-03-26 09:40:49 +00:00
if err := executeStarter(instances, targetTypes[indexI]); nil != err {
return err
}
}
} else {
2018-03-26 15:15:09 +00:00
for indexI := 0; indexI < tlen; indexI++ {
2018-03-26 09:40:49 +00:00
if err := executeStarter(instances, targetTypes[indexI]); nil != err {
return err
}
}
}
return nil
}
func executeStopper(instances []interface{}, t reflect.Type) error {
i := findInstanceByType(instances, t)
if nil == i {
return fmt.Errorf("Cannot find instance[%s]", t.String())
}
s, ok := i.(oocmci.Stopper)
if !ok {
return fmt.Errorf("Instance is not Stopper[%s]", t.String())
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := s.Stop(ctx); nil != err {
return err
}
return nil
}
func findInstanceByType(instances []interface{}, t reflect.Type) interface{} {
if 0 == len(instances) {
return nil
}
for _, i := range instances {
if reflect.TypeOf(i) == t {
return i
}
}
return nil
}