Esempio n. 1
0
func (serviceManager *ServiceManager) Stop(name ...string) error {
	serviceManager.Lock()
	defer serviceManager.Unlock()

	services := new(ServiceContainer)

	if len(name) > 0 {
		for i := 0; i < serviceManager.container.Len(); i++ {
			el := serviceManager.container.Get(i)
			if util.InStrings(el.service.GetName(), name) {
				services.Push(el)
			}
		}
	} else {
		services = serviceManager.container
	}

	sort.Sort(services)
	sort.Sort(sort.Reverse(services))
	for i := 0; i < services.Len(); i++ {
		e := services.Get(i).service
		if e.GetStatus() != STATUS_STARTED {
			continue
		}

		//  服务关闭事件
		evt := event.NewEvt(EVENT_BEFORE_STOP)
		evt.SetParams(e)
		evt.SetTarget(serviceManager)
		ev, err := event.EvtManager.Trigger(evt)
		if err != nil {
			params, ok := ev.GetParams().(*Service)
			if ok {
				e = params
			}
		}

		e.Stop()

		// 关闭完成事件,异步事件
		evt = event.NewEvt(EVENT_AFTER_STOPED)
		evt.SetParams(e)
		evt.SetTarget(serviceManager)
		event.EvtManager.AsyncTrigger(evt)
	}

	serviceManager.Wait()
	return nil
}
Esempio n. 2
0
// 启动所有服务
// 如果传入name那么针对指定服务进行启动
func (serviceManager *ServiceManager) Start(name ...string) error {
	serviceManager.Lock()
	defer serviceManager.Unlock()

	services := new(ServiceContainer)
	if len(name) > 0 {
		for i := 0; i < serviceManager.container.Len(); i++ {
			el := serviceManager.container.Get(i)
			if util.InStrings(el.service.GetName(), name) {
				services.Push(el)
			}
		}
	} else {
		services = serviceManager.container
	}

	sort.Sort(services)
	c := make(chan NOTIFY)
	for i := 0; i < services.Len(); i++ {
		e := services.Get(i).service
		if e.GetStatus() != STATUS_STOPED {
			continue
		}

		//  服务启动事件
		evt := event.NewEvt(EVENT_BEFORE_START)
		evt.SetParams(e)
		evt.SetTarget(serviceManager)
		ev, err := event.EvtManager.Trigger(evt)
		if err != nil {
			params, ok := ev.GetParams().(*Service)
			if ok {
				e = params
			}
		}

		// 注册监听事件
		e.Notify(c, NOTIFY_STARTED)
		serviceManager.Add(1)
		go func(s *Service) {
			defer serviceManager.Done()
			err := s.Start()
			if err != nil {
				log.Panicf("Start service: %s fail.%v", s.GetName(), err)
			}
		}(e)

		// timeout
		select {
		case <-c:
		case <-time.After(time.Second * 30):
			// Maximum execution time of 30 seconds exceeded
			log.Panicf("Start %s timeout", e.GetName())
		}

		e.StopNotify(c)

		// 启动完成事件,异步事件
		evt = event.NewEvt(EVENT_AFTER_STARTED)
		evt.SetParams(e)
		evt.SetTarget(serviceManager)
		event.EvtManager.AsyncTrigger(evt)
	}

	close(c)
	return nil
}