当前位置: 首页>>代码示例>>Golang>>正文


Golang suture.NewSimple函数代码示例

本文整理汇总了Golang中github.com/thejerf/suture.NewSimple函数的典型用法代码示例。如果您正苦于以下问题:Golang NewSimple函数的具体用法?Golang NewSimple怎么用?Golang NewSimple使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NewSimple函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: main

func main() {
	flag.StringVar(&getIPCommand, "cmd", getIPCommand, "Command to get external IP")
	flag.StringVar(&zoneID, "zone", zoneID, "Cloudflare Zone ID")
	flag.StringVar(&name, "name", name, "DNS record to update")
	flag.StringVar(&authEmail, "email", authEmail, "Cloudflare Auth Email")
	flag.StringVar(&authKey, "key", authKey, "Cloudflare API Key")
	flag.IntVar(&ttl, "ttl", ttl, "DNS record TTL (seconds)")
	flag.DurationVar(&interval, "intv", interval, "External IP check interval")
	flag.Parse()

	if name == "" {
		fmt.Println("Option -name is mandatory")
		os.Exit(1)
	}
	if authEmail == "" {
		fmt.Println("Option -email is mandatory")
		os.Exit(1)
	}
	if authKey == "" {
		fmt.Println("Option -key is mandatory")
		os.Exit(1)
	}

	client := cfdns.NewClient(authEmail, authKey)
	main := suture.NewSimple("main")
	checker := newIPChecker(getIPCommand, interval)
	main.Add(checker)
	updater := newDNSUpdater(name, client, checker.changes)
	main.Add(updater)
	main.Serve()
}
开发者ID:calmh,项目名称:cfdyndns,代码行数:31,代码来源:main.go

示例2: startHTTP

func startHTTP(cfg *mockedConfig) (string, error) {
	model := new(mockedModel)
	httpsCertFile := "../../test/h1/https-cert.pem"
	httpsKeyFile := "../../test/h1/https-key.pem"
	assetDir := "../../gui"
	eventSub := new(mockedEventSub)
	discoverer := new(mockedCachingMux)
	connections := new(mockedConnections)
	errorLog := new(mockedLoggerRecorder)
	systemLog := new(mockedLoggerRecorder)
	addrChan := make(chan string)

	// Instantiate the API service
	svc := newAPIService(protocol.LocalDeviceID, cfg, httpsCertFile, httpsKeyFile, assetDir, model,
		eventSub, discoverer, connections, errorLog, systemLog)
	svc.started = addrChan

	// Actually start the API service
	supervisor := suture.NewSimple("API test")
	supervisor.Add(svc)
	supervisor.ServeBackground()

	// Make sure the API service is listening, and get the URL to use.
	addr := <-addrChan
	tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
	if err != nil {
		return "", fmt.Errorf("Weird address from API service: %v", err)
	}
	baseURL := fmt.Sprintf("http://127.0.0.1:%d", tcpAddr.Port)

	return baseURL, nil
}
开发者ID:teotikalki,项目名称:syncthing,代码行数:32,代码来源:gui_test.go

示例3: NewLocal

func NewLocal(id protocol.DeviceID, addr string, addrList AddressLister, relayStat RelayStatusProvider) (FinderService, error) {
	c := &localClient{
		Supervisor:      suture.NewSimple("local"),
		myID:            id,
		addrList:        addrList,
		relayStat:       relayStat,
		localBcastTick:  time.Tick(BroadcastInterval),
		forcedBcastTick: make(chan time.Time),
		localBcastStart: time.Now(),
		cache:           newCache(),
	}

	host, port, err := net.SplitHostPort(addr)
	if err != nil {
		return nil, err
	}

	if len(host) == 0 {
		// A broadcast client
		c.name = "IPv4 local"
		bcPort, err := strconv.Atoi(port)
		if err != nil {
			return nil, err
		}
		c.startLocalIPv4Broadcasts(bcPort)
	} else {
		// A multicast client
		c.name = "IPv6 local"
		c.startLocalIPv6Multicasts(addr)
	}

	go c.sendLocalAnnouncements()

	return c, nil
}
开发者ID:hernad,项目名称:syncthing,代码行数:35,代码来源:local.go

