agent: Refactor msgpack serialization into util

This commit is contained in:
Armon Dadgar 2014-08-29 11:24:41 -07:00
parent 89f258ca2e
commit 6a6885ec18
2 changed files with 17 additions and 16 deletions

View File

@ -1,12 +1,10 @@
package agent package agent
import ( import (
"bytes"
"fmt" "fmt"
"regexp" "regexp"
"github.com/hashicorp/consul/consul/structs" "github.com/hashicorp/consul/consul/structs"
"github.com/ugorji/go/codec"
) )
const ( const (
@ -79,7 +77,7 @@ func (a *Agent) UserEvent(dc string, params *UserEvent) error {
// Format message // Format message
params.ID = generateUUID() params.ID = generateUUID()
params.Version = userEventMaxVersion params.Version = userEventMaxVersion
payload, err := encodeUserEvent(&params) payload, err := encodeMsgPack(&params)
if err != nil { if err != nil {
return fmt.Errorf("UserEvent encoding failed: %v", err) return fmt.Errorf("UserEvent encoding failed: %v", err)
} }
@ -114,7 +112,7 @@ func (a *Agent) handleEvents() {
case e := <-a.eventCh: case e := <-a.eventCh:
// Decode the event // Decode the event
msg := new(UserEvent) msg := new(UserEvent)
if err := decodeUserEvent(e.Payload, msg); err != nil { if err := decodeMsgPack(e.Payload, msg); err != nil {
a.logger.Printf("[ERR] agent: Failed to decode event: %v", err) a.logger.Printf("[ERR] agent: Failed to decode event: %v", err)
continue continue
} }
@ -253,15 +251,3 @@ func (a *Agent) LastUserEvent() *UserEvent {
idx := (((a.eventIndex - 1) % n) + n) % n idx := (((a.eventIndex - 1) % n) + n) % n
return a.eventBuf[idx] return a.eventBuf[idx]
} }
// Decode is used to decode a MsgPack encoded object
func decodeUserEvent(buf []byte, out interface{}) error {
return codec.NewDecoder(bytes.NewReader(buf), msgpackHandle).Decode(out)
}
// encodeUserEvent is used to encode user event
func encodeUserEvent(msg interface{}) ([]byte, error) {
var buf bytes.Buffer
err := codec.NewEncoder(&buf, msgpackHandle).Encode(msg)
return buf.Bytes(), err
}

View File

@ -1,6 +1,7 @@
package agent package agent
import ( import (
"bytes"
crand "crypto/rand" crand "crypto/rand"
"fmt" "fmt"
"math" "math"
@ -9,6 +10,8 @@ import (
"os/exec" "os/exec"
"runtime" "runtime"
"time" "time"
"github.com/ugorji/go/codec"
) )
const ( const (
@ -76,3 +79,15 @@ func generateUUID() string {
buf[8:10], buf[8:10],
buf[10:16]) buf[10:16])
} }
// decodeMsgPack is used to decode a MsgPack encoded object
func decodeMsgPack(buf []byte, out interface{}) error {
return codec.NewDecoder(bytes.NewReader(buf), msgpackHandle).Decode(out)
}
// encodeMsgPack is used to encode an object with msgpack
func encodeMsgPack(msg interface{}) ([]byte, error) {
var buf bytes.Buffer
err := codec.NewEncoder(&buf, msgpackHandle).Encode(msg)
return buf.Bytes(), err
}