Index: rpc/jsoncodec/codec.go |
=== modified file 'rpc/jsoncodec/codec.go' |
--- rpc/jsoncodec/codec.go 2013-05-28 07:01:54 +0000 |
+++ rpc/jsoncodec/codec.go 2013-06-19 07:54:00 +0000 |
@@ -8,6 +8,7 @@ |
"launchpad.net/juju-core/log" |
"launchpad.net/juju-core/rpc" |
"sync" |
+ "sync/atomic" |
) |
// JSONConn sends and receives messages to an underlying connection |
@@ -20,26 +21,39 @@ |
Close() error |
} |
-var logRequests = true |
- |
-// codec implements rpc.Codec for a connection. |
-type codec struct { |
+// Codec implements rpc.Codec for a connection. |
+type Codec struct { |
// msg holds the message that's just been read by ReadHeader, so |
// that the body can be read by ReadBody. |
- msg inMsg |
- conn JSONConn |
- mu sync.Mutex |
- closing bool |
+ msg inMsg |
+ conn JSONConn |
+ logMessages int32 |
+ mu sync.Mutex |
+ closing bool |
} |
// New returns an rpc codec that uses conn to send and receive |
// messages. |
-func New(conn JSONConn) rpc.Codec { |
- return &codec{ |
+func New(conn JSONConn) *Codec { |
+ return &Codec{ |
conn: conn, |
} |
} |
+// SetLogging sets whether messages will be logged |
+// by the codec. |
+func (c *Codec) SetLogging(on bool) { |
+ val := int32(0) |
+ if on { |
+ val = 1 |
+ } |
+ atomic.StoreInt32(&c.logMessages, val) |
+} |
+ |
+func (c *Codec) isLogging() bool { |
+ return atomic.LoadInt32(&c.logMessages) != 0 |
+} |
+ |
// inMsg holds an incoming message. We don't know the type of the |
// parameters or response yet, so we delay parsing by storing them |
// in a RawMessage. |
@@ -66,23 +80,23 @@ |
Response interface{} `json:",omitempty"` |
} |
-func (c *codec) Close() error { |
+func (c *Codec) Close() error { |
c.mu.Lock() |
c.closing = true |
c.mu.Unlock() |
return c.conn.Close() |
} |
-func (c *codec) isClosing() bool { |
+func (c *Codec) isClosing() bool { |
c.mu.Lock() |
defer c.mu.Unlock() |
return c.closing |
} |
-func (c *codec) ReadHeader(hdr *rpc.Header) error { |
+func (c *Codec) ReadHeader(hdr *rpc.Header) error { |
c.msg = inMsg{} // avoid any potential cross-message contamination. |
var err error |
- if logRequests { |
+ if c.isLogging() { |
var m json.RawMessage |
err = c.conn.Receive(&m) |
if err == nil { |
@@ -111,7 +125,7 @@ |
return nil |
} |
-func (c *codec) ReadBody(body interface{}, isRequest bool) error { |
+func (c *Codec) ReadBody(body interface{}, isRequest bool) error { |
if body == nil { |
return nil |
} |
@@ -129,7 +143,7 @@ |
return json.Unmarshal(rawBody, body) |
} |
-func (c *codec) WriteMessage(hdr *rpc.Header, body interface{}) error { |
+func (c *Codec) WriteMessage(hdr *rpc.Header, body interface{}) error { |
r := &outMsg{ |
RequestId: hdr.RequestId, |
@@ -145,7 +159,7 @@ |
} else { |
r.Response = body |
} |
- if logRequests { |
+ if c.isLogging() { |
data, err := json.Marshal(r) |
if err != nil { |
log.Debugf("rpc/jsoncodec: -> marshal error: %v", err) |