示例4: newConnectionSvc

func newConnectionSvc(cfg *config.Wrapper, myID protocol.DeviceID, mdl *model.Model, tlsCfg *tls.Config, discoverer discover.Finder, relaySvc *relay.Svc) *connectionSvc {
	svc := &connectionSvc{
		Supervisor: suture.NewSimple("connectionSvc"),
		cfg:        cfg,
		myID:       myID,
		model:      mdl,
		tlsCfg:     tlsCfg,
		discoverer: discoverer,
		relaySvc:   relaySvc,
		conns:      make(chan model.IntermediateConnection),

		connType:       make(map[protocol.DeviceID]model.ConnectionType),
		relaysEnabled:  cfg.Options().RelaysEnabled,
		lastRelayCheck: make(map[protocol.DeviceID]time.Time),
	}
	cfg.Subscribe(svc)

	// There are several moving parts here; one routine per listening address
	// to handle incoming connections, one routine to periodically attempt
	// outgoing connections, one routine to the the common handling
	// regardless of whether the connection was incoming or outgoing.
	// Furthermore, a relay service which handles incoming requests to connect
	// via the relays.
	//
	// TODO: Clean shutdown, and/or handling config changes on the fly. We
	// partly do this now - new devices and addresses will be picked up, but
	// not new listen addresses and we don't support disconnecting devices
	// that are removed and so on...

	svc.Add(serviceFunc(svc.connect))
	for _, addr := range svc.cfg.Options().ListenAddress {
		uri, err := url.Parse(addr)
		if err != nil {
			l.Infoln("Failed to parse listen address:", addr, err)
			continue
		}

		listener, ok := listeners[uri.Scheme]
		if !ok {
			l.Infoln("Unknown listen address scheme:", uri.String())
			continue
		}

		if debugNet {
			l.Debugln("listening on", uri.String())
		}

		svc.Add(serviceFunc(func() {
			listener(uri, svc.tlsCfg, svc.conns)
		}))
	}
	svc.Add(serviceFunc(svc.handle))

	if svc.relaySvc != nil {
		svc.Add(serviceFunc(svc.acceptRelayConns))
	}

	return svc
}
开发者ID:kbreuni,项目名称:syncthing,代码行数:59,代码来源:connections.go

示例5: newConnectionSvc

func newConnectionSvc(cfg *config.Wrapper, myID protocol.DeviceID, model *model.Model, tlsCfg *tls.Config) *connectionSvc {
	svc := &connectionSvc{
		Supervisor: suture.NewSimple("connectionSvc"),
		cfg:        cfg,
		myID:       myID,
		model:      model,
		tlsCfg:     tlsCfg,
		conns:      make(chan *tls.Conn),
	}

	// There are several moving parts here; one routine per listening address
	// to handle incoming connections, one routine to periodically attempt
	// outgoing connections, and lastly one routine to the the common handling
	// regardless of whether the connection was incoming or outgoing. It ends
	// up as in the diagram below. We embed a Supervisor to manage the
	// routines (i.e. log and restart if they crash or exit, etc).
	//
	//                +-----------------+
	//    Incoming    | +---------------+-+      +-----------------+
	//   Connections  | |                 |      |                 |   Outgoing
	// -------------->| |   svc.listen    |      |                 |  Connections
	//                | |  (1 per listen  |      |   svc.connect   |-------------->
	//                | |    address)     |      |                 |
	//                +-+                 |      |                 |
	//                  +-----------------+      +-----------------+
	//                           v                        v
	//                           |                        |
	//                           |                        |
	//                           +------------+-----------+
	//                                        |
	//                                        | svc.conns
	//                                        v
	//                               +-----------------+
	//                               |                 |
	//                               |                 |
	//                               |   svc.handle    |------> model.AddConnection()
	//                               |                 |
	//                               |                 |
	//                               +-----------------+
	//
	// TODO: Clean shutdown, and/or handling config changes on the fly. We
	// partly do this now - new devices and addresses will be picked up, but
	// not new listen addresses and we don't support disconnecting devices
	// that are removed and so on...

	svc.Add(serviceFunc(svc.connect))
	for _, addr := range svc.cfg.Options().ListenAddress {
		addr := addr
		listener := serviceFunc(func() {
			svc.listen(addr)
		})
		svc.Add(listener)
	}
	svc.Add(serviceFunc(svc.handle))

	return svc
}
开发者ID:kristallizer,项目名称:syncthing,代码行数:57,代码来源:connections.go

