tile38/pkg/controller/hooks.go

644 lines
14 KiB
Go
Raw Normal View History

2016-03-19 17:16:19 +03:00
package controller
import (
"bytes"
"errors"
"sort"
2018-08-14 03:36:02 +03:00
"strconv"
2016-03-19 17:16:19 +03:00
"strings"
2016-09-11 17:49:48 +03:00
"sync"
2016-03-19 17:16:19 +03:00
"time"
2016-09-11 17:49:48 +03:00
"github.com/tidwall/buntdb"
2016-03-29 00:16:21 +03:00
"github.com/tidwall/resp"
"github.com/tidwall/tile38/pkg/endpoint"
"github.com/tidwall/tile38/pkg/glob"
"github.com/tidwall/tile38/pkg/log"
"github.com/tidwall/tile38/pkg/server"
2016-03-19 17:16:19 +03:00
)
2018-04-18 01:40:11 +03:00
var hookLogSetDefaults = &buntdb.SetOptions{
Expires: true, // automatically delete after 30 seconds
TTL: time.Second * 30,
2016-03-19 17:16:19 +03:00
}
type hooksByName []*Hook
func (a hooksByName) Len() int {
return len(a)
}
func (a hooksByName) Less(i, j int) bool {
return a[i].Name < a[j].Name
}
func (a hooksByName) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
2018-08-14 03:05:30 +03:00
func (c *Controller) cmdSetHook(msg *server.Message, chanCmd bool) (
res resp.Value, d commandDetailsT, err error,
) {
2016-03-29 22:29:15 +03:00
start := time.Now()
vs := msg.Values[1:]
2016-09-11 17:49:48 +03:00
var name, urls, cmd string
2016-03-29 22:29:15 +03:00
var ok bool
if vs, name, ok = tokenval(vs); !ok || name == "" {
2017-10-05 18:20:40 +03:00
return server.NOMessage, d, errInvalidNumberOfArguments
2016-03-19 17:16:19 +03:00
}
2016-09-11 17:49:48 +03:00
var endpoints []string
2018-08-14 03:05:30 +03:00
if chanCmd {
endpoints = []string{"local://" + name}
} else {
if vs, urls, ok = tokenval(vs); !ok || urls == "" {
return server.NOMessage, d, errInvalidNumberOfArguments
}
for _, url := range strings.Split(urls, ",") {
url = strings.TrimSpace(url)
err := c.epc.Validate(url)
if err != nil {
log.Errorf("sethook: %v", err)
return resp.SimpleStringValue(""), d, errInvalidArgument(url)
}
endpoints = append(endpoints, url)
2016-03-20 18:24:20 +03:00
}
2016-03-19 17:16:19 +03:00
}
var commandvs []resp.Value
var cmdlc string
2016-03-19 17:16:19 +03:00
var types []string
2018-08-14 03:36:02 +03:00
var expires float64
var expiresSet bool
metaMap := make(map[string]string)
for {
commandvs = vs
if vs, cmd, ok = tokenval(vs); !ok || cmd == "" {
2017-10-05 18:20:40 +03:00
return server.NOMessage, d, errInvalidNumberOfArguments
}
cmdlc = strings.ToLower(cmd)
switch cmdlc {
default:
2017-10-05 18:20:40 +03:00
return server.NOMessage, d, errInvalidArgument(cmd)
case "meta":
var metakey string
var metaval string
if vs, metakey, ok = tokenval(vs); !ok || metakey == "" {
2017-10-05 18:20:40 +03:00
return server.NOMessage, d, errInvalidNumberOfArguments
}
if vs, metaval, ok = tokenval(vs); !ok || metaval == "" {
2017-10-05 18:20:40 +03:00
return server.NOMessage, d, errInvalidNumberOfArguments
}
metaMap[metakey] = metaval
continue
2018-08-14 03:36:02 +03:00
case "ex":
var s string
if vs, s, ok = tokenval(vs); !ok || s == "" {
return server.NOMessage, d, errInvalidNumberOfArguments
}
v, err := strconv.ParseFloat(s, 64)
if err != nil {
return server.NOMessage, d, errInvalidArgument(s)
}
expires = v
expiresSet = true
continue
case "nearby":
types = nearbyTypes
case "within", "intersects":
types = withinOrIntersectsTypes
}
break
2016-03-19 17:16:19 +03:00
}
2018-08-14 03:05:30 +03:00
s, err := c.cmdSearchArgs(true, cmdlc, vs, types)
defer s.Close()
2016-03-19 17:16:19 +03:00
if err != nil {
2017-10-05 18:20:40 +03:00
return server.NOMessage, d, err
2016-03-19 17:16:19 +03:00
}
if !s.fence {
2017-10-05 18:20:40 +03:00
return server.NOMessage, d, errors.New("missing FENCE argument")
2016-03-19 17:16:19 +03:00
}
s.cmd = cmdlc
2016-03-29 22:29:15 +03:00
cmsg := &server.Message{}
*cmsg = *msg
cmsg.Values = make([]resp.Value, len(commandvs))
for i := 0; i < len(commandvs); i++ {
cmsg.Values[i] = commandvs[i]
}
2016-03-29 22:29:15 +03:00
cmsg.Command = strings.ToLower(cmsg.Values[0].String())
metas := make([]FenceMeta, 0, len(metaMap))
for key, val := range metaMap {
metas = append(metas, FenceMeta{key, val})
}
sort.Sort(hookMetaByName(metas))
2016-03-19 17:16:19 +03:00
hook := &Hook{
2016-03-20 18:24:20 +03:00
Key: s.key,
Name: name,
Endpoints: endpoints,
Fence: &s,
2016-03-29 22:29:15 +03:00
Message: cmsg,
2016-09-11 17:49:48 +03:00
epm: c.epc,
Metas: metas,
2018-08-14 03:05:30 +03:00
channel: chanCmd,
cond: sync.NewCond(&sync.Mutex{}),
}
2018-08-14 03:36:02 +03:00
if expiresSet {
hook.expires =
time.Now().Add(time.Duration(expires * float64(time.Second)))
}
2018-08-14 03:05:30 +03:00
if !chanCmd {
hook.db = c.qdb
2016-03-19 17:16:19 +03:00
}
var wr bytes.Buffer
hook.ScanWriter, err = c.newScanWriter(
&wr, cmsg, s.key, s.output, s.precision, s.glob, false,
s.cursor, s.limit, s.wheres, s.whereins, s.whereevals, s.nofields)
2016-03-19 17:16:19 +03:00
if err != nil {
2018-08-14 03:36:02 +03:00
2017-10-05 18:20:40 +03:00
return server.NOMessage, d, err
2016-03-19 17:16:19 +03:00
}
if h, ok := c.hooks[name]; ok {
2018-08-14 03:05:30 +03:00
if h.channel != chanCmd {
return server.NOMessage, d,
errors.New("hooks and channels cannot share the same name")
}
if h.Equals(hook) {
// it was a match so we do nothing. But let's signal just
// for good measure.
h.Signal()
2018-08-14 03:36:02 +03:00
if !hook.expires.IsZero() {
c.hookex.Push(hook)
}
switch msg.OutputType {
case server.JSON:
return server.OKMessage(msg, start), d, nil
case server.RESP:
2017-10-05 18:20:40 +03:00
return resp.IntegerValue(0), d, nil
2016-03-29 22:29:15 +03:00
}
}
2016-09-11 17:49:48 +03:00
h.Close()
2016-04-01 22:46:39 +03:00
// delete the previous hook
2016-03-19 17:16:19 +03:00
if hm, ok := c.hookcols[h.Key]; ok {
delete(hm, h.Name)
}
delete(c.hooks, h.Name)
}
2018-08-14 03:36:02 +03:00
2016-03-29 22:29:15 +03:00
d.updated = true
2016-04-02 17:20:30 +03:00
d.timestamp = time.Now()
2016-03-19 17:16:19 +03:00
c.hooks[name] = hook
hm, ok := c.hookcols[hook.Key]
if !ok {
hm = make(map[string]*Hook)
c.hookcols[hook.Key] = hm
}
hm[name] = hook
2016-09-11 17:49:48 +03:00
hook.Open()
2018-08-14 03:36:02 +03:00
if !hook.expires.IsZero() {
c.hookex.Push(hook)
}
2016-03-29 22:29:15 +03:00
switch msg.OutputType {
case server.JSON:
return server.OKMessage(msg, start), d, nil
case server.RESP:
2017-10-05 18:20:40 +03:00
return resp.IntegerValue(1), d, nil
2016-03-29 22:29:15 +03:00
}
2017-10-05 18:20:40 +03:00
return server.NOMessage, d, nil
2016-03-19 17:16:19 +03:00
}
2018-08-14 03:05:30 +03:00
func (c *Controller) cmdDelHook(msg *server.Message, chanCmd bool) (
res resp.Value, d commandDetailsT, err error,
) {
2016-03-29 22:29:15 +03:00
start := time.Now()
vs := msg.Values[1:]
2016-03-19 17:16:19 +03:00
var name string
2016-03-29 22:29:15 +03:00
var ok bool
if vs, name, ok = tokenval(vs); !ok || name == "" {
2017-10-05 18:20:40 +03:00
return server.NOMessage, d, errInvalidNumberOfArguments
2016-03-19 17:16:19 +03:00
}
2016-03-29 22:29:15 +03:00
if len(vs) != 0 {
2017-10-05 18:20:40 +03:00
return server.NOMessage, d, errInvalidNumberOfArguments
2016-03-19 17:16:19 +03:00
}
2018-08-14 03:05:30 +03:00
if h, ok := c.hooks[name]; ok && h.channel == chanCmd {
2016-09-11 17:49:48 +03:00
h.Close()
2016-03-19 17:16:19 +03:00
if hm, ok := c.hookcols[h.Key]; ok {
delete(hm, h.Name)
}
delete(c.hooks, h.Name)
2016-03-29 22:29:15 +03:00
d.updated = true
}
2016-04-02 17:20:30 +03:00
d.timestamp = time.Now()
2016-03-29 22:29:15 +03:00
switch msg.OutputType {
case server.JSON:
return server.OKMessage(msg, start), d, nil
case server.RESP:
if d.updated {
2017-10-05 18:20:40 +03:00
return resp.IntegerValue(1), d, nil
2016-03-29 22:29:15 +03:00
}
2017-10-05 18:20:40 +03:00
return resp.IntegerValue(0), d, nil
2016-03-19 17:16:19 +03:00
}
return
}
2018-08-14 03:05:30 +03:00
func (c *Controller) cmdPDelHook(msg *server.Message, channel bool) (
res resp.Value, d commandDetailsT, err error,
) {
2016-09-12 05:20:53 +03:00
start := time.Now()
vs := msg.Values[1:]
var pattern string
var ok bool
if vs, pattern, ok = tokenval(vs); !ok || pattern == "" {
2017-10-05 18:20:40 +03:00
return server.NOMessage, d, errInvalidNumberOfArguments
2016-09-12 05:20:53 +03:00
}
if len(vs) != 0 {
2017-10-05 18:20:40 +03:00
return server.NOMessage, d, errInvalidNumberOfArguments
2016-09-12 05:20:53 +03:00
}
count := 0
2018-08-14 03:05:30 +03:00
for name, h := range c.hooks {
if h.channel != channel {
continue
}
2016-09-12 05:20:53 +03:00
match, _ := glob.Match(pattern, name)
2018-08-14 03:05:30 +03:00
if !match {
continue
2016-09-12 05:20:53 +03:00
}
2018-08-14 03:05:30 +03:00
h.Close()
if hm, ok := c.hookcols[h.Key]; ok {
delete(hm, h.Name)
}
delete(c.hooks, h.Name)
d.updated = true
count++
2016-09-12 05:20:53 +03:00
}
d.timestamp = time.Now()
switch msg.OutputType {
case server.JSON:
return server.OKMessage(msg, start), d, nil
case server.RESP:
2017-10-05 18:20:40 +03:00
return resp.IntegerValue(count), d, nil
2016-09-12 05:20:53 +03:00
}
return
}
2018-08-14 06:27:22 +03:00
// possiblyExpireHook will evaluate a hook by it's name for expiration and
// purge it from the database if needed. This operation is called from an
// independent goroutine
func (c *Controller) possiblyExpireHook(name string) {
2018-08-14 03:36:02 +03:00
c.mu.Lock()
2018-08-14 06:27:22 +03:00
if h, ok := c.hooks[name]; ok {
2018-08-14 03:36:02 +03:00
if !h.expires.IsZero() && time.Now().After(h.expires) {
// purge from database
msg := &server.Message{}
if h.channel {
msg.Values = resp.MultiBulkValue("delchan", h.Name).Array()
msg.Command = "delchan"
} else {
msg.Values = resp.MultiBulkValue("delhook", h.Name).Array()
msg.Command = "delhook"
}
_, d, err := c.cmdDelHook(msg, h.channel)
if err != nil {
c.mu.Unlock()
panic(err)
}
if err := c.writeAOF(resp.ArrayValue(msg.Values), &d); err != nil {
c.mu.Unlock()
panic(err)
}
log.Debugf("purged hook %v", h.Name)
}
}
c.mu.Unlock()
}
2018-08-14 03:05:30 +03:00
func (c *Controller) cmdHooks(msg *server.Message, channel bool) (
res resp.Value, err error,
) {
2016-03-19 17:16:19 +03:00
start := time.Now()
2016-03-29 22:29:15 +03:00
vs := msg.Values[1:]
2016-03-19 17:16:19 +03:00
var pattern string
2016-03-29 22:29:15 +03:00
var ok bool
2017-10-05 18:20:40 +03:00
2016-03-29 22:29:15 +03:00
if vs, pattern, ok = tokenval(vs); !ok || pattern == "" {
2017-10-05 18:20:40 +03:00
return server.NOMessage, errInvalidNumberOfArguments
2016-03-19 17:16:19 +03:00
}
2016-03-29 22:29:15 +03:00
if len(vs) != 0 {
2017-10-05 18:20:40 +03:00
return server.NOMessage, errInvalidNumberOfArguments
2016-03-19 17:16:19 +03:00
}
var hooks []*Hook
for name, hook := range c.hooks {
2018-08-14 03:05:30 +03:00
if hook.channel != channel {
continue
}
2016-07-12 22:18:16 +03:00
match, _ := glob.Match(pattern, name)
2016-03-29 22:29:15 +03:00
if match {
2016-03-19 17:16:19 +03:00
hooks = append(hooks, hook)
}
}
sort.Sort(hooksByName(hooks))
2016-03-29 22:29:15 +03:00
switch msg.OutputType {
case server.JSON:
buf := &bytes.Buffer{}
2018-08-14 03:05:30 +03:00
buf.WriteString(`{"ok":true,`)
if channel {
buf.WriteString(`"chans":[`)
} else {
buf.WriteString(`"hooks":[`)
}
2016-03-29 22:29:15 +03:00
for i, hook := range hooks {
2016-03-20 18:24:20 +03:00
if i > 0 {
buf.WriteByte(',')
}
2016-03-29 22:29:15 +03:00
buf.WriteString(`{`)
buf.WriteString(`"name":` + jsonString(hook.Name))
buf.WriteString(`,"key":` + jsonString(hook.Key))
2018-08-14 03:05:30 +03:00
if !channel {
buf.WriteString(`,"endpoints":[`)
for i, endpoint := range hook.Endpoints {
if i > 0 {
buf.WriteByte(',')
}
buf.WriteString(jsonString(endpoint))
2016-03-29 22:29:15 +03:00
}
}
buf.WriteString(`],"command":[`)
for i, v := range hook.Message.Values {
if i > 0 {
buf.WriteString(`,`)
}
buf.WriteString(jsonString(v.String()))
}
buf.WriteString(`],"meta":{`)
for i, meta := range hook.Metas {
if i > 0 {
buf.WriteString(`,`)
}
buf.WriteString(jsonString(meta.Name))
buf.WriteString(`:`)
buf.WriteString(jsonString(meta.Value))
}
buf.WriteString(`}}`)
2016-03-29 22:29:15 +03:00
}
2018-08-14 03:05:30 +03:00
buf.WriteString(`],"elapsed":"` +
time.Now().Sub(start).String() + "\"}")
2017-10-05 18:20:40 +03:00
return resp.StringValue(buf.String()), nil
2016-03-29 22:29:15 +03:00
case server.RESP:
var vals []resp.Value
for _, hook := range hooks {
var hvals []resp.Value
hvals = append(hvals, resp.StringValue(hook.Name))
hvals = append(hvals, resp.StringValue(hook.Key))
var evals []resp.Value
for _, endpoint := range hook.Endpoints {
2016-09-11 17:49:48 +03:00
evals = append(evals, resp.StringValue(endpoint))
2016-03-29 22:29:15 +03:00
}
hvals = append(hvals, resp.ArrayValue(evals))
hvals = append(hvals, resp.ArrayValue(hook.Message.Values))
var metas []resp.Value
for _, meta := range hook.Metas {
metas = append(metas, resp.StringValue(meta.Name))
metas = append(metas, resp.StringValue(meta.Value))
}
hvals = append(hvals, resp.ArrayValue(metas))
2016-03-29 22:29:15 +03:00
vals = append(vals, resp.ArrayValue(hvals))
2016-03-19 17:16:19 +03:00
}
2017-10-05 18:20:40 +03:00
return resp.ArrayValue(vals), nil
2016-03-19 17:16:19 +03:00
}
2017-10-05 18:20:40 +03:00
return resp.SimpleStringValue(""), nil
2016-03-19 17:16:19 +03:00
}
2016-09-11 17:49:48 +03:00
// Hook represents a hook.
type Hook struct {
cond *sync.Cond
Key string
Name string
Endpoints []string
Message *server.Message
Fence *liveFenceSwitches
ScanWriter *scanWriter
Metas []FenceMeta
2016-09-11 17:49:48 +03:00
db *buntdb.DB
2018-08-14 03:05:30 +03:00
channel bool
2016-09-11 17:49:48 +03:00
closed bool
opened bool
query string
2018-04-19 19:25:39 +03:00
epm *endpoint.Manager
2018-08-14 03:05:30 +03:00
expires time.Time
2016-09-11 17:49:48 +03:00
}
2018-08-14 03:36:02 +03:00
// Expires returns when the hook expires. Required by the expire.Item interface.
func (h *Hook) Expires() time.Time {
return h.expires
}
2018-08-14 03:05:30 +03:00
// Equals returns true if two hooks are equal
func (h *Hook) Equals(hook *Hook) bool {
if h.Key != hook.Key ||
h.Name != hook.Name ||
len(h.Endpoints) != len(hook.Endpoints) ||
len(h.Metas) != len(hook.Metas) {
return false
}
2018-08-14 03:36:02 +03:00
if !h.expires.Equal(hook.expires) {
return false
}
for i, endpoint := range h.Endpoints {
if endpoint != hook.Endpoints[i] {
return false
}
}
for i, meta := range h.Metas {
if meta.Name != hook.Metas[i].Name ||
meta.Value != hook.Metas[i].Value {
return false
}
}
2018-08-14 03:36:02 +03:00
return resp.ArrayValue(h.Message.Values).Equals(
resp.ArrayValue(hook.Message.Values))
}
2018-08-14 03:05:30 +03:00
// FenceMeta is a meta key/value pair for fences
type FenceMeta struct {
Name, Value string
}
type hookMetaByName []FenceMeta
func (arr hookMetaByName) Len() int {
return len(arr)
}
func (arr hookMetaByName) Less(a, b int) bool {
return arr[a].Name < arr[b].Name
}
func (arr hookMetaByName) Swap(a, b int) {
arr[a], arr[b] = arr[b], arr[a]
}
2016-09-11 17:49:48 +03:00
// Open is called when a hook is first created. It calls the manager
// function in a goroutine
func (h *Hook) Open() {
2018-08-14 03:05:30 +03:00
if h.channel {
// nothing to open for channels
return
}
h.cond.L.Lock()
defer h.cond.L.Unlock()
2016-09-11 17:49:48 +03:00
if h.opened {
return
}
h.opened = true
2018-08-14 03:05:30 +03:00
h.query = `{"hook":` + jsonString(h.Name) + `}`
2016-09-11 17:49:48 +03:00
go h.manager()
}
// Close closed the hook and stop the manager function
func (h *Hook) Close() {
2018-08-14 03:05:30 +03:00
if h.channel {
// nothing to close for channels
return
}
h.cond.L.Lock()
defer h.cond.L.Unlock()
2016-09-11 17:49:48 +03:00
if h.closed {
return
}
h.closed = true
h.cond.Broadcast()
}
// Signal can be called at any point to wake up the hook and
// notify the manager that there may be something new in the queue.
func (h *Hook) Signal() {
2018-08-14 03:05:30 +03:00
if h.channel {
// nothing to signal for channels
return
}
h.cond.L.Lock()
2016-09-11 17:49:48 +03:00
h.cond.Broadcast()
2018-08-14 03:05:30 +03:00
h.cond.L.Unlock()
2016-09-11 17:49:48 +03:00
}
// the manager is a forever loop that calls proc whenever there's a signal.
// it ends when the "closed" flag is set.
func (h *Hook) manager() {
for {
2018-08-14 03:05:30 +03:00
h.cond.L.Lock()
2016-09-11 17:49:48 +03:00
for {
if h.closed {
2018-08-14 03:05:30 +03:00
h.cond.L.Unlock()
2016-09-11 17:49:48 +03:00
return
}
if h.proc() {
break
}
2018-08-14 03:05:30 +03:00
h.cond.L.Unlock()
// proc failed. wait half a second and try again
time.Sleep(time.Second / 2)
h.cond.L.Lock()
2016-09-11 17:49:48 +03:00
}
h.cond.Wait()
2018-08-14 03:05:30 +03:00
h.cond.L.Unlock()
2016-09-11 17:49:48 +03:00
}
}
2016-09-12 05:01:24 +03:00
// proc processes queued hook logs.
// returning true will indicate that all log entries have been
// successfully handled.
2016-09-11 17:49:48 +03:00
func (h *Hook) proc() (ok bool) {
var keys, vals []string
var ttls []time.Duration
2018-04-18 01:40:11 +03:00
start := time.Now()
2016-09-11 17:49:48 +03:00
err := h.db.Update(func(tx *buntdb.Tx) error {
// get keys and vals
2018-08-14 03:05:30 +03:00
err := tx.AscendGreaterOrEqual("hooks",
h.query, func(key, val string) bool {
if strings.HasPrefix(key, hookLogPrefix) {
keys = append(keys, key)
vals = append(vals, val)
}
return true
},
)
2016-09-11 17:49:48 +03:00
if err != nil {
return err
}
2016-09-12 05:01:24 +03:00
2016-09-11 17:49:48 +03:00
// delete the keys
for _, key := range keys {
2018-04-18 01:40:11 +03:00
ttl, err := tx.TTL(key)
if err != nil {
if err != buntdb.ErrNotFound {
return err
2016-09-11 17:49:48 +03:00
}
}
2018-04-18 01:40:11 +03:00
ttls = append(ttls, ttl)
2016-09-11 17:49:48 +03:00
_, err = tx.Delete(key)
if err != nil {
if err != buntdb.ErrNotFound {
return err
}
}
}
return nil
})
if err != nil {
log.Error(err)
return false
}
// send each val. on failure reinsert that one and all of the following
for i, key := range keys {
val := vals[i]
idx := stringToUint64(key[len(hookLogPrefix):])
var sent bool
for _, endpoint := range h.Endpoints {
err := h.epm.Send(endpoint, val)
if err != nil {
2018-08-14 03:05:30 +03:00
log.Debugf("Endpoint connect/send error: %v: %v: %v",
idx, endpoint, err)
2016-09-11 17:49:48 +03:00
continue
}
2017-08-03 13:05:24 +03:00
log.Debugf("Endpoint send ok: %v: %v: %v", idx, endpoint, err)
2016-09-11 17:49:48 +03:00
sent = true
break
}
if !sent {
2018-08-14 03:05:30 +03:00
// failed to send. try to reinsert the remaining.
// if this fails we lose log entries.
2016-09-11 17:49:48 +03:00
keys = keys[i:]
vals = vals[i:]
2018-04-18 01:40:11 +03:00
ttls = ttls[i:]
2016-09-11 17:49:48 +03:00
h.db.Update(func(tx *buntdb.Tx) error {
for i, key := range keys {
val := vals[i]
2018-04-18 01:40:11 +03:00
ttl := ttls[i] - time.Since(start)
if ttl > 0 {
opts := &buntdb.SetOptions{
2016-09-11 17:49:48 +03:00
Expires: true,
2018-04-18 01:40:11 +03:00
TTL: ttl,
}
_, _, err := tx.Set(key, val, opts)
if err != nil {
return err
2016-09-11 17:49:48 +03:00
}
}
}
return nil
})
return false
}
}
return true
}