Ejemplo n.º 1
1
// redis-cli对monitor指令进行特殊处理,只要monitor不断输出StatusReply,可以实现不间断的流输出
// 适用于海量数据的扫描输出,比如iterator扫描整个数据库
func (server *GoRedisServer) OnMONITOR(session *Session, cmd *Command) (reply *Reply) {
	// 特殊使用,monitor输出全部key
	if cmd.Len() > 1 {
		switch strings.ToUpper(cmd.StringAtIndex(1)) {
		case "KEYS":
			server.monitorKeys(session, cmd)
		default:
			reply = ErrorReply("bad monitor command")
			go func() {
				time.Sleep(time.Millisecond * 100)
				session.Close()
			}()
		}
		return
	}

	session.WriteReply(StatusReply("OK"))
	client := NewMonClient(session)
	remoteHost := session.RemoteAddr().String()

	go func() {
		stdlog.Printf("[%s] monitor start\n", remoteHost)
		// sleep一下,避免启动瞬间输出 +1394530022.495448 [0 127.0.0.1:51980] "monitor"
		time.Sleep(time.Millisecond * 10)
		server.monmgr.Put(remoteHost, client)
		client.Start()
		server.monmgr.Remove(remoteHost)
		stdlog.Printf("[%s] monitor exit\n", remoteHost)
	}()

	return
}
Ejemplo n.º 2
1
func TestPause(t *testing.T) {
	log.SetOutput(ioutil.Discard)
	defer log.SetOutput(os.Stdout)

	_, _, nsqd := mustStartNSQD(NewNSQDOptions())
	defer nsqd.Exit()

	topicName := "test_topic_pause" + strconv.Itoa(int(time.Now().Unix()))
	topic := nsqd.GetTopic(topicName)
	err := topic.Pause()
	assert.Equal(t, err, nil)

	channel := topic.GetChannel("ch1")
	assert.NotEqual(t, channel, nil)

	msg := nsq.NewMessage(<-nsqd.idChan, []byte("aaaaaaaaaaaaaaaaaaaaaaaaaaa"))
	err = topic.PutMessage(msg)
	assert.Equal(t, err, nil)

	time.Sleep(15 * time.Millisecond)

	assert.Equal(t, topic.Depth(), int64(1))
	assert.Equal(t, channel.Depth(), int64(0))

	err = topic.UnPause()
	assert.Equal(t, err, nil)

	time.Sleep(15 * time.Millisecond)

	assert.Equal(t, topic.Depth(), int64(0))
	assert.Equal(t, channel.Depth(), int64(1))
}
Ejemplo n.º 3
1
func configurer(done chan bool, errLog, infoLog chan string, config chan configTask, configName string) {
	var (
		fd  *os.File
		err error
		//		settings     settingsBlock
		configBlocks []*configBlock
	)
	for {
		select {
		case <-done:
			return
		default:
			if fd, err = os.Open(configName); err != nil {
				errLog <- fmt.Sprintf("can't read configuration from %s", configName)
				time.Sleep(waitForValidConfigFile)
			}
			_, configBlocks, err = parseConfigFile(fd)
			// XXX compare with prev parsed blocks (или делать это в контроллере)
			if err != nil {
				errLog <- err.Error()
			}
			for _, b := range configBlocks {
				fmt.Printf("%+v %+v\n", b, b.Checks)
			}
			time.Sleep(1 * time.Second)
		}
	}
}
Ejemplo n.º 4
1
func TestBackToInitialFilter(t *testing.T) {
	_, guard := setDummyScreen()
	defer guard()

	ctx := newCtx(nil, 25)
	defer ctx.Stop()

	ctx.config.Keymap["C-q"] = "peco.BackToInitialFilter"
	ctx.startInput()
	if ctx.filters.current != 0 {
		t.Errorf("Expected filter to be at position 0, got %d", ctx.filters.current)
		return
	}

	screen.SendEvent(termbox.Event{Key: termbox.KeyCtrlR})
	time.Sleep(time.Second)
	if ctx.filters.current != 1 {
		t.Errorf("Expected filter to be at position 1, got %d", ctx.filters.current)
		return
	}

	screen.SendEvent(termbox.Event{Key: termbox.KeyCtrlQ})
	time.Sleep(time.Second)
	if ctx.filters.current != 0 {
		t.Errorf("Expected filter to be at position 0, got %d", ctx.filters.current)
		return
	}
}
Ejemplo n.º 5
1
// New Go Routine based server with auth
func RunServerWithAuth(opts *server.Options, auth server.Auth) *server.Server {
	if opts == nil {
		opts = &DefaultTestOptions
	}
	s := server.New(opts)
	if s == nil {
		panic("No NATS Server object returned.")
	}

	if auth != nil {
		s.SetAuthMethod(auth)
	}

	// Run server in Go routine.
	go s.Start()

	end := time.Now().Add(10 * time.Second)
	for time.Now().Before(end) {
		addr := s.Addr()
		if addr == nil {
			time.Sleep(50 * time.Millisecond)
			// Retry. We might take a little while to open a connection.
			continue
		}
		conn, err := net.Dial("tcp", addr.String())
		if err != nil {
			// Retry after 50ms
			time.Sleep(50 * time.Millisecond)
			continue
		}
		conn.Close()
		return s
	}
	panic("Unable to start NATS Server in Go Routine")
}
Ejemplo n.º 6
1
func (m *MonstiService) EmitSignal(args *Receive, ret *[][]byte) error {
	*ret = make([][]byte, len(m.subscriptions[args.Name]))
	for i, id := range m.subscriptions[args.Name] {
		retChan := make(chan emitRet)
		done := false
		go func() {
			time.Sleep(time.Second)
			for !done {
				time.Sleep(30 * time.Second)
				m.Logger.Printf(
					"Waiting for signal response. Signal: %v, Subscriber: %v",
					args.Name, id)
			}
		}()
		m.subscriber[id] <- &signal{args.Name, args.Args, retChan}
		emitRet := <-retChan
		if len(emitRet.Error) > 0 {
			done = true
			return fmt.Errorf("Received error as signal response: %v", emitRet.Error)
		}
		(*ret)[i] = emitRet.Ret
		done = true
	}
	return nil
}
Ejemplo n.º 7
1
func IsLeaderAlive(currentLeader string) {

	if retryCount > 0 {
		fmt.Println("Trying......", retryCount)
		transport := http.Transport{
			Dial: dialTimeout,
		}

		client := http.Client{
			Transport: &transport,
		}

		url := fmt.Sprintf("http://localhost:%s/isalive", currentLeader)
		res, err := client.Get(url)

		if err != nil {

			time.Sleep(5000 * time.Millisecond)
			retryCount--
			IsLeaderAlive(currentLeader)
		}

		fmt.Println("Response Status:", res.StatusCode)
		if res.StatusCode == 200 {
			time.Sleep(5000 * time.Millisecond)
			IsLeaderAlive(currentLeader)
		}
	} else {
		resp, _ := http.Get("http://localhost:9999/flushall")
		resp.Body.Close()
		initiateElection()
	}
}
Ejemplo n.º 8
0
func main() {
	input_channel := make(chan interface{})
	go func() {
		for i := 0; i < 100; i++ {
			// This helps reveal time-dependant bugs
			time.Sleep(1000000)
			input_channel <- i
		}
		close(input_channel)
	}()
	result := mapreduce.MapReduce(
		func(x interface{}, output chan interface{}) {
			fmt.Println("Mapping ", x)
			time.Sleep(100000000)
			output <- x.(int) * x.(int)
		},
		func(input chan interface{}, output chan interface{}) {
			total := 0
			for item := range input {
				fmt.Println("Reducing: ", item.(int))
				total += item.(int)
			}
			output <- total
		},
		input_channel, 10)

	if result.(int) != 328350 {
		fmt.Println(result.(int), "Unexpected MapReduce result")
	} else {
		fmt.Println("OK")
	}
}
Ejemplo n.º 9
0
func (s *DockerSuite) TestRestartContainerwithRestartPolicy(c *check.C) {
	out1, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false")
	out2, _ := dockerCmd(c, "run", "-d", "--restart=always", "busybox", "false")

	id1 := strings.TrimSpace(string(out1))
	id2 := strings.TrimSpace(string(out2))
	err := waitInspect(id1, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 30*time.Second)
	c.Assert(err, checker.IsNil)

	// TODO: fix racey problem during restart:
	// https://jenkins.dockerproject.org/job/Docker-PRs-Win2Lin/24665/console
	// Error response from daemon: Cannot restart container 6655f620d90b390527db23c0a15b3e46d86a58ecec20a5697ab228d860174251: remove /var/run/docker/libcontainerd/6655f620d90b390527db23c0a15b3e46d86a58ecec20a5697ab228d860174251/rootfs: device or resource busy
	if _, _, err := dockerCmdWithError("restart", id1); err != nil {
		// if restart met racey problem, try again
		time.Sleep(500 * time.Millisecond)
		dockerCmd(c, "restart", id1)
	}
	if _, _, err := dockerCmdWithError("restart", id2); err != nil {
		// if restart met racey problem, try again
		time.Sleep(500 * time.Millisecond)
		dockerCmd(c, "restart", id2)
	}

	dockerCmd(c, "stop", id1)
	dockerCmd(c, "stop", id2)
	dockerCmd(c, "start", id1)
	dockerCmd(c, "start", id2)
}
Ejemplo n.º 10
0
func (b *board) initBoard() {
	for {
		b.queryFirmware()
		time.Sleep(50 * time.Millisecond)
		b.readAndProcess()
		if len(b.findEvents("firmware_query")) > 0 {
			break
		}
	}
	for {
		b.queryCapabilities()
		time.Sleep(50 * time.Millisecond)
		b.readAndProcess()
		if len(b.findEvents("capability_query")) > 0 {
			break
		}
	}
	for {
		b.queryAnalogMapping()
		time.Sleep(50 * time.Millisecond)
		b.readAndProcess()
		if len(b.findEvents("analog_mapping_query")) > 0 {
			break
		}
	}
	b.togglePinReporting(0, High, ReportDigital)
	time.Sleep(50 * time.Millisecond)
	b.togglePinReporting(1, High, ReportDigital)
	time.Sleep(50 * time.Millisecond)
}
Ejemplo n.º 11
0
func RedisDo(commandName string, args ...interface{}) (interface{}, error) {

	var redisConn redis.Conn
	var err error

	for i := 0; i < redisRetryCount; i++ {
		if redisConn, err = redis.Dial("tcp", redisAddress); err != nil {
			fog.Warn("redis.Dial: %s", err)
			time.Sleep(5 * time.Second)
			continue
		}

		result, err := redisConn.Do(commandName, args...)
		redisConn.Close()
		if err != nil {
			fog.Warn("RedisDo: %s", err)
			time.Sleep(1 * time.Second)
			continue
		}

		return result, nil
	}

	return nil, fmt.Errorf("RedisDo: failed after %d retries %s",
		redisRetryCount, err)
}
Ejemplo n.º 12
0
func join(c *cli.Context) {
	dflag := getDiscovery(c)
	if dflag == "" {
		log.Fatalf("discovery required to join a cluster. See '%s join --help'.", c.App.Name)
	}

	addr := c.String("advertise")
	if addr == "" {
		log.Fatal("missing mandatory --advertise flag")
	}
	if !checkAddrFormat(addr) {
		log.Fatal("--advertise should be of the form ip:port or hostname:port")
	}

	joinDelay, err := time.ParseDuration(c.String("delay"))
	if err != nil {
		log.Fatalf("invalid --delay: %v", err)
	}
	if joinDelay < time.Duration(0)*time.Second {
		log.Fatalf("--delay should not be a negative number")
	}

	hb, err := time.ParseDuration(c.String("heartbeat"))
	if err != nil {
		log.Fatalf("invalid --heartbeat: %v", err)
	}
	if hb < 1*time.Second {
		log.Fatal("--heartbeat should be at least one second")
	}
	ttl, err := time.ParseDuration(c.String("ttl"))
	if err != nil {
		log.Fatalf("invalid --ttl: %v", err)
	}
	if ttl <= hb {
		log.Fatal("--ttl must be strictly superior to the heartbeat value")
	}

	d, err := discovery.New(dflag, hb, ttl, getDiscoveryOpt(c))
	if err != nil {
		log.Fatal(err)
	}

	// if joinDelay is 0, no delay will be executed
	// if joinDelay is larger than 0,
	// add a random delay between 0s and joinDelay at start to avoid synchronized registration
	if joinDelay > 0 {
		r := rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
		delay := time.Duration(r.Int63n(int64(joinDelay)))
		log.Infof("Add a random delay %s to avoid synchronized registration", delay)
		time.Sleep(delay)
	}

	for {
		log.WithFields(log.Fields{"addr": addr, "discovery": dflag}).Infof("Registering on the discovery service every %s...", hb)
		if err := d.Register(addr); err != nil {
			log.Error(err)
		}
		time.Sleep(hb)
	}
}
Ejemplo n.º 13
0
func (self *ProtobufClient) readResponses() {
	message := make([]byte, 0, MAX_RESPONSE_SIZE)
	buff := bytes.NewBuffer(message)
	for !self.stopped {
		buff.Reset()
		conn := self.getConnection()
		if conn == nil {
			time.Sleep(200 * time.Millisecond)
			continue
		}
		var messageSizeU uint32
		var err error
		err = binary.Read(conn, binary.LittleEndian, &messageSizeU)
		if err != nil {
			log.Error("Error while reading messsage size: %d", err)
			time.Sleep(200 * time.Millisecond)
			continue
		}
		messageSize := int64(messageSizeU)
		messageReader := io.LimitReader(conn, messageSize)
		_, err = io.Copy(buff, messageReader)
		if err != nil {
			log.Error("Error while reading message: %d", err)
			time.Sleep(200 * time.Millisecond)
			continue
		}
		response, err := protocol.DecodeResponse(buff)
		if err != nil {
			log.Error("error unmarshaling response: %s", err)
			time.Sleep(200 * time.Millisecond)
		} else {
			self.sendResponse(response)
		}
	}
}
Ejemplo n.º 14
0
func main() {
	c := make(chan int)
	quit := make(chan int)
	go func() {
		for i := 0; i < 10; i++ {
			time.Sleep(100 * time.Millisecond)
			fmt.Printf("%d, %d\n", i, <-c) // ここで読み出すと、case c <- x が評価され、fibonacci内のloopが回る
		}
		quit <- 0
	}()
	fibonacci(c, quit)

	tick := time.Tick(100 * time.Millisecond)
	boom := time.After(500 * time.Millisecond)
	for {
		select {
		case <-tick:
			fmt.Println("tick.")
		case <-boom:
			fmt.Println("BOOM!")
			return
		default:
			fmt.Println("    .")
			time.Sleep(50 * time.Millisecond)
		}
	}
}
Ejemplo n.º 15
0
// waitInspect will wait for the specified container to have the specified string
// in the inspect output. It will wait until the specified timeout (in seconds)
// is reached.
func waitInspect(name, expr, expected string, timeout time.Duration) error {
	after := time.After(timeout)

	for {
		cmd := exec.Command(dockerBinary, "inspect", "-f", expr, name)
		out, _, err := runCommandWithOutput(cmd)
		if err != nil {
			if !strings.Contains(out, "No such") {
				return fmt.Errorf("error executing docker inspect: %v\n%s", err, out)
			}
			select {
			case <-after:
				return err
			default:
				time.Sleep(10 * time.Millisecond)
				continue
			}
		}

		out = strings.TrimSpace(out)
		if out == expected {
			break
		}

		select {
		case <-after:
			return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected)
		default:
		}

		time.Sleep(100 * time.Millisecond)
	}
	return nil
}
Ejemplo n.º 16
0
func waitForSync() {
	for {
		Trace.Println("Waiting for Sync")
		r, err := http.NewRequest("GET", target+"/rest/system/config/insync", nil)
		res, err := performRequest(r)
		defer func() {
			if res != nil && res.Body != nil {
				res.Body.Close()
			}
		}()
		if err != nil {
			Warning.Println("Failed to perform request /rest/system/config/insync", err)
			time.Sleep(configSyncTimeout)
			continue
		}
		if res.StatusCode != 200 {
			Warning.Printf("Status %d != 200 for GET", res.StatusCode)
			time.Sleep(configSyncTimeout)
			continue
		}
		bs, err := ioutil.ReadAll(res.Body)
		if err != nil {
			time.Sleep(configSyncTimeout)
			continue
		}
		var inSync map[string]bool
		err = json.Unmarshal(bs, &inSync)
		if inSync["configInSync"] {
			return
		}
		time.Sleep(configSyncTimeout)
	}
}
Ejemplo n.º 17
0
func TestClientHeartbeat(t *testing.T) {
	heartbeatInterval = 10 * time.Millisecond
	addr, err := net.ResolveTCPAddr("tcp", testAddr)
	if err != nil {
		t.Fatalf("invalid test server address %s: %s", testAddr, err)
	}
	s := NewServer(addr)
	go s.ListenAndServe()
	// Delve into rpc server struct to ensure we get correct address since we're
	// picking an unused port. If we don't wait for the server to start listening,
	// the address will be incorrect.
	<-s.listening
	c := NewClient(s.Addr())
	time.Sleep(heartbeatInterval * 2)
	if c != NewClient(s.Addr()) {
		t.Error("expected cached client to be returned while healthy")
	}
	s.Close()
	c.Close()

	// Wait for the heartbeat interval, which should see a failure on
	// the client. Then get a new client and verify it's a new client
	// struct.
	time.Sleep(heartbeatInterval + 1*time.Millisecond)
	if c == NewClient(s.Addr()) {
		t.Error("expected failed client to not be returned in 2nd call to NewClient")
	}
}
Ejemplo n.º 18
0
func (self *ServerSuite) TestRestartAfterCompaction(c *C) {
	data := `
  [{
    "points": [[1]],
    "name": "test_restart_after_compaction",
    "columns": ["val"]
  }]
  `
	self.serverProcesses[0].Post("/db/test_rep/series?u=paul&p=pass", data, c)

	collection := self.serverProcesses[0].Query("test_rep", "select * from test_restart_after_compaction", false, c)
	c.Assert(collection.Members, HasLen, 1)
	series := collection.GetSeries("test_restart_after_compaction", c)
	c.Assert(series.Points, HasLen, 1)
	resp := self.serverProcesses[0].Post("/raft/force_compaction?u=root&p=root", "", c)
	c.Assert(resp.StatusCode, Equals, http.StatusOK)
	self.serverProcesses[0].Stop()
	time.Sleep(time.Second)
	self.serverProcesses[0].Start()
	time.Sleep(time.Second * 3)

	collection = self.serverProcesses[0].Query("test_rep", "select * from test_restart_after_compaction", false, c)
	c.Assert(collection.Members, HasLen, 1)
	series = collection.GetSeries("test_restart_after_compaction", c)
	c.Assert(series.Points, HasLen, 1)
}
Ejemplo n.º 19
0
func (s *DockerSuite) TestEventsTimestampFormats(c *check.C) {
	name := "events-time-format-test"

	// Start stopwatch, generate an event
	start := daemonTime(c)
	time.Sleep(1100 * time.Millisecond) // so that first event occur in different second from since (just for the case)
	dockerCmd(c, "run", "--rm", "--name", name, "busybox", "true")
	time.Sleep(1100 * time.Millisecond) // so that until > since
	end := daemonTime(c)

	// List of available time formats to --since
	unixTs := func(t time.Time) string { return fmt.Sprintf("%v", t.Unix()) }
	rfc3339 := func(t time.Time) string { return t.Format(time.RFC3339) }
	duration := func(t time.Time) string { return time.Now().Sub(t).String() }

	// --since=$start must contain only the 'untag' event
	for _, f := range []func(time.Time) string{unixTs, rfc3339, duration} {
		since, until := f(start), f(end)
		out, _ := dockerCmd(c, "events", "--since="+since, "--until="+until)
		events := strings.Split(out, "\n")
		events = events[:len(events)-1]

		nEvents := len(events)
		c.Assert(nEvents, checker.GreaterOrEqualThan, 5) //Missing expected event
		containerEvents := eventActionsByIDAndType(c, events, name, "container")
		c.Assert(containerEvents, checker.HasLen, 5, check.Commentf("events: %v", events))

		c.Assert(containerEvents[0], checker.Equals, "create", check.Commentf(out))
		c.Assert(containerEvents[1], checker.Equals, "attach", check.Commentf(out))
		c.Assert(containerEvents[2], checker.Equals, "start", check.Commentf(out))
		c.Assert(containerEvents[3], checker.Equals, "die", check.Commentf(out))
		c.Assert(containerEvents[4], checker.Equals, "destroy", check.Commentf(out))
	}
}
Ejemplo n.º 20
0
// For issue #140 https://github.com/influxdb/influxdb/issues/140
func (self *ServerSuite) TestRestartServers(c *C) {
	data := `
  [{
    "points": [[1]],
    "name": "test_restart",
    "columns": ["val"]
  }]
  `
	self.serverProcesses[0].Post("/db/test_rep/series?u=paul&p=pass", data, c)

	collection := self.serverProcesses[0].Query("test_rep", "select * from test_restart", false, c)
	c.Assert(collection.Members, HasLen, 1)
	series := collection.GetSeries("test_restart", c)
	c.Assert(series.Points, HasLen, 1)

	for _, s := range self.serverProcesses {
		s.Stop()
	}
	time.Sleep(time.Second)

	err := self.serverProcesses[0].Start()
	c.Assert(err, IsNil)
	time.Sleep(time.Second)
	err = self.serverProcesses[1].Start()
	c.Assert(err, IsNil)
	err = self.serverProcesses[2].Start()
	time.Sleep(time.Second * 5)

	collection = self.serverProcesses[0].Query("test_rep", "select * from test_restart", false, c)
	c.Assert(collection.Members, HasLen, 1)
	series = collection.GetSeries("test_restart", c)
	c.Assert(series.Points, HasLen, 1)
}
Ejemplo n.º 21
0
func TestDoAcceptChar(t *testing.T) {
	_, guard := setDummyScreen()
	defer guard()

	ctx := newCtx(nil, 25)
	defer ctx.Stop()
	ctx.startInput()

	message := "Hello, World!"
	writeQueryToPrompt(t, message)
	time.Sleep(500 * time.Millisecond)

	if qs := ctx.QueryString(); qs != message {
		t.Errorf("Expected query to be populated as '%s', but got '%s'", message, qs)
	}

	ctx.MoveCaretPos(-1 * len("World!"))
	writeQueryToPrompt(t, "Cruel ")

	time.Sleep(500 * time.Millisecond)

	expected := "Hello, Cruel World!"
	if qs := ctx.QueryString(); qs != expected {
		t.Errorf("Expected query to be populated as '%s', but got '%s'", expected, qs)
	}
}
Ejemplo n.º 22
0
func (self *ServerSuite) TestDropSeries(c *C) {
	for i := 0; i < 2; i++ {
		self.serverProcesses[0].Post("/db?u=root&p=root", `{"name": "drop_series", "replicationFactor": 3}`, c)
		self.serverProcesses[0].Post("/db/drop_series/users?u=root&p=root", `{"name": "paul", "password": "******"}`, c)
		data := `[{
		"name": "cluster_query",
		"columns": ["val1"],
		"points": [[1]]
		}]`
		self.serverProcesses[0].Post("/db/drop_series/series?u=paul&p=pass", data, c)
		time.Sleep(time.Second)
		if i == 0 {
			fmt.Printf("Using the http api\n")
			resp := self.serverProcesses[0].Request("DELETE", "/db/drop_series/series/cluster_query?u=root&p=root", "", c)
			c.Assert(resp.StatusCode, Equals, http.StatusNoContent)
		} else {
			fmt.Printf("Using the drop series\n")
			self.serverProcesses[0].Query("drop_series", "drop series cluster_query", false, c)
		}
		time.Sleep(time.Second)
		for _, s := range self.serverProcesses {
			fmt.Printf("Running query against: %d\n", s.apiPort)
			collection := s.Query("drop_series", "select * from cluster_query", true, c)
			c.Assert(collection.Members, HasLen, 0)
		}
	}
}
Ejemplo n.º 23
0
// #18453
func (s *DockerSuite) TestEventsContainerFilterBeforeCreate(c *check.C) {
	testRequires(c, DaemonIsLinux)
	var (
		out string
		ch  chan struct{}
	)
	ch = make(chan struct{})

	// calculate the time it takes to create and start a container and sleep 2 seconds
	// this is to make sure the docker event will recevie the event of container
	since := daemonTime(c).Unix()
	id, _ := dockerCmd(c, "run", "-d", "busybox", "top")
	cID := strings.TrimSpace(id)
	waitRun(cID)
	time.Sleep(2 * time.Second)
	duration := daemonTime(c).Unix() - since

	go func() {
		out, _ = dockerCmd(c, "events", "-f", "container=foo", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()+2*duration))
		close(ch)
	}()
	// Sleep 2 second to wait docker event to start
	time.Sleep(2 * time.Second)
	id, _ = dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top")
	cID = strings.TrimSpace(id)
	waitRun(cID)
	<-ch
	c.Assert(out, checker.Contains, cID, check.Commentf("Missing event of container (foo)"))
}
Ejemplo n.º 24
0
func TestCache(t *testing.T) {
	foobar := "foobar"
	Set("foobar", foobar, time.Duration(10*time.Second))
	obj, err := Get("foobar")
	if err != nil {
		t.Error(err)
	}

	str, ok := obj.(string)
	if !ok {
		t.Error("Type assertions error")
	}
	if str != foobar {
		t.Error("Set/Get were not conform.")
	}
	go Set("foobar", foobar, time.Duration(1*time.Microsecond))
	time.Sleep(20 * time.Microsecond)
	obj, err = Get("foobar")
	if err == nil {
		t.Error("Time out is not working.")
	}

	go Set("foobar", foobar, time.Duration(1*time.Microsecond))
	time.Sleep(time.Minute)
	if HasKey("foobar") {
		t.Error("GC is not working.")
	}
}
Ejemplo n.º 25
0
func main() {
	worker, _ := zmq.NewSocket(zmq.REQ)
	defer worker.Close()

	//  Set random identity to make tracing easier
	rand.Seed(time.Now().UnixNano())
	identity := fmt.Sprintf("%04X-%04X", rand.Intn(0x10000), rand.Intn(0x10000))
	worker.SetIdentity(identity)
	worker.Connect("tcp://localhost:5556")

	//  Tell broker we're ready for work
	fmt.Printf("I: (%s) worker ready\n", identity)
	worker.Send(WORKER_READY, 0)

	for cycles := 0; true; {
		msg, err := worker.RecvMessage(0)
		if err != nil {
			break //  Interrupted
		}

		//  Simulate various problems, after a few cycles
		cycles++
		if cycles > 3 && rand.Intn(5) == 0 {
			fmt.Printf("I: (%s) simulating a crash\n", identity)
			break
		} else if cycles > 3 && rand.Intn(5) == 0 {
			fmt.Printf("I: (%s) simulating CPU overload\n", identity)
			time.Sleep(3 * time.Second)
		}

		fmt.Printf("I: (%s) normal reply\n", identity)
		time.Sleep(time.Second) //  Do some heavy work
		worker.SendMessage(msg)
	}
}
Ejemplo n.º 26
0
func main() {
	c1 := make(chan string, 3)
	c2 := make(chan string, 3)

	go func() {
		time.Sleep(time.Second * 2)
		c1 <- "c1 resource"
	}()

	select {
	case msg := <-c1:
		fmt.Println(msg)
	case <-time.After(time.Second * 2):
		fmt.Println("timeout 2")
	}

	go func() {
		time.Sleep(time.Second * 1)
		c2 <- "c2 resource"
	}()

	select {
	case msg := <-c2:
		fmt.Println(msg)
	case <-time.After(time.Second * 3):
		fmt.Println("timeout 3")
	}

}
Ejemplo n.º 27
0
func (d *Driver) Start() error {
	log.Debugf("Starting VM %s", d.MachineName)
	d.validateVMRef()
	err := d.VM.Create()
	if err != nil {
		log.Warnf("Failed to start: %s", err)
		return err
	}

	// They wont start immediately
	time.Sleep(5 * time.Second)

	for i := 0; i < 90; i++ {
		time.Sleep(time.Second)
		ip, _ := d.GetIP()
		if ip != "" {
			// Add a second to let things settle
			time.Sleep(time.Second)
			return nil
		}
		log.Debugf("Waiting for the VM to come up... %d", i)
	}
	log.Warnf("Unable to determine VM's IP address, did it fail to boot?")
	return err
}
Ejemplo n.º 28
0
func fileWriter(t *testing.T, file *os.File, logs []string) {
	filename := file.Name()
	time.Sleep(1 * time.Second) // wait for start Tail...

	for _, line := range logs {
		if strings.Index(line, RotateMarker) != -1 {
			log.Println("fileWriter: rename file => file.old")
			os.Rename(filename, filename+".old")
			file.Close()
			file, _ = os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0644)
			log.Println("fileWriter: re-opened file")
		} else if strings.Index(line, TruncateMarker) != -1 {
			time.Sleep(1 * time.Second)
			log.Println("fileWriter: truncate(file, 0)")
			os.Truncate(filename, 0)
			file.Seek(int64(0), os.SEEK_SET)
		}
		_, err := file.WriteString(line)
		log.Print("fileWriter: wrote ", line)
		if err != nil {
			log.Println("write failed", err)
		}
		time.Sleep(1 * time.Millisecond)
	}
	file.Close()
}
Ejemplo n.º 29
0
func (S) TestAttemptNextHasNext(c *C) {
	a := aws.AttemptStrategy{}.Start()
	c.Assert(a.Next(), Equals, true)
	c.Assert(a.Next(), Equals, false)

	a = aws.AttemptStrategy{}.Start()
	c.Assert(a.Next(), Equals, true)
	c.Assert(a.HasNext(), Equals, false)
	c.Assert(a.Next(), Equals, false)

	a = aws.AttemptStrategy{Total: 2e8}.Start()
	c.Assert(a.Next(), Equals, true)
	c.Assert(a.HasNext(), Equals, true)
	time.Sleep(2e8)
	c.Assert(a.HasNext(), Equals, true)
	c.Assert(a.Next(), Equals, true)
	c.Assert(a.Next(), Equals, false)

	a = aws.AttemptStrategy{Total: 1e8, Min: 2}.Start()
	time.Sleep(1e8)
	c.Assert(a.Next(), Equals, true)
	c.Assert(a.HasNext(), Equals, true)
	c.Assert(a.Next(), Equals, true)
	c.Assert(a.HasNext(), Equals, false)
	c.Assert(a.Next(), Equals, false)
}
Ejemplo n.º 30
0
func TestSelectDuplicateChannel(t *testing.T) {
	// This test makes sure we can queue a G on
	// the same channel multiple times.
	c := make(chan int)
	d := make(chan int)
	e := make(chan int)

	// goroutine A
	go func() {
		select {
		case <-c:
		case <-c:
		case <-d:
		}
		e <- 9
	}()
	time.Sleep(time.Millisecond) // make sure goroutine A gets qeueued first on c

	// goroutine B
	go func() {
		<-c
	}()
	time.Sleep(time.Millisecond) // make sure goroutine B gets queued on c before continuing

	d <- 7 // wake up A, it dequeues itself from c.  This operation used to corrupt c.recvq.
	<-e    // A tells us it's done
	c <- 8 // wake up B.  This operation used to fail because c.recvq was corrupted (it tries to wake up an already running G instead of B)
}