commons-go/core/util/executer.go

109 lines
2.2 KiB
Go
Raw Normal View History

2018-04-12 09:38:04 +00:00
package util
import (
"context"
"fmt"
"reflect"
"time"
"git.loafle.net/overflow/commons-go/core/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 {
for indexI := tlen - 1; indexI >= 0; indexI-- {
if err := executeStarter(instances, targetTypes[indexI]); nil != err {
return err
}
}
} else {
for indexI := 0; indexI < tlen; indexI++ {
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.(interfaces.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 {
for indexI := tlen - 1; indexI >= 0; indexI-- {
if err := executeStarter(instances, targetTypes[indexI]); nil != err {
return err
}
}
} else {
for indexI := 0; indexI < tlen; indexI++ {
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.(interfaces.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
}