• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang context.WithCancel函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: TestWatchNetworkAdded

func TestWatchNetworkAdded(t *testing.T) {
	msr := newDummyRegistry()
	sm := NewMockManager(msr)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	events := make(chan []Event)
	go WatchNetworks(ctx, sm, events)

	// skip over the initial snapshot
	<-events

	expected := "foobar"
	msr.CreateNetwork(ctx, expected, `{"Network": "10.1.1.0/16", "Backend": {"Type": "bridge"}}`)

	evtBatch := <-events

	if len(evtBatch) != 1 {
		t.Fatalf("WatchNetworks produced wrong sized event batch")
	}

	evt := evtBatch[0]

	if evt.Type != EventAdded {
		t.Fatalf("WatchNetworks produced wrong event type")
	}

	actual := evt.Network
	if actual != expected {
		t.Errorf("WatchNetworks produced wrong network: expected %s, got %s", expected, actual)
	}
}
开发者ID:erickcantwell,项目名称:flannel,代码行数:33,代码来源:subnet_test.go


示例2: TestWatchLeaseRemoved

func TestWatchLeaseRemoved(t *testing.T) {
	msr := newDummyRegistry(0)
	sm := newEtcdManager(msr)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	events := make(chan []Event)
	go WatchLeases(ctx, sm, "", events)

	// skip over the initial snapshot
	<-events

	expected := "10.3.4.0-24"
	msr.expireSubnet(expected)

	evtBatch := <-events

	if len(evtBatch) != 1 {
		t.Fatalf("WatchSubnets produced wrong sized event batch")
	}

	evt := evtBatch[0]

	if evt.Type != SubnetRemoved {
		t.Fatalf("WatchSubnets produced wrong event type")
	}

	actual := evt.Lease.Key()
	if actual != expected {
		t.Errorf("WatchSubnet produced wrong subnet: expected %s, got %s", expected, actual)
	}
}
开发者ID:shenjinxi,项目名称:flannel,代码行数:33,代码来源:subnet_test.go


示例3: TestSimpleHTTPClientDoCancelContextWaitForRoundTrip

func TestSimpleHTTPClientDoCancelContextWaitForRoundTrip(t *testing.T) {
	tr := newFakeTransport()
	c := &simpleHTTPClient{transport: tr}

	donechan := make(chan struct{})
	ctx, cancel := context.WithCancel(context.Background())
	go func() {
		c.Do(ctx, &fakeAction{})
		close(donechan)
	}()

	// This should call CancelRequest and begin the cancellation process
	cancel()

	select {
	case <-donechan:
		t.Fatalf("simpleHTTPClient.Do should not have exited yet")
	default:
	}

	tr.finishCancel <- struct{}{}

	select {
	case <-donechan:
		//expected behavior
		return
	case <-time.After(time.Second):
		t.Fatalf("simpleHTTPClient.Do did not exit within 1s")
	}
}
开发者ID:nathanleiby,项目名称:flannel,代码行数:30,代码来源:client_test.go


示例4: TestRemoveReservation

func TestRemoveReservation(t *testing.T) {
	msr := newDummyRegistry()
	sm := NewMockManager(msr)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	r := Reservation{
		Subnet:   newIP4Net("10.3.10.0", 24),
		PublicIP: ip.MustParseIP4("52.195.12.13"),
	}
	if err := sm.AddReservation(ctx, "_", &r); err != nil {
		t.Fatalf("failed to add reservation: %v", err)
	}

	if err := sm.RemoveReservation(ctx, "_", r.Subnet); err != nil {
		t.Fatalf("failed to remove reservation: %v", err)
	}

	// The node should have a TTL
	sub, _, err := msr.getSubnet(ctx, "_", r.Subnet)
	if err != nil {
		t.Fatalf("getSubnet failed: %v", err)
	}

	if sub.Expiration.IsZero() {
		t.Fatalf("removed reservation resulted in no TTL")
	}
}
开发者ID:erickcantwell,项目名称:flannel,代码行数:29,代码来源:subnet_test.go


示例5: TestSimpleHTTPClientDoCancelContextResponseBodyClosed