示例6: main

func main() {
	const (
		cleanIntv = 1 * time.Hour
		statsIntv = 5 * time.Minute
	)

	var listen string

	log.SetOutput(os.Stdout)
	log.SetFlags(0)

	flag.StringVar(&listen, "listen", ":22027", "Listen address")
	flag.IntVar(&lruSize, "limit-cache", lruSize, "Limiter cache entries")
	flag.IntVar(&limitAvg, "limit-avg", limitAvg, "Allowed average package rate, per 10 s")
	flag.IntVar(&limitBurst, "limit-burst", limitBurst, "Allowed burst size, packets")
	flag.StringVar(&statsFile, "stats-file", statsFile, "File to write periodic operation stats to")
	flag.StringVar(&backend, "db-backend", backend, "Database backend to use")
	flag.StringVar(&dsn, "db-dsn", dsn, "Database DSN")
	flag.Parse()

	addr, _ := net.ResolveUDPAddr("udp", listen)

	var err error
	db, err := sql.Open(backend, dsn)
	if err != nil {
		log.Fatalln("sql.Open:", err)
	}
	prep, err := setup(backend, db)
	if err != nil {
		log.Fatalln("Setup:", err)
	}

	main := suture.NewSimple("main")

	main.Add(&querysrv{
		addr: addr,
		db:   db,
		prep: prep,
	})

	main.Add(&cleansrv{
		intv: cleanIntv,
		db:   db,
		prep: prep,
	})

	main.Add(&statssrv{
		intv: statsIntv,
		file: statsFile,
		db:   db,
	})

	globalStats.Reset()
	main.Serve()
}
开发者ID:rumpelsepp,项目名称:discosrv,代码行数:55,代码来源:main.go

示例7: NewService

func NewService(cfg *config.Wrapper, myID protocol.DeviceID, mdl Model, tlsCfg *tls.Config, discoverer discover.Finder,
	bepProtocolName string, tlsDefaultCommonName string, lans []*net.IPNet) *Service {

	service := &Service{
		Supervisor:           suture.NewSimple("connections.Service"),
		cfg:                  cfg,
		myID:                 myID,
		model:                mdl,
		tlsCfg:               tlsCfg,
		discoverer:           discoverer,
		conns:                make(chan IntermediateConnection),
		bepProtocolName:      bepProtocolName,
		tlsDefaultCommonName: tlsDefaultCommonName,
		lans:                 lans,
		natService:           nat.NewService(myID, cfg),

		listenersMut:   sync.NewRWMutex(),
		listeners:      make(map[string]genericListener),
		listenerTokens: make(map[string]suture.ServiceToken),

		curConMut:         sync.NewMutex(),
		currentConnection: make(map[protocol.DeviceID]Connection),
	}
	cfg.Subscribe(service)

	// The rate variables are in KiB/s in the UI (despite the camel casing
	// of the name). We multiply by 1024 here to get B/s.
	options := service.cfg.Options()
	if options.MaxSendKbps > 0 {
		service.writeRateLimit = ratelimit.NewBucketWithRate(float64(1024*options.MaxSendKbps), int64(5*1024*options.MaxSendKbps))
	}

	if options.MaxRecvKbps > 0 {
		service.readRateLimit = ratelimit.NewBucketWithRate(float64(1024*options.MaxRecvKbps), int64(5*1024*options.MaxRecvKbps))
	}

	// There are several moving parts here; one routine per listening address
	// (handled in configuration changing) to handle incoming connections,
	// one routine to periodically attempt outgoing connections, one routine to
	// the the common handling regardless of whether the connection was
	// incoming or outgoing.

	service.Add(serviceFunc(service.connect))
	service.Add(serviceFunc(service.handle))

	raw := cfg.Raw()
	// Actually starts the listeners and NAT service
	service.CommitConfiguration(raw, raw)

	return service
}
开发者ID:carriercomm,项目名称:syncthing,代码行数:51,代码来源:service.go

