Beispiel #1
0
func (s *S) TestRemoveUnits(c *gocheck.C) {
	var calls int32
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		v := atomic.LoadInt32(&calls)
		atomic.StoreInt32(&calls, v+1)
		w.WriteHeader(http.StatusNoContent)
	}))
	srvc := service.Service{Name: "mysql", Endpoint: map[string]string{"production": ts.URL}}
	err := srvc.Create()
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Services().Remove(bson.M{"_id": "mysql"})
	app := App{
		Name:      "chemistry",
		Framework: "python",
	}
	instance := service.ServiceInstance{
		Name:        "my-inst",
		ServiceName: "mysql",
		Teams:       []string{s.team.Name},
		Apps:        []string{app.Name},
	}
	instance.Create()
	defer s.conn.ServiceInstances().Remove(bson.M{"name": "my-inst"})
	err = s.conn.Apps().Insert(app)
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Apps().Remove(bson.M{"name": app.Name})
	c.Assert(err, gocheck.IsNil)
	s.provisioner.Provision(&app)
	defer s.provisioner.Destroy(&app)
	app.AddUnits(4)
	otherApp := App{Name: app.Name, Units: app.Units}
	err = otherApp.RemoveUnits(2)
	c.Assert(err, gocheck.IsNil)
	ts.Close()
	units := s.provisioner.GetUnits(&app)
	c.Assert(units, gocheck.HasLen, 3) // when you provision you already have one, so it's 4+1-2 (in provisioner, in app struct we have 2)
	c.Assert(units[0].Name, gocheck.Equals, "chemistry/0")
	c.Assert(units[1].Name, gocheck.Equals, "chemistry/3")
	c.Assert(units[2].Name, gocheck.Equals, "chemistry/4")
	err = app.Get()
	c.Assert(err, gocheck.IsNil)
	c.Assert(app.Framework, gocheck.Equals, "python")
	c.Assert(app.Units, gocheck.HasLen, 2)
	c.Assert(app.Units[0].Name, gocheck.Equals, "chemistry/3")
	c.Assert(app.Units[1].Name, gocheck.Equals, "chemistry/4")
	ok := make(chan int8)
	go func() {
		for _ = range time.Tick(1e3) {
			if atomic.LoadInt32(&calls) == 2 {
				ok <- 1
				return
			}
		}
	}()
	select {
	case <-ok:
	case <-time.After(2e9):
		c.Fatal("Did not call service endpoint twice.")
	}
}
Beispiel #2
0
func (s *S) TestPiler(c *check.C) {
	epsilon := 0.95
	for _, f := range []PileFilter{
		nil,
		func(a, b *feat.Feature, pa, pb *PileInterval) bool {
			lpa := float64(pa.End - pa.Start)
			lpb := float64(pb.End - pb.Start)

			return float64(a.Len()) >= lpa*epsilon || float64(b.Len()) >= lpb*epsilon
		},
	} {
		p := NewPiler(0)
		for _, fp := range testPairs {
			err := p.Add(fp)
			if err != nil {
				c.Fatal(err)
			}
		}

		piles, err := p.Piles(f)
		if err != nil {
			c.Fatal(err)
		}

		for i, pi := range piles {
			c.Logf("%d %v", i, pi)
			for _, fp := range pi.Images {
				c.Logf("\t%v", fp)
				c.Check(fp.A.Meta, check.DeepEquals, pi)
			}
		}
	}
}
Beispiel #3
0
func (s *QueryBuilderSuite) TestGetItemQuery(c *gocheck.C) {
	primary := dynamodb.NewStringAttribute("domain", "")
	key := dynamodb.PrimaryKey{primary, nil}
	table := s.server.NewTable("sites", key)

	q := dynamodb.NewQuery(table)
	q.AddKey(table, &dynamodb.Key{HashKey: "test"})

	queryJson, err := simplejson.NewJson([]byte(q.String()))
	if err != nil {
		c.Fatal(err)
	}

	expectedJson, err := simplejson.NewJson([]byte(`
{
	"Key": {
		"domain": {
			"S": "test"
		}
	},
	"TableName": "sites"
}
	`))
	if err != nil {
		c.Fatal(err)
	}
	c.Check(queryJson, gocheck.DeepEquals, expectedJson)
}
Beispiel #4
0
func (s *S) TestWrite(c *check.C) {
	b := &B{&bytes.Buffer{}}
	w := NewWriter(b, 0, 60, false)
	for _, t := range T {
		if f1, err := featureOf(ps, t.start, t.end, false); err != nil {
			c.Fatal(err)
		} else {
			if f2, err := featureOf(ps, t.start, t.end, false); err != nil {
				c.Fatal(err)
			} else {
				n, err := w.Write(&FeaturePair{A: f1, B: f2})
				c.Check(n, check.Not(check.Equals), 0)
				c.Check(err, check.Equals, nil)
			}
		}
	}
	c.Check(string(b.Bytes()), check.Equals, "")
	w.Close()
	c.Check(string(b.Bytes()), check.Equals,
		`deBruijn2	pals	hit	1	6	0.0000	.	.	Target deBruijn2 1 6; maxe 0
deBruijn2	pals	hit	2	6	0.0000	.	.	Target deBruijn2 2 6; maxe 0
deBruijn2	pals	hit	1	16	0.0000	.	.	Target deBruijn2 1 16; maxe 0
deBruijn1	pals	hit	1	4	0.0000	.	.	Target deBruijn1 1 4; maxe 0
deBruijn5	pals	hit	1	904	0.0000	.	.	Target deBruijn5 1 904; maxe 0
deBruijn8	pals	hit	1025	4095	0.0000	.	.	Target deBruijn8 1025 4095; maxe 0
`)
}
Beispiel #5
0
// Tests
func (s *S) TestHash(c *check.C) {
	var (
		err     error
		f       *os.File
		md5hash []byte
	)

	// FIXME: This will not work with MacOS.
	if _, err = exec.LookPath("md5sum"); err != nil {
		c.Skip(err.Error())
	}
	md5sum := exec.Command("md5sum", "./files_test.go")
	b := &bytes.Buffer{}
	md5sum.Stdout = b
	if err = md5sum.Run(); err != nil {
		c.Fatal(err)
	}
	if f, err = os.Open("./files_test.go"); err != nil {
		c.Fatalf("%v %s", md5sum, err)
	}
	if md5hash, err = Hash(md5.New(), f); err != nil {
		c.Fatal(err)
	}
	md5string := fmt.Sprintf("%x .*\n", md5hash)

	c.Check(string(b.Bytes()), check.Matches, md5string)
}
Beispiel #6
0
func (s *S) TestKmerFrequencies(c *check.C) {
	for k := MinKmerLen; k <= MaxKmerLen; k++ {
		if i, err := New(k, s.Seq); err != nil {
			c.Fatalf("New KmerIndex failed: %v", err)
		} else {
			freqs, ok := i.KmerFrequencies()
			c.Check(ok, check.Equals, true)
			hashFreqs := make(map[string]int)
			for i := 0; i+k <= s.Seq.Len(); i++ {
				hashFreqs[string(s.Seq.Seq[i:i+k])]++
			}
			for key := range freqs {
				if freqs[key] != hashFreqs[i.Stringify(key)] {
					c.Logf("seq %s\n", s.Seq)
					c.Logf("key %x, string of %q\n", key, i.Stringify(key))
				}
				c.Check(freqs[key], check.Equals, hashFreqs[i.Stringify(key)])
			}
			for key := range hashFreqs {
				if keyKmer, err := i.KmerOf(key); err != nil {
					c.Fatal(err)
				} else {
					if freqs[keyKmer] != hashFreqs[key] {
						c.Logf("seq %s\n", s.Seq)
						c.Logf("keyKmer %x, string of %q, key %q\n", keyKmer, i.Stringify(keyKmer), key)
					}
					c.Check(freqs[keyKmer], check.Equals, hashFreqs[key])
				}
			}
		}
	}
}
Beispiel #7
0
func (s *S) TestWeightedTimeSeeded(c *check.C) {
	c.Log("Note: This test is stochastic and is expected to fail with probability ≈ 0.05.")
	rand.Seed(time.Now().Unix())
	f := make([]float64, len(sel))
	ts := make(Selector, len(sel))

	for i := 0; i < 1e6; i++ {
		copy(ts, sel)
		ts.Init()
		item, err := ts.Select()
		if err != nil {
			c.Fatal(err)
		}
		f[item-1]++
	}

	fsum, exsum := 0., 0.
	for i := range f {
		fsum += f[i]
		exsum += exp[i]
	}
	fac := fsum / exsum
	for i := range f {
		exp[i] *= fac
	}

	// Check that our obtained values are within statistical expectations for p = 0.05.
	// This will not be true approximately 1 in 20 tests.
	X := chi2(f, exp)
	c.Logf("H₀: d(Sample) = d(Expect), H₁: d(S) ≠ d(Expect). df = %d, p = 0.05, X² threshold = %.2f, X² = %f", len(f)-1, sigChi2, X)
	c.Check(X < sigChi2, check.Equals, true)
}
Beispiel #8
0
func (s *S) TestCreateTokenRemoveOldTokens(c *gocheck.C) {
	config.Set("auth:max-simultaneous-sessions", 2)
	u := User{Email: "*****@*****.**", Password: "******"}
	err := u.Create()
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Users().Remove(bson.M{"email": u.Email})
	defer s.conn.Tokens().RemoveAll(bson.M{"useremail": u.Email})
	t1, err := newUserToken(&u)
	c.Assert(err, gocheck.IsNil)
	t2 := t1
	t2.Token += "aa"
	err = s.conn.Tokens().Insert(t1, t2)
	_, err = u.CreateToken("123456")
	c.Assert(err, gocheck.IsNil)
	ok := make(chan bool, 1)
	go func() {
		for {
			ct, err := s.conn.Tokens().Find(bson.M{"useremail": u.Email}).Count()
			c.Assert(err, gocheck.IsNil)
			if ct == 2 {
				ok <- true
				return
			}
			runtime.Gosched()
		}
	}()
	select {
	case <-ok:
	case <-time.After(2e9):
		c.Fatal("Did not remove old tokens after 2 seconds")
	}
}
Beispiel #9
0
func (s *S) TestProvisionerDestroy(c *gocheck.C) {
	err := newImage("tsuru/python", s.server.URL())
	c.Assert(err, gocheck.IsNil)
	cont, err := s.newContainer(nil)
	c.Assert(err, gocheck.IsNil)
	app := testing.NewFakeApp(cont.AppName, "python", 1)
	var p dockerProvisioner
	p.Provision(app)
	c.Assert(p.Destroy(app), gocheck.IsNil)
	ok := make(chan bool, 1)
	go func() {
		coll := collection()
		defer coll.Close()
		for {
			ct, err := coll.Find(bson.M{"appname": cont.AppName}).Count()
			if err != nil {
				c.Fatal(err)
			}
			if ct == 0 {
				ok <- true
				return
			}
			runtime.Gosched()
		}
	}()
	select {
	case <-ok:
	case <-time.After(10e9):
		c.Fatal("Timed out waiting for the container to be destroyed (10 seconds)")
	}
	c.Assert(rtesting.FakeRouter.HasBackend("myapp"), gocheck.Equals, false)
}
Beispiel #10
0
func (s *AmazonServer) SetUp(c *gocheck.C) {
	auth, err := aws.EnvAuth()
	if err != nil {
		c.Fatal(err)
	}
	s.auth = auth
}
Beispiel #11
0
func (s *S) TestUndirectedConnectedComponent(c *check.C) {
	g := undirected(c, uv)
	f := func(_ Edge) bool { return true }
	c.Check(len(g.ConnectedComponents(f)), check.Equals, 1)
	g.DeleteByID(deleteNode)
	nodes, edges := make(map[int]int), make(map[int]int)
	for _, n := range uv {
		nodes[n.u], nodes[n.v] = 1, 1
		edges[n.u]++
		edges[n.v]++
	}
	c.Check(g.Order(), check.Equals, len(nodes)-1)
	c.Check(g.Size(), check.Equals, len(uv)-edges[deleteNode])
	cc := g.ConnectedComponents(f)
	c.Check(len(cc), check.Equals, 2)
	for i, p := range cc {
		c.Check(len(p), check.Equals, partSizes[i])
		for _, n := range p {
			c.Check(parts[n.ID()], check.Equals, i)
		}
		g0, err := p.BuildUndirected(true)
		if err != nil {
			c.Fatal(err)
		}
		c.Check(g0.Order(), check.Equals, partSizes[i])
		c.Check(g0.Size(), check.Equals, partSizes[i])
	}
}
func (s *S) TestCollectStatusIDChangeFromPending(c *gocheck.C) {
	server, url := badGatewayServer()
	defer server.Close()
	tmpdir, err := commandmocker.Add("juju", generateOutput(url))
	c.Assert(err, gocheck.IsNil)
	defer commandmocker.Remove(tmpdir)
	p := JujuProvisioner{}
	collection := p.unitsCollection()
	defer collection.Close()
	err = collection.Insert(instance{UnitName: "as_i_rise/0", InstanceID: "pending"})
	c.Assert(err, gocheck.IsNil)
	defer collection.Remove(bson.M{"_id": bson.M{"$in": []string{"as_i_rise/0", "the_infanta/0"}}})
	_, err = p.CollectStatus()
	c.Assert(err, gocheck.IsNil)
	done := make(chan int8)
	go func() {
		for {
			q := bson.M{"_id": "as_i_rise/0", "instanceid": "i-00000439"}
			ct, err := collection.Find(q).Count()
			c.Assert(err, gocheck.IsNil)
			if ct == 1 {
				done <- 1
				return
			}
			runtime.Gosched()
		}
	}()
	select {
	case <-done:
	case <-time.After(5e9):
		c.Fatal("Did not update the unit after 5 seconds.")
	}
}
Beispiel #13
0
func (s *S) TestCollectStatusIDChangeDisabledELB(c *gocheck.C) {
	tmpdir, err := commandmocker.Add("juju", collectOutput)
	c.Assert(err, gocheck.IsNil)
	defer commandmocker.Remove(tmpdir)
	p := JujuProvisioner{}
	conn, collection := p.unitsCollection()
	defer conn.Close()
	err = collection.Insert(instance{UnitName: "as_i_rise/0", InstanceId: "i-00000239"})
	c.Assert(err, gocheck.IsNil)
	defer collection.Remove(bson.M{"_id": bson.M{"$in": []string{"as_i_rise/0", "the_infanta/0"}}})
	_, err = p.CollectStatus()
	c.Assert(err, gocheck.IsNil)
	done := make(chan int8)
	go func() {
		for {
			q := bson.M{"_id": "as_i_rise/0", "instanceid": "i-00000439"}
			ct, err := collection.Find(q).Count()
			c.Assert(err, gocheck.IsNil)
			if ct == 1 {
				done <- 1
				return
			}
			time.Sleep(1e3)
		}
	}()
	select {
	case <-done:
	case <-time.After(5e9):
		c.Fatal("Did not update the unit after 5 seconds.")
	}
}
Beispiel #14
0
func (s *DynamoDBTest) WaitUntilStatus(c *gocheck.C, status string) {
	// We should wait until the table is in specified status because a real DynamoDB has some delay for ready
	done := make(chan bool)
	timeout := time.After(TIMEOUT)
	go func() {
		for {
			select {
			case <-done:
				return
			default:
				desc, err := s.table.DescribeTable()
				if err != nil {
					c.Fatal(err)
				}
				if desc.TableStatus == status {
					done <- true
					return
				}
				time.Sleep(5 * time.Second)
			}
		}
	}()
	select {
	case <-done:
		break
	case <-timeout:
		c.Errorf("Expect a status to be %s, but timed out", status)
		close(done)
	}
}
Beispiel #15
0
func (s *S) TestProvisionerProvision(c *gocheck.C) {
	config.Set("local:authorized-key-path", "somepath")
	rfs := &fstesting.RecordingFs{}
	fsystem = rfs
	defer func() {
		fsystem = nil
	}()
	f, _ := os.Open("testdata/dnsmasq.leases")
	data, err := ioutil.ReadAll(f)
	c.Assert(err, gocheck.IsNil)
	file, err := rfs.Create("/var/lib/misc/dnsmasq.leases")
	c.Assert(err, gocheck.IsNil)
	_, err = file.Write(data)
	c.Assert(err, gocheck.IsNil)
	tmpdir, err := commandmocker.Add("sudo", "$*")
	c.Assert(err, gocheck.IsNil)
	defer commandmocker.Remove(tmpdir)
	sshTempDir, err := commandmocker.Add("ssh", "$*")
	c.Assert(err, gocheck.IsNil)
	defer commandmocker.Remove(sshTempDir)
	scpTempDir, err := commandmocker.Add("scp", "$*")
	c.Assert(err, gocheck.IsNil)
	defer commandmocker.Remove(scpTempDir)
	var p LocalProvisioner
	app := testing.NewFakeApp("myapp", "python", 0)
	defer p.collection().Remove(bson.M{"name": "myapp"})
	c.Assert(p.Provision(app), gocheck.IsNil)
	ok := make(chan bool, 1)
	go func() {
		for {
			coll := s.conn.Collection(s.collName)
			ct, err := coll.Find(bson.M{"name": "myapp", "status": provision.StatusStarted}).Count()
			if err != nil {
				c.Fatal(err)
			}
			if ct > 0 {
				ok <- true
				return
			}
			time.Sleep(1e3)
		}
	}()
	select {
	case <-ok:
	case <-time.After(10e9):
		c.Fatal("Timed out waiting for the container to be provisioned (10 seconds)")
	}
	c.Assert(commandmocker.Ran(tmpdir), gocheck.Equals, true)
	expected := "lxc-create -t ubuntu -n myapp -- -S somepath"
	expected += "lxc-start --daemon -n myapp"
	expected += "service nginx restart"
	c.Assert(commandmocker.Output(tmpdir), gocheck.Equals, expected)
	var unit provision.Unit
	err = s.conn.Collection(s.collName).Find(bson.M{"name": "myapp"}).One(&unit)
	c.Assert(err, gocheck.IsNil)
	c.Assert(unit.Ip, gocheck.Equals, "10.10.10.15")
}
Beispiel #16
0
func (s *S) TestFeaturise(c *check.C) {
	for _, t := range T {
		f, err := featureOf(ps, t.start, t.end, false)
		if err != nil {
			c.Fatal(err)
		}
		c.Check(f.String(), check.Equals, t.result)
	}
}
func (s *ELBSuite) TestCollectStatusWithELBAndIDChange(c *gocheck.C) {
	a := testing.NewFakeApp("symfonia", "symfonia", 0)
	p := JujuProvisioner{}
	router, err := Router()
	c.Assert(err, gocheck.IsNil)
	err = router.AddBackend(a.GetName())
	c.Assert(err, gocheck.IsNil)
	defer router.RemoveBackend(a.GetName())
	id1 := s.server.NewInstance()
	defer s.server.RemoveInstance(id1)
	id2 := s.server.NewInstance()
	defer s.server.RemoveInstance(id2)
	id3 := s.server.NewInstance()
	defer s.server.RemoveInstance(id3)
	collection := p.unitsCollection()
	defer collection.Close()
	err = collection.Insert(instance{UnitName: "symfonia/0", InstanceID: id3})
	c.Assert(err, gocheck.IsNil)
	err = router.AddRoute(a.GetName(), id3)
	c.Assert(err, gocheck.IsNil)
	err = router.AddRoute(a.GetName(), id2)
	c.Assert(err, gocheck.IsNil)
	q := bson.M{"_id": bson.M{"$in": []string{"symfonia/0", "symfonia/1", "symfonia/2", "raise/0"}}}
	defer collection.Remove(q)
	output := strings.Replace(simpleCollectOutput, "i-00004444", id1, 1)
	output = strings.Replace(output, "i-00004445", id2, 1)
	tmpdir, err := commandmocker.Add("juju", output)
	c.Assert(err, gocheck.IsNil)
	defer commandmocker.Remove(tmpdir)
	_, err = p.CollectStatus()
	c.Assert(err, gocheck.IsNil)
	done := make(chan int8)
	go func() {
		for {
			q := bson.M{"_id": "symfonia/0", "instanceid": id1}
			ct, err := collection.Find(q).Count()
			c.Assert(err, gocheck.IsNil)
			if ct == 1 {
				done <- 1
				return
			}
			runtime.Gosched()
		}
	}()
	select {
	case <-done:
	case <-time.After(5e9):
		c.Fatal("Did not save the unit after 5 seconds.")
	}
	resp, err := s.client.DescribeLoadBalancers(a.GetName())
	c.Assert(err, gocheck.IsNil)
	c.Assert(resp.LoadBalancerDescriptions, gocheck.HasLen, 1)
	instances := resp.LoadBalancerDescriptions[0].Instances
	c.Assert(instances, gocheck.HasLen, 2)
	c.Assert(instances[0].InstanceId, gocheck.Equals, id2)
	c.Assert(instances[1].InstanceId, gocheck.Equals, id1)
}
Beispiel #18
0
func (s *LiveSuite) SetUpSuite(c *gocheck.C) {
	if !Amazon {
		c.Skip("amazon tests not enabled (-amazon flag)")
	}
	auth, err := aws.EnvAuth()
	if err != nil {
		c.Fatal(err.Error())
	}
	s.auth = auth
}
Beispiel #19
0
func (s *SuiteI) SetUpSuite(c *gocheck.C) {
	if !*integration {
		c.Skip("Integration tests not enabled (-int flag)")
	}
	auth, err := aws.EnvAuth()
	if err != nil {
		c.Fatal(err)
	}
	s.auth = auth
}
func (s *S) TestNotifyFiltered(c *gocheck.C) {
	var logs struct {
		l []interface{}
		sync.Mutex
	}
	app := App{Name: "fade"}
	l, err := NewLogListener(&app, Applog{Source: "tsuru", Unit: "unit1"})
	c.Assert(err, gocheck.IsNil)
	defer l.Close()
	go func() {
		for log := range l.C {
			logs.Lock()
			logs.l = append(logs.l, log)
			logs.Unlock()
		}
	}()
	t := time.Date(2014, 7, 10, 15, 0, 0, 0, time.UTC)
	ms := []interface{}{
		Applog{Date: t, Message: "Something went wrong. Check it out:", Source: "tsuru", Unit: "unit1"},
		Applog{Date: t, Message: "This program has performed an illegal operation.", Source: "other", Unit: "unit1"},
		Applog{Date: t, Message: "Last one.", Source: "tsuru", Unit: "unit2"},
	}
	notify(app.Name, ms)
	done := make(chan bool, 1)
	q := make(chan bool)
	go func(quit chan bool) {
		for _ = range time.Tick(1e3) {
			select {
			case <-quit:
				return
			default:
			}
			logs.Lock()
			if len(logs.l) == 1 {
				logs.Unlock()
				done <- true
				return
			}
			logs.Unlock()
		}
	}(q)
	select {
	case <-done:
	case <-time.After(2e9):
		defer close(q)
		c.Fatal("Timed out.")
	}
	logs.Lock()
	defer logs.Unlock()
	expected := []interface{}{
		Applog{Date: t, Message: "Something went wrong. Check it out:", Source: "tsuru", Unit: "unit1"},
	}
	c.Assert(logs.l, gocheck.DeepEquals, expected)
}
func (s *TestSuite) TestCustomJSONMarshals(c *gocheck.C) {
	/* Heartbeat (for Heartbeat request/response) */
	var hb, hB *Heartbeat
	hb = &Heartbeat{time.Now()}
	js, err := hb.MarshalJSON()
	c.Assert(err, gocheck.IsNil)
	err = json.Unmarshal(js, &hB)
	c.Assert(err, gocheck.IsNil)
	if hb.Timestamp.UnixNano()/1e6 != hB.Timestamp.UnixNano()/1e6 {
		c.Fatal("Timestamp changed during Marshal/Unmarshal")
	}
}
Beispiel #22
0
func (s *UpgradeSuite) TestDowngradeOnMasterWhenOtherStateServerDoesntStartUpgrade(c *gc.C) {
	// This test checks that the master triggers a downgrade if one of
	// the other state server fails to signal it is ready for upgrade.
	//
	// This test is functional, ensuring that the upgrader worker
	// terminates the machine agent with the UpgradeReadyError which
	// makes the downgrade happen.

	// Speed up the watcher frequency to make the test much faster.
	s.PatchValue(&watcher.Period, 200*time.Millisecond)

	// Provide (fake) tools so that the upgrader has something to downgrade to.
	envtesting.AssertUploadFakeToolsVersions(c, s.Environ.Storage(), s.oldVersion)

	// Only the first machine is going to be ready for upgrade.
	machineIdA, machineIdB, _ := s.createUpgradingStateServers(c)

	// One of the other state servers is ready for upgrade (but machine C doesn't).
	info, err := s.State.EnsureUpgradeInfo(machineIdB, s.oldVersion.Number, version.Current.Number)
	c.Assert(err, gc.IsNil)

	agent := s.newAgentFromMachineId(c, machineIdA)
	defer agent.Stop()

	s.machineIsMaster = true

	var agentErr error
	agentDone := make(chan bool)
	go func() {
		agentErr = agent.Run(nil)
		close(agentDone)
	}()

	select {
	case <-agentDone:
		upgradeReadyErr, ok := agentErr.(*upgrader.UpgradeReadyError)
		if !ok {
			c.Fatalf("didn't see UpgradeReadyError, instead got: %v", agentErr)
		}
		// Confirm that the downgrade is back to the previous version.
		c.Assert(upgradeReadyErr.OldTools, gc.Equals, version.Current)
		c.Assert(upgradeReadyErr.NewTools, gc.Equals, s.oldVersion)

	case <-time.After(coretesting.LongWait):
		c.Fatal("machine agent did not exit as expected")
	}

	// UpgradeInfo doc should now be archived.
	err = info.Refresh()
	c.Assert(err, gc.ErrorMatches, "current upgrade info not found")
}
Beispiel #23
0
func (s *S) TestUndirectedMerge(c *check.C) {
	g := undirected(c, uv)
	order := g.Order()
	size := g.Size()
	err := g.Merge(g.Node(7), g.Node(9))
	if err != nil {
		c.Fatal(err)
	}
	conn, err := g.ConnectingEdges(g.Node(7), g.Node(7))
	if err != nil {
		c.Fatal(err)
	}
	c.Check(len(conn), check.Equals, 1)
	c.Check(conn[0].String(), check.Equals, "7--7")
	c.Check(g.Order(), check.Equals, order-1)
	c.Check(g.Size(), check.Equals, size)
	c.Check(g.Node(7).Degree(), check.Equals, 6)
	c.Check(len(g.Node(7).Edges()), check.Equals, 5)

	err = g.Merge(g.Node(6), g.Node(3))
	if err != nil {
		c.Fatal(err)
	}
	conn, err = g.ConnectingEdges(g.Node(7), g.Node(6))
	if err != nil {
		c.Fatal(err)
	}
	c.Check(len(conn), check.Equals, 2)
}
Beispiel #24
0
func (s *PublishSuite) TestInferURL(c *gc.C) {
	addMeta(c, s.branch, "")

	cmd := &PublishCommand{}
	cmd.ChangePushLocation(func(location string) string {
		c.Assert(location, gc.Equals, "lp:charms/precise/wordpress")
		c.SucceedNow()
		panic("unreachable")
	})

	_, err := testing.RunCommandInDir(c, envcmd.Wrap(cmd), []string{"precise/wordpress"}, s.dir)
	c.Assert(err, gc.IsNil)
	c.Fatal("shouldn't get here; location closure didn't run?")
}
Beispiel #25
0
func (s *S) TestProvisionerDestroy(c *gocheck.C) {
	fexec := &etesting.FakeExecutor{}
	execut = fexec
	defer func() {
		execut = nil
	}()
	w := new(bytes.Buffer)
	l := stdlog.New(w, "", stdlog.LstdFlags)
	log.SetLogger(l)
	app := testing.NewFakeApp("myapp", "python", 1)
	u := provision.Unit{
		Name:       app.ProvisionUnits()[0].GetName(),
		AppName:    app.GetName(),
		Machine:    app.ProvisionUnits()[0].GetMachine(),
		InstanceId: app.ProvisionUnits()[0].GetInstanceId(),
		Status:     provision.StatusCreating,
	}
	err := s.conn.Collection(s.collName).Insert(&u)
	c.Assert(err, gocheck.IsNil)
	img := image{Name: app.GetName()}
	err = s.conn.Collection(s.imageCollName).Insert(&img)
	c.Assert(err, gocheck.IsNil)
	var p DockerProvisioner
	c.Assert(p.Destroy(app), gocheck.IsNil)
	ok := make(chan bool, 1)
	go func() {
		for {
			coll := s.conn.Collection(s.collName)
			ct, err := coll.Find(bson.M{"name": u.Name}).Count()
			if err != nil {
				c.Fatal(err)
			}
			if ct == 0 {
				ok <- true
				return
			}
			runtime.Gosched()
		}
	}()
	select {
	case <-ok:
	case <-time.After(10e9):
		c.Error("Timed out waiting for the container to be destroyed (10 seconds)")
	}
	args := []string{"stop", "i-01"}
	c.Assert(fexec.ExecutedCmd("docker", args), gocheck.Equals, true)
	args = []string{"rm", "i-01"}
	c.Assert(fexec.ExecutedCmd("docker", args), gocheck.Equals, true)
}
Beispiel #26
0
func (s *S) TestUndirectedConnected(c *check.C) {
	g := undirected(c, uv)
	n := g.Nodes()
	conns := 0
	for i := 0; i < g.Order(); i++ {
		for j := 0; j < g.Order(); j++ {
			if ok, err := g.Connected(n[i], n[j]); ok {
				conns++
			} else if err != nil {
				c.Fatal(err)
			}
		}
	}
	c.Check(conns, check.Equals, 2*g.Size()+g.Order())
}
Beispiel #27
0
Datei: mgo.go Projekt: jkary/core
func (s *MgoSuite) TearDownTest(c *gc.C) {
	MgoServer.Reset()
	s.Session.Close()
	for i := 0; ; i++ {
		stats := mgo.GetStats()
		if stats.SocketsInUse == 0 && stats.SocketsAlive == 0 {
			break
		}
		if i == 20 {
			c.Fatal("Test left sockets in a dirty state")
		}
		c.Logf("Waiting for sockets to die: %d in use, %d alive", stats.SocketsInUse, stats.SocketsAlive)
		time.Sleep(500 * time.Millisecond)
	}
}
Beispiel #28
0
func (s *S) TestNotify(c *gocheck.C) {
	var logs struct {
		l []interface{}
		sync.Mutex
	}
	app := App{Name: "fade"}
	l := NewLogListener(&app)
	defer l.Close()
	go func() {
		for log := range l.C {
			logs.Lock()
			logs.l = append(logs.l, log)
			logs.Unlock()
		}
	}()
	ms := []interface{}{
		Applog{Date: time.Now(), Message: "Something went wrong. Check it out:", Source: "tsuru"},
		Applog{Date: time.Now(), Message: "This program has performed an illegal operation.", Source: "tsuru"},
	}
	notify(app.Name, ms)
	done := make(chan bool, 1)
	q := make(chan bool)
	go func(quit chan bool) {
		for _ = range time.Tick(1e3) {
			select {
			case <-quit:
				return
			default:
			}
			logs.Lock()
			if len(logs.l) == 2 {
				logs.Unlock()
				done <- true
				return
			}
			logs.Unlock()
		}
	}(q)
	select {
	case <-done:
	case <-time.After(2e9):
		defer close(q)
		c.Fatal("Timed out.")
	}
	logs.Lock()
	defer logs.Unlock()
	c.Assert(logs.l, gocheck.DeepEquals, ms)
}
Beispiel #29
0
func (s *S) TestProvisionerDestroy(c *gocheck.C) {
	fexec := &etesting.FakeExecutor{}
	setExecut(fexec)
	defer setExecut(nil)
	w := new(bytes.Buffer)
	l := stdlog.New(w, "", stdlog.LstdFlags)
	log.SetLogger(l)
	app := testing.NewFakeApp("myapp", "python", 1)
	cont := container{
		Id:      app.ProvisionUnits()[0].GetName(),
		AppName: app.GetName(),
	}
	err := s.conn.Collection(s.collName).Insert(cont)
	c.Assert(err, gocheck.IsNil)
	defer s.conn.Collection(s.collName).RemoveId(cont.Id)
	s.conn.Collection(s.collName).Insert(container{Id: "something-01", AppName: app.GetName()})
	defer s.conn.Collection(s.collName).RemoveId("something-01")
	img := image{Name: app.GetName()}
	err = s.conn.Collection(s.imageCollName).Insert(&img)
	c.Assert(err, gocheck.IsNil)
	var p dockerProvisioner
	p.Provision(app)
	c.Assert(p.Destroy(app), gocheck.IsNil)
	ok := make(chan bool, 1)
	go func() {
		coll := s.conn.Collection(s.collName)
		for {
			ct, err := coll.Find(bson.M{"appname": cont.AppName}).Count()
			if err != nil {
				c.Fatal(err)
			}
			if ct == 0 {
				ok <- true
				return
			}
			runtime.Gosched()
		}
	}()
	select {
	case <-ok:
	case <-time.After(10e9):
		c.Fatal("Timed out waiting for the container to be destroyed (10 seconds)")
	}
	args := []string{"rm", "myapp/0"}
	c.Assert(fexec.ExecutedCmd("docker", args), gocheck.Equals, true)
	c.Assert(rtesting.FakeRouter.HasBackend("myapp"), gocheck.Equals, false)
}
Beispiel #30
0
func (s *S) TestUndirectedBuild(c *check.C) {
	g := undirected(c, uv)
	g0, err := g.Nodes().BuildUndirected(false)
	if err != nil {
		c.Fatal(err)
	}
	for _, n := range g.Nodes() {
		id := n.ID()
		c.Check(g0.Node(id).ID(), check.Equals, g.Node(id).ID())
	}
	for i := range g.Edges() {
		c.Check(g0.Edge(i).ID(), check.Equals, i)
		c.Check(g0.Edge(i).ID(), check.Equals, g.Edge(i).ID())
		c.Check(g0.Edge(i).Head().ID(), check.Equals, g.Edge(i).Head().ID())
		c.Check(g0.Edge(i).Tail().ID(), check.Equals, g.Edge(i).Tail().ID())
	}
}