func TestSimpleHTTPClientDoCancelContextResponseBodyClosed(t *testing.T) {
	tr := newFakeTransport()
	c := &simpleHTTPClient{transport: tr}

	// create an already-cancelled context
	ctx, cancel := context.WithCancel(context.Background())
	cancel()

	body := &checkableReadCloser{ReadCloser: ioutil.NopCloser(strings.NewReader("foo"))}
	go func() {
		// wait that simpleHTTPClient knows the context is already timed out,
		// and calls CancelRequest
		testutil.WaitSchedule()

		// response is returned before cancel effects
		tr.respchan <- &http.Response{Body: body}
	}()

	_, _, err := c.Do(ctx, &fakeAction{})
	if err == nil {
		t.Fatalf("expected non-nil error, got nil")
	}

	if !body.closed {
		t.Fatalf("expected closed body")
	}
}
开发者ID:nathanleiby,项目名称:flannel,代码行数:27,代码来源:client_test.go


示例6: TestWatchGetNetworks

func TestWatchGetNetworks(t *testing.T) {
	msr := newDummyRegistry()
	sm := NewMockManager(msr)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Kill the previously added "_" network
	msr.DeleteNetwork(ctx, "_")

	expected := "foobar"
	msr.CreateNetwork(ctx, expected, `{"Network": "10.1.1.0/16", "Backend": {"Type": "bridge"}}`)

	resp, err := sm.WatchNetworks(ctx, nil)
	if err != nil {
		t.Errorf("WatchNetworks(nil) failed:", err)
	}

	if len(resp.Snapshot) != 1 {
		t.Errorf("WatchNetworks(nil) produced wrong number of networks: expected 1, got %d", len(resp.Snapshot))
	}

	if resp.Snapshot[0] != expected {
		t.Errorf("WatchNetworks(nil) produced wrong network: expected %s, got %s", expected, resp.Snapshot[0])
	}
}
开发者ID:erickcantwell,项目名称:flannel,代码行数:26,代码来源:subnet_test.go


示例7: doTestWatchNetworks

func doTestWatchNetworks(t *testing.T, sm subnet.Manager, serverRegistry *subnet.MockSubnetRegistry) {
	ctx, cancel := context.WithCancel(context.Background())
	wg := sync.WaitGroup{}
	wg.Add(1)
	defer func() {
		cancel()
		wg.Wait()
	}()

	events := make(chan []subnet.Event)
	go func() {
		subnet.WatchNetworks(ctx, sm, events)
		wg.Done()
	}()

	// skip over the initial snapshot
	<-events

	expectedNetname := "foobar"
	config := fmt.Sprintf(`{"Network": %q}`, expectedNetwork)
	err := serverRegistry.CreateNetwork(ctx, expectedNetname, config)
	if err != nil {
		t.Errorf("create network failed: %v", err)
	}

	evtBatch := <-events

	if len(evtBatch) != 1 {
		t.Fatalf("WatchNetworks create produced wrong sized event batch")
	}

	evt := evtBatch[0]
	if evt.Type != subnet.EventAdded {
		t.Fatalf("WatchNetworks create produced wrong event type")
	}

	if evt.Network != expectedNetname {
		t.Errorf("WatchNetwork create produced wrong network: expected %s, got %s", expectedNetname, evt.Network)
	}

	err = serverRegistry.DeleteNetwork(ctx, expectedNetname)
	if err != nil {
		t.Errorf("delete network failed: %v", err)
	}

	evtBatch = <-events

	if len(evtBatch) != 1 {
		t.Fatalf("WatchNetworks delete produced wrong sized event batch")
	}

	evt = evtBatch[0]
	if evt.Type != subnet.EventRemoved {
		t.Fatalf("WatchNetworks delete produced wrong event type")
	}

	if evt.Network != expectedNetname {
		t.Errorf("WatchNetwork delete produced wrong network: expected %s, got %s", expectedNetname, evt.Network)
	}
}
开发者ID:hidetosaito,项目名称:flannel,代码行数:60,代码来源:remote_test.go


示例8: TestRenewLease