示例8: CommitConfiguration

func (m *usageReportingManager) CommitConfiguration(from, to config.Configuration) bool {
	if to.Options.URAccepted >= usageReportVersion && m.sup == nil {
		// Usage reporting was turned on; lets start it.
		service := newUsageReportingService(m.cfg, m.model)
		m.sup = suture.NewSimple("usageReporting")
		m.sup.Add(service)
		m.sup.ServeBackground()
	} else if to.Options.URAccepted < usageReportVersion && m.sup != nil {
		// Usage reporting was turned off
		m.sup.Stop()
		m.sup = nil
	}

	return true
}
开发者ID:brgmnn,项目名称:syncthing,代码行数:15,代码来源:usage_report.go

示例9: newFolderSummarySvc

func newFolderSummarySvc(m *model.Model) *folderSummarySvc {
	svc := &folderSummarySvc{
		Supervisor:      suture.NewSimple("folderSummarySvc"),
		model:           m,
		stop:            make(chan struct{}),
		immediate:       make(chan string),
		folders:         make(map[string]struct{}),
		foldersMut:      sync.NewMutex(),
		lastEventReqMut: sync.NewMutex(),
	}

	svc.Add(serviceFunc(svc.listenForUpdates))
	svc.Add(serviceFunc(svc.calculateSummaries))

	return svc
}
开发者ID:sgilani,项目名称:Syncthing-iOS,代码行数:16,代码来源:summarysvc.go

示例10: newFolderSummaryService

func newFolderSummaryService(cfg *config.Wrapper, m *model.Model) *folderSummaryService {
	service := &folderSummaryService{
		Supervisor:      suture.NewSimple("folderSummaryService"),
		cfg:             cfg,
		model:           m,
		stop:            make(chan struct{}),
		immediate:       make(chan string),
		folders:         make(map[string]struct{}),
		foldersMut:      sync.NewMutex(),
		lastEventReqMut: sync.NewMutex(),
	}

	service.Add(serviceFunc(service.listenForUpdates))
	service.Add(serviceFunc(service.calculateSummaries))

	return service
}
开发者ID:wmwwmv,项目名称:syncthing,代码行数:17,代码来源:summaryservice.go

示例11: main

func main() {
	// Instantiate a SIFT server
	server, err := sift.NewServer(sift.DefaultDBFilepath)
	if err != nil {
		panic(err)
	}
	if err = server.AddDefaults(); err != nil {
		panic(err)
	}

	// Start the server as a suture process
	supervisor := suture.NewSimple("movies and chill (SIFT app)")
	servToken := supervisor.Add(server)
	defer supervisor.Remove(servToken)
	go supervisor.ServeBackground()

	// Run the SIFT script
	moviesAndChill(server)
}
开发者ID:upwrd,项目名称:sift,代码行数:19,代码来源:moviesAndChill.go

示例12: TestStopAfterBrokenConfig

func TestStopAfterBrokenConfig(t *testing.T) {
	baseDirs["config"] = "../../test/h1" // to load HTTPS keys
	expandLocations()

	cfg := config.Configuration{
		GUI: config.GUIConfiguration{
			RawAddress: "127.0.0.1:0",
			RawUseTLS:  false,
		},
	}
	w := config.Wrap("/dev/null", cfg)

	srv, err := newAPIService(protocol.LocalDeviceID, w, "", nil, nil, nil, nil, nil, nil)
	if err != nil {
		t.Fatal(err)
	}
	srv.started = make(chan struct{})

	sup := suture.NewSimple("test")
	sup.Add(srv)
	sup.ServeBackground()

	<-srv.started

	// Service is now running, listening on a random port on localhost. Now we
	// request a config change to a completely invalid listen address. The
	// commit will fail and the service will be in a broken state.

	newCfg := config.Configuration{
		GUI: config.GUIConfiguration{
			RawAddress: "totally not a valid address",
			RawUseTLS:  false,
		},
	}
	if srv.CommitConfiguration(cfg, newCfg) {
		t.Fatal("Config commit should have failed")
	}

	// Nonetheless, it should be fine to Stop() it without panic.

	sup.Stop()
}
开发者ID:hernad,项目名称:syncthing,代码行数:42,代码来源:gui_test.go

