示例#1
0
func (d *mdiscovery) Scan(query string, handlerPtr mojom.ScanHandler_Pointer) (*mojom.Closer_Pointer, *mojom.Error, error) {
	ctx, cancel := context.WithCancel(d.ctx)

	scanCh, err := d.d.Scan(ctx, query)
	if err != nil {
		cancel()
		return nil, v2mError(err), nil
	}

	handler := mojom.NewScanHandlerProxy(handlerPtr, bindings.GetAsyncWaiter())
	go func() {
		defer handler.Close_Proxy()

		for update := range scanCh {
			mUpdate := newMojoUpdate(d.ctx, update)

			req, ptr := mojom.CreateMessagePipeForUpdate()
			stub := mojom.NewUpdateStub(req, mUpdate, bindings.GetAsyncWaiter())
			if err := handler.OnUpdate(ptr); err != nil {
				stub.Close()
				cancel()
				return
			}
			d.serveStub(stub, nil)
		}
	}()

	req, ptr := mojom.CreateMessagePipeForCloser()
	stub := mojom.NewCloserStub(req, &closer{cancel}, bindings.GetAsyncWaiter())
	d.serveStub(stub, cancel)
	return &ptr, nil, nil
}
示例#2
0
func startLockServer(ctx *context.T, configDir string) (func(), error) {
	blessings, _ := v23.GetPrincipal(ctx).BlessingStore().Default()
	lockNhSuffix := fmt.Sprint(blessings)
	// Start a local mounttable where the lock server would be
	// mounted, and make this mounttable visible in the local
	// neighborhood.
	mtName, stopMT, err := locklib.StartMounttable(ctx, configDir, locklib.LockNhPrefix+lockNhSuffix)
	if err != nil {
		return nil, err
	}
	ctx, _, err = v23.WithNewNamespace(ctx, mtName)
	if err != nil {
		stopMT()
		return nil, err
	}
	ctx, cancel := context.WithCancel(ctx)
	_, server, err := v23.WithNewServer(ctx, lockObjectName(ctx), newLock(), security.DefaultAuthorizer())
	if err != nil {
		stopMT()
		return nil, err
	}
	stopLock := func() {
		cancel()
		vlog.Infof("Stopping lock server...")
		<-server.Closed()
		vlog.Infof("Stopped lock server...")
		stopMT()
	}
	vlog.Infof("Started lock server\n")
	vlog.Infof("ENDPOINT: %v\n", server.Status().Endpoints[0].Name())
	return stopLock, nil
}
示例#3
0
func startUnclaimedLockServer(ctx *context.T, configDir string) (<-chan struct{}, func(), error) {
	// Start a local mounttable where the unclaimed lock server would
	// be mounted, and make this mounttable visible in the local
	// neighborhood.
	mtName, stopMT, err := locklib.StartMounttable(ctx, configDir, locklib.LockNhPrefix+unclaimedLockNhSuffix)
	if err != nil {
		return nil, nil, err
	}
	ctx, _, err = v23.WithNewNamespace(ctx, mtName)
	if err != nil {
		stopMT()
		return nil, nil, err
	}
	claimed := make(chan struct{})
	ctx, cancel := context.WithCancel(ctx)
	_, server, err := v23.WithNewServer(ctx, lockObjectName(ctx), newUnclaimedLock(claimed, configDir), security.AllowEveryone())
	if err != nil {
		stopMT()
		return nil, nil, err
	}
	stopUnclaimedLock := func() {
		cancel()
		vlog.Infof("Stopping unclaimed lock server...")
		<-server.Closed()
		vlog.Infof("Stopped unclaimed lock server...")
		stopMT()
	}
	vlog.Infof("Started unclaimed lock server\n")
	vlog.Infof("ENDPOINT: %v\n", server.Status().Endpoints[0].Name())
	return claimed, stopUnclaimedLock, nil
}
示例#4
0
//export swift_io_v_v23_context_VContext_nativeWithCancel
func swift_io_v_v23_context_VContext_nativeWithCancel(ctxHandle C.GoContextHandle, errOut C.SwiftVErrorPtr) C.GoCancelableContextHandle {
	ctx := GoContext(uint64(ctxHandle))
	ctx, cancelFunc := context.WithCancel(ctx)
	swiftCtx, err := SwiftCancelableContext(ctx, cancelFunc)
	if err != nil {
		sutil.ThrowSwiftError(ctx, err, unsafe.Pointer(errOut))
		return C.GoCancelableContextHandle(0)
	}
	return C.GoCancelableContextHandle(swiftCtx)
}
示例#5
0
文件: jni.go 项目: vanadium/go.jni
//export Java_io_v_v23_context_VContext_nativeWithCancel
func Java_io_v_v23_context_VContext_nativeWithCancel(jenv *C.JNIEnv, jVContext C.jobject, goRef C.jlong) C.jobject {
	env := jutil.Env(uintptr(unsafe.Pointer(jenv)))
	ctx, cancelFunc := context.WithCancel((*context.T)(jutil.GoRefValue(jutil.Ref(goRef))))
	jCtx, err := JavaContext(env, ctx, cancelFunc)
	if err != nil {
		jutil.JThrowV(env, err)
		return nil
	}
	return C.jobject(unsafe.Pointer(jCtx))
}
示例#6
0
// NewDiscovery returns a new Vanadium discovery instance.
func NewDiscovery(ctx *context.T, connectionUrl string) (DiscoveryCloser, error) {
	d, err := newDiscovery(ctx, connectionUrl)
	if err != nil {
		return nil, err
	}

	ctx, cancel := context.WithCancel(ctx)
	md := &mdiscovery{
		ctx:    ctx,
		cancel: cancel,
		d:      d,
		stubs:  make(map[*bindings.Stub]struct{}),
	}
	return md, nil
}
示例#7
0
func seekInvites(ctx *context.T, disc discovery.T, server rpc.Server, updates <-chan bool) {
	var (
		ad = &discovery.Advertisement{
			InterfaceName: interfaceName,
			Attributes: discovery.Attributes{
				"OS": runtime.GOOS,
			},
		}
		cancel    func()
		chStopped <-chan struct{}
		start     = func() {
			// Start the advertisement, update cancelCtx, cancel and chStopped
			var err error
			var advCtx *context.T
			advCtx, cancel = context.WithCancel(ctx)
			if chStopped, err = discutil.AdvertiseServer(advCtx, disc, server, "", ad, nil); err != nil {
				cancel()
				ctx.Infof("Failed to advertise %#v: %v", *ad, err)
				return
			}
			ctx.Infof("Started advertising: %#v", *ad)
		}
		stop = func() {
			if chStopped == nil {
				return
			}
			cancel()
			<-chStopped
			ctx.Infof("Stopped advertising: %#v", *ad)
			chStopped = nil
		}
	)
	start()
	go func() {
		for shouldStart := range updates {
			if shouldStart {
				start()
				continue
			}
			stop()
		}
	}()
}
示例#8
0
// Advertises a set of game log and game settings syncgroups
func Advertise(logAddress, settingsAddress, gameStartData string, quit chan bool, ctx *context.T) {
	ctx, stop := context.WithCancel(ctx)
	mdns, err := mdns.New("")
	if err != nil {
		ctx.Fatalf("mDNS failed: %v", err)
	}
	discoveryService := ldiscovery.NewWithPlugins([]ldiscovery.Plugin{mdns})
	gameService := discovery.Service{
		InstanceName:  "A sample game service",
		InterfaceName: util.CroupierInterface,
		Attrs:         map[string]string{"settings_sgname": settingsAddress, "game_start_data": gameStartData},
		Addrs:         []string{logAddress},
	}
	if _, err := discoveryService.Advertise(ctx, &gameService, nil); err != nil {
		ctx.Fatalf("Advertise failed: %v", err)
	}
	select {
	case <-signals.ShutdownOnSignals(ctx):
		stop()
	case <-quit:
		stop()
	}
}
示例#9
0
func runRecvKey(ctx *context.T, env *cmdline.Env, args []string) error {
	ctx, stop, err := withLocalNamespace(ctx, "", lockUserNhName(ctx))
	if err != nil {
		return err
	}
	defer stop()

	service := &recvKeyService{
		env:    env,
		notify: make(chan error),
	}
	ctx, cancel := context.WithCancel(ctx)
	_, server, err := v23.WithNewServer(ctx, recvKeySuffix, service, security.AllowEveryone())
	if err != nil {
		return fmt.Errorf("failed to create server to receive keys: %v", err)
	}
	defer func() {
		cancel()
		<-server.Closed()
	}()
	fmt.Println("Waiting for keys")
	return <-service.notify
}
示例#10
0
func (d *mdiscovery) Advertise(ad mojom.Advertisement, visibility *[]string) (*[AdIdLen]uint8, *mojom.Closer_Pointer, *mojom.Error, error) {
	ctx, cancel := context.WithCancel(d.ctx)

	vAd := m2vAd(&ad)
	vVisibility := m2vVisibility(visibility)
	done, err := d.d.Advertise(ctx, &vAd, vVisibility)
	if err != nil {
		cancel()
		return nil, nil, v2mError(err), nil
	}

	stop := func() {
		cancel()
		<-done
	}
	req, ptr := mojom.CreateMessagePipeForCloser()
	stub := mojom.NewCloserStub(req, &closer{stop}, bindings.GetAsyncWaiter())
	d.serveStub(stub, stop)

	var id [AdIdLen]uint8
	id = vAd.Id
	return &id, &ptr, nil, nil
}
示例#11
0
func sendInvites(ctx *context.T, disc discovery.T, notify chan<- string) {
	ctx.Infof("Scanning for peers to invite")
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	updates, err := disc.Scan(ctx, fmt.Sprintf("v.InterfaceName=%q", interfaceName))
	if err != nil {
		ctx.Panic(err)
	}
	for u := range updates {
		if u.IsLost() {
			continue
		}
		ctx.Infof("Sending invitations to %+v", u.Addresses())
		if addr := sendOneInvite(ctx, u.Addresses()); len(addr) > 0 {
			notify <- addr
			go func() {
				for range updates {
				}
			}()
			return
		}
	}
	ctx.Infof("Stopped scanning for peers to invite without finding one")
}
示例#12
0
文件: funcs.go 项目: vanadium/go.jni
func btAndDiscoveryFunc(ctx *context.T, w io.Writer) error {
	bothf := func(ctx *context.T, w io.Writer, format string, args ...interface{}) {
		fmt.Fprintf(w, format, args...)
		ctx.Infof(format, args...)
	}
	defer bothf(ctx, w, "finishing!")

	dis, err := v23.NewDiscovery(ctx)
	if err != nil {
		bothf(ctx, w, "Can't create discovery %v", err)
		return err
	}

	ctx = v23.WithListenSpec(ctx, rpc.ListenSpec{Addrs: rpc.ListenAddrs{{Protocol: "bt", Address: "/0"}}})
	_, server, err := v23.WithNewServer(ctx, "", &echoServer{}, security.AllowEveryone())
	if err != nil {
		bothf(ctx, w, "Can't create server %v", err)
		return err
	}
	ctx.Infof("Server listening on %v", server.Status().Endpoints)
	ctx.Infof("Server listen errors: %v", server.Status().ListenErrors)

	interfaces := []string{
		"v.io/x/jni/impl/google/services/vango/Echo",
		"v.io/x/jni/impl/google/services/vango/Echo2",
		"v.io/x/jni/impl/google/services/vango/Echo3",
		"v.io/x/jni/impl/google/services/vango/Echo4",
	}
	type adstate struct {
		ad   *discovery.Advertisement
		stop func()
	}
	ads := []adstate{}
	for _, name := range interfaces {
		ad := &discovery.Advertisement{
			InterfaceName: name,
			Attributes: discovery.Attributes{
				"one":   "A value of some kind",
				"two":   "Yet another value",
				"three": "More and more",
				"four":  "This is insane",
			},
		}
		nctx, ncancel := context.WithCancel(ctx)
		ch, err := libdiscovery.AdvertiseServer(nctx, dis, server, "", ad, nil)
		if err != nil {
			bothf(nctx, w, "Can't advertise server %v", err)
			return err
		}

		stop := func() {
			ncancel()
			<-ch
		}
		ads = append(ads, adstate{ad, stop})
	}

	type updateState struct {
		ch   <-chan discovery.Update
		stop func()
	}
	var updates []updateState
	for _, name := range interfaces {
		nctx, ncancel := context.WithCancel(ctx)
		u, err := dis.Scan(nctx, `v.InterfaceName="`+name+`"`)
		if err != nil {
			bothf(nctx, w, "Can't scan %v", err)
			return err
		}
		stop := func() {
			ncancel()
		}
		updates = append(updates, updateState{u, stop})
	}

	for _, u := range updates[1:] {
		go func(up updateState) {
			for _ = range up.ch {
			}
		}(u)
	}

	makeopt := func(ad discovery.Advertisement) options.Preresolved {
		me := &naming.MountEntry{
			IsLeaf: true,
		}
		for _, a := range ad.Addresses {
			addr, _ := naming.SplitAddressName(a)
			me.Servers = append(me.Servers, naming.MountedServer{
				Server: addr,
			})
		}
		return options.Preresolved{Resolution: me}
	}

	alive := map[discovery.AdId]options.Preresolved{}
	ticker := time.NewTicker(time.Second)
	for {
		select {
		case <-ticker.C:
			if len(alive) == 0 {
				bothf(ctx, w, "No live connections to dial.")
			}
			for _, opt := range alive {
				dialtime := options.ConnectionTimeout(5 * time.Second)
				channeltime := options.ChannelTimeout(2 * time.Second)
				data := make([]byte, 1024)
				summary, err := runTimedCall(ctx, "A timed call.", string(data), opt, dialtime, channeltime)
				if err != nil {
					bothf(ctx, w, "failed call %s, %v, %v", summary, err, opt.Resolution.Servers)
				} else {
					bothf(ctx, w, "succeeded call: %s, %v", summary, opt.Resolution.Servers)
				}
			}

		case u := <-updates[0].ch:
			if u.IsLost() {
				bothf(ctx, w, "lost %v", u.Addresses())
				delete(alive, u.Id())
			} else {
				bothf(ctx, w, "found %v", u.Addresses())
				alive[u.Id()] = makeopt(u.Advertisement())
			}
		}
	}
}