func TestRenewLease(t *testing.T) {
	msr := newDummyRegistry()
	sm := NewMockManager(msr)
	now := time.Now()
	fakeClock := clockwork.NewFakeClockAt(now)
	clock = fakeClock

	// Create LeaseAttrs
	extIaddr, _ := ip.ParseIP4("1.2.3.4")
	attrs := LeaseAttrs{
		PublicIP:    extIaddr,
		BackendType: "vxlan",
	}

	ld, err := json.Marshal(&leaseData{Dummy: "test string"})
	if err != nil {
		t.Fatalf("Failed to marshal leaseData: %v", err)
	}
	attrs.BackendData = json.RawMessage(ld)

	// Acquire lease
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	l, err := sm.AcquireLease(ctx, "_", &attrs)
	if err != nil {
		t.Fatal("AcquireLease failed: ", err)
	}

	now = now.Add(subnetTTL)

	fakeClock.Advance(24 * time.Hour)

	if err := sm.RenewLease(ctx, "_", l); err != nil {
		t.Fatal("RenewLease failed: ", err)
	}

	// check that it's still good
	n, err := msr.getNetwork(ctx, "_")
	if err != nil {
		t.Error("Failed to renew lease: could not get networks: %v", err)
	}

	for _, sn := range n.subnets {
		if sn.Subnet.Equal(l.Subnet) {
			expected := now.Add(subnetTTL)
			if !sn.Expiration.Equal(expected) {
				t.Errorf("Failed to renew lease: bad expiration; expected %v, got %v", expected, sn.Expiration)
			}
			if !reflect.DeepEqual(sn.Attrs, attrs) {
				t.Errorf("LeaseAttrs changed: was %#v, now %#v", attrs, sn.Attrs)
			}
			return
		}
	}

	t.Fatalf("Failed to find acquired lease")
}
开发者ID:erickcantwell,项目名称:flannel,代码行数:58,代码来源:subnet_test.go


示例9: New

func New(sm subnet.Manager, network string) backend.Backend {
	ctx, cancel := context.WithCancel(context.Background())

	return &AllocBackend{
		sm:      sm,
		network: network,
		ctx:     ctx,
		cancel:  cancel,
	}
}
开发者ID:nathanleiby,项目名称:flannel,代码行数:10,代码来源:alloc.go


示例10: TestRenewLease

func TestRenewLease(t *testing.T) {
	msr := newDummyRegistry(1)
	sm := newEtcdManager(msr)

	// Create LeaseAttrs
	extIaddr, _ := ip.ParseIP4("1.2.3.4")
	attrs := LeaseAttrs{
		PublicIP:    extIaddr,
		BackendType: "vxlan",
	}

	ld, err := json.Marshal(&leaseData{Dummy: "test string"})
	if err != nil {
		t.Fatalf("Failed to marshal leaseData: %v", err)
	}
	attrs.BackendData = json.RawMessage(ld)

	// Acquire lease
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	l, err := sm.AcquireLease(ctx, "_", &attrs)
	if err != nil {
		t.Fatal("AcquireLease failed: ", err)
	}

	go LeaseRenewer(ctx, sm, "_", l)

	fmt.Println("Waiting for lease to pass original expiration")
	time.Sleep(2 * time.Second)

	// check that it's still good
	net, err := msr.getNetwork(ctx, "_")
	if err != nil {
		t.Error("Failed to renew lease: could not get networks: %v", err)
	}
	for _, n := range net.Node.Nodes {
		if n.Key == l.Subnet.StringSep(".", "-") {
			if n.Expiration.Before(time.Now()) {
				t.Error("Failed to renew lease: expiration did not advance")
			}
			a := LeaseAttrs{}
			if err := json.Unmarshal([]byte(n.Value), &a); err != nil {
				t.Errorf("Failed to JSON-decode LeaseAttrs: %v", err)
				return
			}
			if !reflect.DeepEqual(a, attrs) {
				t.Errorf("LeaseAttrs changed: was %#v, now %#v", attrs, a)
			}
			return
		}
	}

	t.Fatalf("Failed to find acquired lease")
}
开发者ID:jonboulle,项目名称:flannel,代码行数:55,代码来源:subnet_test.go


示例11: TestWatchLeaseAdded

func TestWatchLeaseAdded(t *testing.T) {
	msr := newDummyRegistry()
	sm := NewMockManager(msr)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	l := acquireLease(ctx, t, sm)

	events := make(chan []Event)
	go WatchLeases(ctx, sm, "_", l, events)

	evtBatch := <-events
	for _, evt := range evtBatch {
		if evt.Lease.Key() == l.Key() {
			t.Errorf("WatchLeases returned our own lease")
		}
	}

	expected := ip.IP4Net{
		IP:        ip.MustParseIP4("10.3.30.0"),
		PrefixLen: 24,
	}
	// Sanity check to make sure acquired lease is not this.
	// It shouldn't be as SubnetMin/SubnetMax in config is [10.3.1.0/24 to 10.3.25.0/24]
	if l.Subnet.Equal(expected) {
		t.Fatalf("Acquired lease conflicts with one about to create")
	}

	attrs := &LeaseAttrs{
		PublicIP: ip.MustParseIP4("1.1.1.1"),
	}
	_, err := msr.createSubnet(ctx, "_", expected, attrs, 0)
	if err != nil {
		t.Fatalf("createSubnet filed: %v", err)
	}

	evtBatch = <-events

	if len(evtBatch) != 1 {
		t.Fatalf("WatchLeases produced wrong sized event batch: got %v, expected 1", len(evtBatch))
	}

	evt := evtBatch[0]

	if evt.Type != EventAdded {
		t.Fatalf("WatchLeases produced wrong event type")
	}

	actual := evt.Lease.Subnet
	if !actual.Equal(expected) {
		t.Errorf("WatchSubnet produced wrong subnet: expected %s, got %s", expected, actual)
	}
}
开发者ID:vanloswang,项目名称:flannel,代码行数:54,代码来源:subnet_test.go