示例13: main

func main() {
	sift.SetLogLevel("debug")
	//ipv4.Log.SetHandler(log.DiscardHandler()) // ignore ipv4 scanner stuff

	// Instantiate a SIFT server
	server, err := sift.NewServer(sift.DefaultDBFilepath)
	if err != nil {
		panic(err)
	}
	if err = server.AddDefaults(); err != nil {
		panic(err)
	}

	// Start the server as a suture process
	supervisor := suture.NewSimple("repeat to console (SIFT app)")
	servToken := supervisor.Add(server)
	defer supervisor.Remove(servToken)
	go supervisor.ServeBackground()

	// Run the SIFT script
	repeatUpdatesToConsole(server)
}
开发者ID:upwrd,项目名称:sift,代码行数:22,代码来源:repeatToConsole.go

示例14: TestStopAfterBrokenConfig

func TestStopAfterBrokenConfig(t *testing.T) {
	cfg := config.Configuration{
		GUI: config.GUIConfiguration{
			RawAddress: "127.0.0.1:0",
			RawUseTLS:  false,
		},
	}
	w := config.Wrap("/dev/null", cfg)

	srv := newAPIService(protocol.LocalDeviceID, w, "../../test/h1/https-cert.pem", "../../test/h1/https-key.pem", "", nil, nil, nil, nil, nil, nil)
	srv.started = make(chan string)

	sup := suture.NewSimple("test")
	sup.Add(srv)
	sup.ServeBackground()

	<-srv.started

	// Service is now running, listening on a random port on localhost. Now we
	// request a config change to a completely invalid listen address. The
	// commit will fail and the service will be in a broken state.

	newCfg := config.Configuration{
		GUI: config.GUIConfiguration{
			RawAddress: "totally not a valid address",
			RawUseTLS:  false,
		},
	}
	if err := srv.VerifyConfiguration(cfg, newCfg); err == nil {
		t.Fatal("Verify config should have failed")
	}

	// Nonetheless, it should be fine to Stop() it without panic.

	sup.Stop()
}
开发者ID:letiemble,项目名称:syncthing,代码行数:36,代码来源:gui_test.go

示例15: main

func main() {
	const (
		cleanIntv = 1 * time.Hour
		statsIntv = 5 * time.Minute
	)

	var listen string

	log.SetOutput(os.Stdout)
	log.SetFlags(0)

	flag.StringVar(&listen, "listen", ":8443", "Listen address")
	flag.IntVar(&lruSize, "limit-cache", lruSize, "Limiter cache entries")
	flag.IntVar(&limitAvg, "limit-avg", limitAvg, "Allowed average package rate, per 10 s")
	flag.IntVar(&limitBurst, "limit-burst", limitBurst, "Allowed burst size, packets")
	flag.StringVar(&statsFile, "stats-file", statsFile, "File to write periodic operation stats to")
	flag.StringVar(&backend, "db-backend", backend, "Database backend to use")
	flag.StringVar(&dsn, "db-dsn", dsn, "Database DSN")
	flag.StringVar(&certFile, "cert", certFile, "Certificate file")
	flag.StringVar(&keyFile, "key", keyFile, "Key file")
	flag.BoolVar(&debug, "debug", debug, "Debug")
	flag.Parse()

	cert, err := tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		log.Fatalln("Failed to load X509 key pair:", err)
	}

	db, err := sql.Open(backend, dsn)
	if err != nil {
		log.Fatalln("sql.Open:", err)
	}
	prep, err := setup(backend, db)
	if err != nil {
		log.Fatalln("Setup:", err)
	}

	main := suture.NewSimple("main")

	main.Add(&querysrv{
		addr: listen,
		cert: cert,
		db:   db,
		prep: prep,
	})

	main.Add(&cleansrv{
		intv: cleanIntv,
		db:   db,
		prep: prep,
	})

	main.Add(&statssrv{
		intv: statsIntv,
		file: statsFile,
		db:   db,
	})

	globalStats.Reset()
	main.Serve()
}
开发者ID:Links2004,项目名称:discosrv,代码行数:61,代码来源:main.go


注:本文中的github.com/thejerf/suture.NewSimple函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。