コード例 #1
0
ファイル: service.go プロジェクト: ClarityServices/skynet2
// Wraps your custom service in Skynet
func CreateService(sd ServiceDelegate, si *skynet.ServiceInfo) (s *Service) {
	s = &Service{
		Delegate:       sd,
		ServiceInfo:    si,
		methods:        make(map[string]reflect.Value),
		connectionChan: make(chan *net.TCPConn),
		registeredChan: make(chan bool),
		shutdownChan:   make(chan bool),
		ClientInfo:     make(map[string]ClientInfo),
		shuttingDown:   false,
	}

	// Override LogLevel for Service
	if l, err := config.String(s.Name, s.Version, "log.level"); err != nil {
		log.SetLogLevel(log.LevelFromString(l))
	}

	logWriter := log.NewMultiWriter()

	if logStdout, err := config.Bool(s.Name, s.Version, "service.log.stdout"); err == nil {
		if logStdout {
			logWriter.AddWriter(os.Stdout)
		}
	} else {
		// Stdout is enabled by default
		logWriter.AddWriter(os.Stdout)
	}

	if logFile, err := config.String(s.Name, s.Version, "service.log.file"); err == nil {
		f, err := os.OpenFile(logFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)

		if err != nil {
			log.Fatal("Failed to open log file: ", logFile, err)
		}

		logWriter.AddWriter(f)
	}

	log.SetOutput(logWriter)

	// the main rpc server
	s.RPCServ = rpc.NewServer()
	rpcForwarder := NewServiceRPC(s)
	s.RPCServ.RegisterName(si.Name, rpcForwarder)

	// Daemon doesn't accept commands over pipe
	if si.Name != "SkynetDaemon" {
		// Listen for admin requests
		go s.serveAdminRequests()
	}

	return
}
コード例 #2
0
ファイル: service.go プロジェクト: ClarityServices/skynet2
// Starts your skynet service, including binding to ports. Optionally register for requests at the same time. Returns a sync.WaitGroup that will block until all requests have finished
func (s *Service) Start() (done *sync.WaitGroup) {
	bindWait := &sync.WaitGroup{}

	bindWait.Add(1)
	go s.listen(s.ServiceAddr, bindWait)

	// Watch signals for shutdown
	c := make(chan os.Signal, 1)
	go watchSignals(c, s)

	s.doneChan = make(chan bool, 1)

	// We must block here, we don't want to register, until we've actually bound to an ip:port
	bindWait.Wait()

	s.doneGroup = &sync.WaitGroup{}
	s.doneGroup.Add(1)

	go func() {
		s.mux()
		s.doneGroup.Done()
	}()
	done = s.doneGroup

	if r, err := config.Bool(s.Name, s.Version, "service.register"); err == nil {
		s.Registered = r
	}

	err := skynet.GetServiceManager().Add(*s.ServiceInfo)
	if err != nil {
		log.Println(log.ERROR, "Failed to add service: "+err.Error())
	}

	if s.Registered {
		s.Register()
	}

	go s.Delegate.Started(s) // Call user defined callback

	if s.ServiceInfo.Registered {
		go s.Delegate.Registered(s) // Call user defined callback
	}

	return
}