示例12: NewNetwork

func NewNetwork(ctx context.Context, sm subnet.Manager, name string, ipMasq bool) *Network {
	ctx, cancel := context.WithCancel(ctx)

	return &Network{
		Name:       name,
		ctx:        ctx,
		cancelFunc: cancel,
		sm:         sm,
		ipMasq:     ipMasq,
	}
}
开发者ID:patrobinson,项目名称:flannel,代码行数:11,代码来源:network.go


示例13: New

func New(sm subnet.Manager, network string, config *subnet.Config) backend.Backend {
	ctx, cancel := context.WithCancel(context.Background())

	gb := GCEBackend{
		sm:      sm,
		config:  config,
		ctx:     ctx,
		cancel:  cancel,
		network: network,
	}
	return &gb
}
开发者ID:MarkBruns,项目名称:flannel,代码行数:12,代码来源:gce.go


示例14: New

func New(sm subnet.Manager, network string, config *subnet.Config) backend.Backend {
	ctx, cancel := context.WithCancel(context.Background())

	be := AwsVpcBackend{
		sm:      sm,
		network: network,
		config:  config,
		ctx:     ctx,
		cancel:  cancel,
	}
	return &be
}
开发者ID:nathanleiby,项目名称:flannel,代码行数:12,代码来源:awsvpc.go


示例15: New

func New(sm subnet.Manager, network string, config *subnet.Config) backend.Backend {
	ctx, cancel := context.WithCancel(context.Background())

	be := UdpBackend{
		sm:      sm,
		network: network,
		config:  config,
		ctx:     ctx,
		cancel:  cancel,
	}
	be.cfg.Port = defaultPort
	return &be
}
开发者ID:rajatchopra,项目名称:flannel,代码行数:13,代码来源:udp.go


示例16: New

func New(sm subnet.Manager, network string, config *subnet.Config) backend.Backend {
	ctx, cancel := context.WithCancel(context.Background())

	vb := &VXLANBackend{
		sm:      sm,
		network: network,
		config:  config,
		ctx:     ctx,
		cancel:  cancel,
	}
	vb.cfg.VNI = defaultVNI

	return vb
}
开发者ID:rajatchopra,项目名称:flannel,代码行数:14,代码来源:vxlan.go


示例17: TestAddReservation

func TestAddReservation(t *testing.T) {
	msr := newDummyRegistry()
	sm := NewMockManager(msr)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	r := Reservation{
		Subnet:   newIP4Net("10.4.3.0", 24),
		PublicIP: ip.MustParseIP4("52.195.12.13"),
	}
	if err := sm.AddReservation(ctx, "_", &r); err == nil {
		t.Fatalf("unexpectedly added a reservation outside of configured network")
	}

	r.Subnet = newIP4Net("10.3.10.0", 24)
	if err := sm.AddReservation(ctx, "_", &r); err != nil {
		t.Fatalf("failed to add reservation: %v", err)
	}

	// Add the same reservation -- should succeed
	if err := sm.AddReservation(ctx, "_", &r); err != nil {
		t.Fatalf("failed to add reservation: %v", err)
	}

	// Add a reservation with a different public IP -- should fail
	r2 := r
	r2.PublicIP = ip.MustParseIP4("52.195.12.17")
	if err := sm.AddReservation(ctx, "_", &r2); err != ErrLeaseTaken {
		t.Fatalf("taken add reservation returned: %v", err)
	}

	attrs := &LeaseAttrs{
		PublicIP: r.PublicIP,
	}
	l, err := sm.AcquireLease(ctx, "_", attrs)
	if err != nil {
		t.Fatalf("failed to acquire subnet: %v", err)
	}
	if !l.Subnet.Equal(r.Subnet) {
		t.Fatalf("acquired subnet is not the reserved one: expected %v, got %v", r.Subnet, l.Subnet)
	}
	if !l.Expiration.IsZero() {
		t.Fatalf("acquired lease (prev reserved) has expiration set")
	}
}
开发者ID:erickcantwell,项目名称:flannel,代码行数:46,代码来源:subnet_test.go


