Ver código fonte

use non-blocking channel to prevent dead-lock and add test for server

Victor Vieux 12 anos atrás
pai
commit
040c3b50d0
2 arquivos alterados com 44 adições e 1 exclusões
  1. 4 1
      server.go
  2. 40 0
      server_test.go

+ 4 - 1
server.go

@@ -1185,7 +1185,10 @@ func (srv *Server) LogEvent(action, id string) {
 	jm := utils.JSONMessage{Status: action, ID: id, Time: now}
 	srv.events = append(srv.events, jm)
 	for _, c := range srv.listeners {
-		c <- jm
+		select { // non blocking channel
+		case c <- jm:
+		default:
+		}
 	}
 }
 

+ 40 - 0
server_test.go

@@ -1,7 +1,9 @@
 package docker
 
 import (
+	"github.com/dotcloud/docker/utils"
 	"testing"
+	"time"
 )
 
 func TestContainerTagImageDelete(t *testing.T) {
@@ -163,3 +165,41 @@ func TestRunWithTooLowMemoryLimit(t *testing.T) {
 	}
 
 }
+
+func TestLogEvent(t *testing.T) {
+	runtime := mkRuntime(t)
+	srv := &Server{
+		runtime:   runtime,
+		events:    make([]utils.JSONMessage, 0, 64),
+		listeners: make(map[string]chan utils.JSONMessage),
+	}
+
+	srv.LogEvent("fakeaction", "fakeid")
+
+	listener := make(chan utils.JSONMessage)
+	srv.Lock()
+	srv.listeners["test"] = listener
+	srv.Unlock()
+
+	srv.LogEvent("fakeaction2", "fakeid")
+
+	if len(srv.events) != 2 {
+		t.Fatalf("Expected 2 events, found %d", len(srv.events))
+	}
+	go func() {
+		time.Sleep(200 * time.Millisecond)
+		srv.LogEvent("fakeaction3", "fakeid")
+		time.Sleep(200 * time.Millisecond)
+		srv.LogEvent("fakeaction4", "fakeid")
+	}()
+
+	setTimeout(t, "Listening for events timed out", 2*time.Second, func() {
+		for i := 2; i < 4; i++ {
+			event := <-listener
+			if event != srv.events[i] {
+				t.Fatalf("Event received it different than expected")
+			}
+		}
+	})
+
+}