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 { 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.(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 { 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.(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 }