示例18: doTestWatch

func doTestWatch(t *testing.T, sm subnet.Manager) {
	ctx, cancel := context.WithCancel(context.Background())
	wg := sync.WaitGroup{}
	wg.Add(1)
	defer func() {
		cancel()
		wg.Wait()
	}()

	events := make(chan []subnet.Event)
	go func() {
		subnet.WatchLeases(ctx, sm, "_", nil, events)
		wg.Done()
	}()

	// skip over the initial snapshot
	<-events

	attrs := &subnet.LeaseAttrs{
		PublicIP: mustParseIP4("1.1.1.2"),
	}
	l, err := sm.AcquireLease(ctx, "_", attrs)
	if err != nil {
		t.Errorf("AcquireLease failed: %v", err)
		return
	}
	if !mustParseIP4Net(expectedNetwork).Contains(l.Subnet.IP) {
		t.Errorf("AcquireLease returned subnet not in network: %v (in %v)", l.Subnet, expectedNetwork)
	}

	evtBatch := <-events

	if len(evtBatch) != 1 {
		t.Fatalf("WatchSubnets produced wrong sized event batch")
	}

	evt := evtBatch[0]
	if evt.Type != subnet.SubnetAdded {
		t.Fatalf("WatchSubnets produced wrong event type")
	}

	if evt.Lease.Key() != l.Key() {
		t.Errorf("WatchSubnet produced wrong subnet: expected %s, got %s", l.Key(), evt.Lease.Key())
	}
}
开发者ID:nathanleiby,项目名称:flannel,代码行数:45,代码来源:remote_test.go


示例19: TestWatchLeaseAdded

func TestWatchLeaseAdded(t *testing.T) {
	msr := newDummyRegistry()
	sm := NewMockManager(msr)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	l := acquireLease(ctx, t, sm)

	events := make(chan []Event)
	go WatchLeases(ctx, sm, "_", l, events)

	evtBatch := <-events
	for _, evt := range evtBatch {
		if evt.Lease.Key() == l.Key() {
			t.Errorf("WatchLeases returned our own lease")
		}
	}

	expected := ip.IP4Net{
		IP:        ip.MustParseIP4("10.3.6.0"),
		PrefixLen: 24,
	}
	attrs := &LeaseAttrs{
		PublicIP: ip.MustParseIP4("1.1.1.1"),
	}
	msr.createSubnet(ctx, "_", expected, attrs, 0)

	evtBatch = <-events

	if len(evtBatch) != 1 {
		t.Fatalf("WatchLeases produced wrong sized event batch")
	}

	evt := evtBatch[0]

	if evt.Type != EventAdded {
		t.Fatalf("WatchLeases produced wrong event type")
	}

	actual := evt.Lease.Subnet
	if !actual.Equal(expected) {
		t.Errorf("WatchSubnet produced wrong subnet: expected %s, got %s", expected, actual)
	}
}
开发者ID:erickcantwell,项目名称:flannel,代码行数:45,代码来源:subnet_test.go


示例20: newFixture

func newFixture(t *testing.T) *fixture {
	f := &fixture{}

	config := fmt.Sprintf(`{"Network": %q}`, expectedNetwork)
	f.registry = subnet.NewMockRegistry("", config, nil)
	sm := subnet.NewMockManager(f.registry)

	f.srvAddr = "127.0.0.1:9999"

	f.ctx, f.cancel = context.WithCancel(context.Background())
	f.wg.Add(1)
	go func() {
		RunServer(f.ctx, sm, f.srvAddr, "", "", "")
		f.wg.Done()
	}()

	var err error
	f.sm, err = NewRemoteManager(f.srvAddr, "", "", "")
	if err != nil {
		panic(fmt.Sprintf("Failed to create remote mananager: %v", err))
	}

	for i := 0; ; i++ {
		_, err := f.sm.GetNetworkConfig(f.ctx, "_")
		if err == nil {
			break
		}

		if isConnRefused(err) {
			if i == 100 {
				t.Fatalf("Out of connection retries")
			}

			fmt.Println("Connection refused, retrying...")
			time.Sleep(300 * time.Millisecond)
			continue
		}

		t.Fatalf("GetNetworkConfig failed: %v", err)
	}

	return f
}
开发者ID:vanloswang,项目名称:flannel,代码行数:43,代码来源:remote_test.go



注:本文中的github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context.WithCancel函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang context.Context类代码示例发布时间:2022-05-23
下一篇:
Golang context.Background函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap