Browse code

Add default timeout to pkg/plugins/client

Signed-off-by: Chun Chen <ramichen@tencent.com>

Chun Chen authored on 2016/08/17 12:25:25
Showing 2 changed files
... ...
@@ -16,7 +16,8 @@ import (
16 16
 )
17 17
 
18 18
 const (
19
-	defaultTimeOut = 30
19
+	defaultTimeOut     = 30
20
+	defaultHTTPTimeOut = 32 * time.Second
20 21
 )
21 22
 
22 23
 // NewClient creates a new plugin client (http).
... ...
@@ -53,6 +54,7 @@ func NewClient(addr string, tlsConfig *tlsconfig.Options) (*Client, error) {
53 53
 func NewClientWithTransport(tr transport.Transport) *Client {
54 54
 	return &Client{
55 55
 		http: &http.Client{
56
+			Timeout:   defaultHTTPTimeOut,
56 57
 			Transport: tr,
57 58
 		},
58 59
 		requestFactory: tr,
... ...
@@ -6,6 +6,7 @@ import (
6 6
 	"net/http/httptest"
7 7
 	"net/url"
8 8
 	"reflect"
9
+	"strings"
9 10
 	"testing"
10 11
 	"time"
11 12
 
... ...
@@ -30,6 +31,26 @@ func teardownRemotePluginServer() {
30 30
 	}
31 31
 }
32 32
 
33
+func TestHttpTimeout(t *testing.T) {
34
+	addr := setupRemotePluginServer()
35
+	defer teardownRemotePluginServer()
36
+	stop := false // we need this variable to stop the http server
37
+	mux.HandleFunc("/hang", func(w http.ResponseWriter, r *http.Request) {
38
+		for {
39
+			if stop {
40
+				break
41
+			}
42
+			time.Sleep(5 * time.Second)
43
+		}
44
+	})
45
+	c, _ := NewClient(addr, &tlsconfig.Options{InsecureSkipVerify: true})
46
+	_, err := c.callWithRetry("hang", nil, false)
47
+	stop = true
48
+	if err == nil || !strings.Contains(err.Error(), "request canceled") {
49
+		t.Fatalf("The request should be canceled %v", err)
50
+	}
51
+}
52
+
33 53
 func TestFailedConnection(t *testing.T) {
34 54
 	c, _ := NewClient("tcp://127.0.0.1:1", &tlsconfig.Options{InsecureSkipVerify: true})
35 55
 	_, err := c.callWithRetry("Service.Method", nil, false)