예제 #1
0
func (s *Server) SetupInjector(inj *inject.Injector, name string) {
	cname := name
	if s.ServerConfig.Name != "" {
		cname = s.ServerConfig.Name + "/" + name
	}
	c := sarif.NewClient(cname)
	c.Connect(s.Broker.NewLocalConn())
	c.SetLogger(s.Log)

	inj.Instance(s.Broker)
	inj.Factory(func() sarif.Conn {
		return s.Broker.NewLocalConn()
	})
	inj.Factory(func() *sarif.Client {
		return c
	})
	inj.Factory(func() services.Config {
		if !s.configStoreInitialized {
			return s.Config.Section(name)
		}
		cfg := config.NewConfigStore(c)
		cfg.Store.StoreName = s.ServerConfig.ConfigStore
		cfg.ConfigDir = s.Config.Dir()
		return cfg
	})
}
예제 #2
0
파일: web.go 프로젝트: sarifsystems/sarif
func (s *Server) getApiClientByName(name string) *sarif.Client {
	client, ok := s.apiClients[name]
	if !ok {
		client = sarif.NewClient("web/" + name)
		client.Connect(s.Broker.NewLocalConn())
		s.apiClients[name] = client
	}
	return client
}
예제 #3
0
파일: xmpp.go 프로젝트: sarifsystems/sarif
func (c *Client) newConversation(remote string) *conversation {
	user := xmpp.RemoveResourceFromJid(remote)
	client := sarif.NewClient("xmpp/" + user)
	client.Connect(c.Broker.NewLocalConn())
	cv := &conversation{
		Remote: remote,
		Proto:  client,
		Xmpp:   c,
	}
	if err := client.Subscribe("", "self", cv.handleProtoMessage); err != nil {
		c.Log.Errorln("[xmpp] new:", err)
	}
	c.conversations[user] = cv
	return cv
}
예제 #4
0
파일: main.go 프로젝트: sarifsystems/sarif
func main() {
	addr := "tcp://localhost:23100"
	if len(os.Args) > 1 {
		addr = os.Args[1]
	}
	fmt.Println("connecting to", addr)

	// Setup our client.
	client := sarif.NewClient("sarifping")
	err := client.Dial(&sarif.NetConfig{
		Address: addr,
	})
	if err != nil {
		log.Fatal(err)
	}
	pings := make(map[string]time.Time)

	// Subscribe to all acknowledgements to our pings
	// and print them.
	client.Subscribe("ack", "self", func(msg sarif.Message) {
		if !msg.IsAction("ack") {
			return
		}
		sent, ok := pings[msg.CorrId]
		if !ok {
			return
		}

		fmt.Printf("%s from %s: time=%.1fms\n",
			msg.Action,
			msg.Source,
			time.Since(sent).Seconds()*1e3,
		)
	})

	// Every second, send a ping to all devices.
	for _ = range time.Tick(1 * time.Second) {
		// Create the ping message and publish it on the network
		msg := sarif.Message{
			Id:     sarif.GenerateId(),
			Action: "ping",
		}
		if err := client.Publish(msg); err != nil {
			log.Fatal(err)
		}
		pings[msg.Id] = time.Now()
	}
}
예제 #5
0
func (s *Server) instantiate(m *services.Module) (interface{}, error) {
	inj := inject.NewInjector()
	inj.Instance(s.Broker)
	inj.Factory(func() services.Config {
		return nullConfig{}
	})
	inj.Factory(func() sarif.Conn {
		return s.Broker.NewLocalConn()
	})
	inj.Factory(func() *sarif.Client {
		c := sarif.NewClient("js/" + m.Name)
		c.Connect(s.Broker.NewLocalConn())
		return c
	})
	return inj.Create(m.NewInstance)
}
예제 #6
0
func ExampleClient() {
	recv := make(chan bool)

	// Hosting a broker
	broker := sarif.NewBroker()
	go broker.Listen(&sarif.NetConfig{
		Address: "tcp://localhost:5698",
		Auth:    sarif.AuthNone,
	})
	time.Sleep(10 * time.Millisecond)

	// Setup client and listen for "testaction"
	client := sarif.NewClient("mytestdevice")
	err := client.Dial(&sarif.NetConfig{
		Address: "tcp://localhost:5698",
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	client.Subscribe("testaction", "", func(msg sarif.Message) {
		fmt.Printf("received %q from %q\n", msg.Action, msg.Source)

		var payload MyPayload
		msg.DecodePayload(&payload)
		fmt.Println("payload:", payload.Value)
		recv <- true
	})

	// Publish a "testaction" message
	client.Publish(sarif.CreateMessage("testaction", MyPayload{"weee, a test message!"}))

	// Block until message received or timeout
	select {
	case <-recv:
	case <-time.After(time.Second):
	}

	// Output:
	// received "testaction" from "mytestdevice"
	// payload: weee, a test message!
}
예제 #7
0
func TestSpec(t *testing.T) {
	srv := server.New("sarif", "temp")
	srv.Log.SetLevel(core.LogLevelWarn)

	srv.RegisterModule(events.Module)
	srv.RegisterModule(location.Module)
	srv.RegisterModule(lua.Module)
	srv.RegisterModule(natural.Module)
	srv.RegisterModule(scheduler.Module)
	srv.RegisterModule(store.Module)

	srv.ServerConfig.Name = "myserver"
	srv.ServerConfig.EnabledModules = []string{
		"events",
		"location",
		"lua",
		"natural",
		"scheduler",
		"store",
	}
	srv.Init()
	// srv.Log.SetLevel(core.LogLevelTrace)
	// srv.Broker.TraceMessages(true)

	c := sarif.NewClient("testservice")
	c.Connect(srv.Broker.NewLocalConn())
	c.SetLogger(srv.Log)

	for _, tst := range runTests {
		tr := NewTestRunner(t)
		tr.UseConn(srv.Broker.NewLocalConn())
		tr.Wait()

		convey.Convey("Test module '"+tst.Name+"'", t, func() {
			tst.Func(tr)
		})
	}

	srv.Close()
}
예제 #8
0
파일: app.go 프로젝트: sarifsystems/sarif
func (app *App) ClientDial(ci sarif.ClientInfo) (*sarif.Client, error) {
	cfg := sarif.NetConfig{
		Address: "tcp://localhost:" + sarif.DefaultPort,
	}
	app.Config.Get("dial", &cfg)
	app.WriteConfig()

	c := sarif.NewClient(ci.Name)
	c.Info = ci
	c.OnConnectionLost(func(err error) {
		app.Log.Errorln("connection lost:", err)
		for {
			time.Sleep(5 * time.Second)
			if err := c.Dial(&cfg); err == nil {
				app.Log.Println("reconnected")
				return
			}
		}
	})

	err := c.Dial(&cfg)
	return c, err
}
예제 #9
0
func (s *Service) createMachine(name string) (*Machine, error) {
	if name == "" {
		name = sarif.GenerateId()
	}
	if _, ok := s.Machines[name]; ok {
		return nil, errors.New("Machine " + name + " already exists")
	}

	c := sarif.NewClient(s.DeviceId + "/" + name)
	c.Connect(s.Broker.NewLocalConn())

	m := NewMachine(c)
	s.Machines[name] = m
	if listeners, ok := s.Listeners[name]; ok {
		for _, l := range listeners {
			m.Attach(l)
		}
	}
	if err := m.Enable(); err != nil {
		return m, err
	}
	return m, nil
}
예제 #10
0
func (s *Server) InitBroker() error {
	if s.Broker != nil {
		return nil
	}

	sarif.SetDefaultLogger(s.Log)
	s.Broker = sarif.NewBroker()
	if s.Log.GetLevel() <= core.LogLevelTrace {
		s.Broker.TraceMessages(true)
	}

	s.Client = sarif.NewClient(s.ServerConfig.Name + "/sarifd")
	s.Client.Connect(s.Broker.NewLocalConn())
	s.Client.SetLogger(s.Log)

	cfg := &s.ServerConfig
	if _, ok := s.Config.Get("server", cfg); !ok {
		if len(cfg.Listen) == 0 {
			cfg.Listen = append(cfg.Listen, &sarif.NetConfig{
				Address: "tcp://localhost:23100",
				Auth:    sarif.AuthNone,
			})
			s.Config.Set("server", cfg)
		}
	}

	// Listen on connections
	for _, cfg := range cfg.Listen {
		go func(cfg *sarif.NetConfig) {
			s.Log.Infoln("[server] listening on", cfg.Address)
			s.Must(s.Broker.Listen(cfg))
		}(cfg)
	}

	// Setup bridges
	for _, cfg := range cfg.Bridges {
		go func(cfg *sarif.NetConfig) {
			for {
				s.Log.Infoln("[server] bridging to ", cfg.Address)
				conn, err := sarif.Dial(cfg)
				if err == nil {
					err = s.Broker.ListenOnBridge(conn)
				}
				s.Log.Errorln("[server] bridge error:", err)
				time.Sleep(5 * time.Second)
			}
		}(cfg)
	}

	// Setup gateways
	for _, cfg := range cfg.Gateways {
		go func(cfg *sarif.NetConfig) {
			for {
				s.Log.Infoln("[server] gateway to ", cfg.Address)
				conn, err := sarif.Dial(cfg)
				if err == nil {
					err = s.Broker.ListenOnGateway(conn)
				}
				s.Log.Errorln("[server] gateway error:", err)
				time.Sleep(5 * time.Second)
			}
		}(cfg)
	}

	return nil
}