restart fix + slack commands
This commit is contained in:
1 parent
e90c9f324b
commit
25fcf85855
22 files changed
+1077
-119
No files matched your search
@@ -3,6 +3,7 @@ load("@rules_go//go:def.bzl", "go_library", "go_test")
|
||||
go_library(
|
||||
name = "bot",
|
||||
srcs = [
|
||||
"agent.go",
|
||||
"assistant.go",
|
||||
"bot.go",
|
||||
"files.go",
|
||||
@@ -10,6 +11,7 @@ go_library(
|
||||
"listen.go",
|
||||
"manage.go",
|
||||
"stream.go",
|
||||
"update.go",
|
||||
"version.go",
|
||||
],
|
||||
importpath = "slackerbot/internal/bot",
|
||||
@@ -36,8 +38,10 @@ go_library(
|
||||
go_test(
|
||||
name = "bot_test",
|
||||
srcs = [
|
||||
"agent_test.go",
|
||||
"bot_test.go",
|
||||
"lifecycle_test.go",
|
||||
"update_test.go",
|
||||
"version_test.go",
|
||||
],
|
||||
embed = [":bot"],
|
||||
@@ -50,6 +54,7 @@ go_test(
|
||||
"//slackerbot/internal/state",
|
||||
"//slackerbot/internal/testutil",
|
||||
"//slackerbot/internal/testutil/clustertest",
|
||||
"//slackerbot/internal/tools",
|
||||
"@com_github_slack_go_slack//:slack",
|
||||
"@com_github_slack_go_slack//slackevents",
|
||||
],
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
|
||||
"slackerbot/internal/model"
|
||||
"slackerbot/internal/tools"
|
||||
)
|
||||
|
||||
const maxReplyBytes = 1 << 20
|
||||
|
||||
// agentCommands runs the Slack commands the agent calls as tools during one
|
||||
// turn, as the person whose message started it. Only stop waits for the turn
|
||||
// to end, because stopping the container would cut the reply off.
|
||||
type agentCommands struct {
|
||||
b *Bot
|
||||
u *model.Owner
|
||||
m incoming
|
||||
root string
|
||||
|
||||
wg sync.WaitGroup
|
||||
mu sync.Mutex
|
||||
stopWhen bool
|
||||
}
|
||||
|
||||
func (b *Bot) agentCommands(u *model.Owner, m incoming, root string) *agentCommands {
|
||||
m.threadTS = root
|
||||
return &agentCommands{b: b, u: u, m: m, root: root}
|
||||
}
|
||||
|
||||
// Update must not block: it's called from the ACP read loop.
|
||||
func (a *agentCommands) Update(ctx context.Context, up acpUpdate) {
|
||||
c, args, ok := tools.CommandCall(up)
|
||||
if !ok || c.Missing(args) {
|
||||
return
|
||||
}
|
||||
a.wg.Add(1)
|
||||
go func() {
|
||||
defer a.wg.Done()
|
||||
reply, isErr := a.run(ctx, c, args)
|
||||
a.answer(ctx, c, args, reply, isErr)
|
||||
}()
|
||||
}
|
||||
|
||||
func (a *agentCommands) run(ctx context.Context, c tools.SlackCommand, args string) (string, bool) {
|
||||
text := c.Text(args)
|
||||
log.Printf("agent: %s ran %q for %s in %s/%s", a.u.Machine, text, a.m.user, a.m.channel, a.root)
|
||||
if c.Name == tools.Stop {
|
||||
return a.queueStop(), false
|
||||
}
|
||||
verb, rest := splitCommand(text)
|
||||
var reply string
|
||||
var ok bool
|
||||
if c.Name == tools.Move {
|
||||
reply, ok = a.b.move(ctx, a.m, rest, a.root, true)
|
||||
} else {
|
||||
reply, ok = a.b.runCommand(ctx, a.m, verb, rest, true)
|
||||
}
|
||||
if !ok {
|
||||
return fmt.Sprintf("`%s` isn't something slackerbot understands. Check the tool's description for the args it takes.", text), true
|
||||
}
|
||||
if c.Changes(args) && c.Name != tools.Move {
|
||||
a.b.say(ctx, a.m.channel, a.root, fmt.Sprintf(":robot_face: The agent ran `%s` for %s:\n%s", text, a.b.displayName(ctx, a.m.user), reply))
|
||||
}
|
||||
return reply, false
|
||||
}
|
||||
|
||||
func (a *agentCommands) queueStop() string {
|
||||
if a.b.store.Owner(a.u.ID) == nil {
|
||||
return "There's no container to stop."
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.stopWhen = true
|
||||
a.mu.Unlock()
|
||||
return "The container will shut down as soon as this reply ends. Its files are kept, and the next message starts it again."
|
||||
}
|
||||
|
||||
func (a *agentCommands) answer(ctx context.Context, c tools.SlackCommand, args, text string, isErr bool) {
|
||||
data, _ := json.Marshal(tools.Reply{Text: text, Error: isErr})
|
||||
p := tools.ReplyPath(a.b.cfg.AgentCwd, c.Name, args)
|
||||
if err := a.b.mgr.WriteFile(ctx, a.u, p, maxReplyBytes, bytes.NewReader(data)); err != nil {
|
||||
log.Printf("agent: answering %s in %s: %v", c.Name, a.u.Machine, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Finish waits for the turn's commands, then does what had to wait for the turn to end.
|
||||
func (a *agentCommands) Finish(ctx context.Context) {
|
||||
a.wg.Wait()
|
||||
a.mu.Lock()
|
||||
stop := a.stopWhen
|
||||
a.mu.Unlock()
|
||||
if !stop {
|
||||
return
|
||||
}
|
||||
reply := a.b.stopFor(ctx, a.u.ID)
|
||||
a.b.say(ctx, a.m.channel, a.root, fmt.Sprintf(":robot_face: The agent ran `stop` for %s:\n%s", a.b.displayName(ctx, a.m.user), reply))
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slack-go/slack"
|
||||
|
||||
"slackerbot/internal/acp"
|
||||
"slackerbot/internal/manager"
|
||||
"slackerbot/internal/model"
|
||||
"slackerbot/internal/testutil"
|
||||
"slackerbot/internal/testutil/clustertest"
|
||||
"slackerbot/internal/tools"
|
||||
)
|
||||
|
||||
func TestAgentRunsCommandsAsTheSender(t *testing.T) {
|
||||
c := clustertest.New(t)
|
||||
c.Cfg.AgentCwd = "/root"
|
||||
c.Cfg.IdleTimeout = 6 * time.Hour
|
||||
c.Cfg.MaxIdleTimeout = 7 * 24 * time.Hour
|
||||
c.AddOwner(t, testutil.HomeData(), true)
|
||||
c.Store.SeedPermissions(model.PermissionsConfig{Managers: []string{"UBOSS"}, Default: map[string][]string{"UBOSS": {"all"}}})
|
||||
log := &slackLog{text: map[string]string{}, under: map[string]string{}}
|
||||
srv := httptest.NewServer(log)
|
||||
defer srv.Close()
|
||||
b := &Bot{cfg: c.Cfg, store: c.Store, mgr: c.Mgr, api: slack.New("xoxb", slack.OptionAPIURL(srv.URL+"/")),
|
||||
acps: map[string]*acp.ACP{}, busy: map[string]int{}}
|
||||
|
||||
call := func(user, tool, args string) (tools.Reply, bool) {
|
||||
u := c.Store.Owner("C1")
|
||||
cmds := b.agentCommands(u, incoming{user: user, channel: "C1", ts: "5.0"}, "5.0")
|
||||
raw, _ := json.Marshal(map[string]string{"args": args})
|
||||
cmds.Update(c.Ctx, acp.Update{Kind: "tool_call", ToolID: "1", ToolName: "slackerbot__" + tool, RawInput: raw})
|
||||
cmds.Finish(c.Ctx)
|
||||
c.Master.Mu.Lock()
|
||||
defer c.Master.Mu.Unlock()
|
||||
for key, data := range c.Master.Files {
|
||||
if strings.HasPrefix(key, "/d/c-c1/.slackerbot/replies/") {
|
||||
delete(c.Master.Files, key)
|
||||
var r tools.Reply
|
||||
_ = json.Unmarshal(data, &r)
|
||||
return r, true
|
||||
}
|
||||
}
|
||||
return tools.Reply{}, false
|
||||
}
|
||||
|
||||
if r, ok := call("UBOSS", "keep", "3h"); !ok || !strings.Contains(r.Text, "3h") {
|
||||
t.Fatalf("keep: %+v %v", r, ok)
|
||||
}
|
||||
if got := c.Store.Owner("C1").IdleTimeout; got != 3*time.Hour {
|
||||
t.Fatalf("keep wasn't saved: %s", got)
|
||||
}
|
||||
if r, _ := call("UANA", "scale", "up"); !strings.Contains(r.Text, ":lock:") {
|
||||
t.Fatalf("the sender's permissions apply: %+v", r)
|
||||
}
|
||||
if r, _ := call("UANA", "status", ""); !strings.Contains(r.Text, "This channel's container") {
|
||||
t.Fatalf("status: %+v", r)
|
||||
}
|
||||
if r, _ := call("UANA", "scale", "the tests"); !r.Error {
|
||||
t.Fatalf("nonsense args should be an error: %+v", r)
|
||||
}
|
||||
if r, _ := call("UANA", "stop", ""); !strings.Contains(r.Text, "as soon as this reply ends") {
|
||||
t.Fatalf("stop: %+v", r)
|
||||
}
|
||||
testutil.WaitFor(t, "container to stop", func() bool { return c.Mgr.State(c.Store.Owner("C1")) != manager.StateRunning })
|
||||
|
||||
log.mu.Lock()
|
||||
defer log.mu.Unlock()
|
||||
var seen []string
|
||||
for _, ts := range log.order {
|
||||
if log.under[ts] == "5.0" && strings.Contains(log.text[ts], "The agent ran") {
|
||||
seen = append(seen, log.text[ts])
|
||||
}
|
||||
}
|
||||
if len(seen) != 3 || !strings.Contains(seen[0], "`keep 3h`") || !strings.Contains(seen[1], ":lock:") || !strings.Contains(seen[2], "`stop`") {
|
||||
t.Fatalf("changes should be posted in the thread, got %q", seen)
|
||||
}
|
||||
}
|
||||
+116
-55
@@ -72,6 +72,8 @@ type Bot struct {
|
||||
busy map[string]int
|
||||
names sync.Map
|
||||
|
||||
updateAsked sync.Map // machine → asked to restart onto a newer system
|
||||
|
||||
channels sync.Map // channel ID → *slack.Channel
|
||||
running sync.Map // "channel/ts" of a prompt's message or reply → its cancel func
|
||||
viewing sync.Map // assistant "channel/thread" → channel the user has open
|
||||
@@ -326,8 +328,10 @@ func (b *Bot) onMessage(ctx context.Context, m incoming) {
|
||||
}
|
||||
st := NewStreamer(b.api, m.channel, root, ph)
|
||||
var sends tools.Calls
|
||||
cmds := b.agentCommands(u, m, root)
|
||||
stop, err := acp.Prompt(pctx, id, text, func(up acpUpdate) {
|
||||
sends.Update(up)
|
||||
cmds.Update(ctx, up)
|
||||
st.Update(up)
|
||||
})
|
||||
if pctx.Err() != nil && ctx.Err() == nil {
|
||||
@@ -335,7 +339,9 @@ func (b *Bot) onMessage(ctx context.Context, m incoming) {
|
||||
}
|
||||
st.Finish(stop, err)
|
||||
b.upload(ctx, u, m.channel, root, sends.Files())
|
||||
cmds.Finish(ctx)
|
||||
_ = b.store.Touch(u.ID)
|
||||
b.offerUpdate(ctx, u, m.channel, root)
|
||||
switch {
|
||||
case stop == "cancelled":
|
||||
outcome = ""
|
||||
@@ -344,28 +350,51 @@ func (b *Bot) onMessage(ctx context.Context, m incoming) {
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bot) command(ctx context.Context, m incoming) bool {
|
||||
ownerID, kind := m.owner()
|
||||
verb, args, _ := strings.Cut(strings.TrimSpace(m.text), " ")
|
||||
func splitCommand(text string) (verb, args string) {
|
||||
verb, args, _ = strings.Cut(strings.TrimSpace(text), " ")
|
||||
verb = strings.ToLower(strings.TrimRight(verb, ".!?"))
|
||||
args = strings.TrimRight(strings.TrimSpace(args), " .!?")
|
||||
return verb, args
|
||||
}
|
||||
|
||||
func (b *Bot) command(ctx context.Context, m incoming) bool {
|
||||
verb, args := splitCommand(m.text)
|
||||
if verb == "move" || verb == "migrate" {
|
||||
return b.moveCommand(ctx, m, cmp.Or(m.threadTS, m.ts))
|
||||
}
|
||||
reply, ok := b.runCommand(ctx, m, verb, args, false)
|
||||
if reply != "" {
|
||||
b.say(ctx, m.channel, m.threadTS, reply)
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// runCommand returns ok=false when the text isn't a command, so it belongs to
|
||||
// the agent. An empty reply means it was posted already, with buttons. The
|
||||
// agent can't press buttons, so it gets plain text instead.
|
||||
func (b *Bot) runCommand(ctx context.Context, m incoming, verb, args string, agent bool) (reply string, ok bool) {
|
||||
ownerID, kind := m.owner()
|
||||
if verb == "grant" || verb == "revoke" || verb == "dm" || verb == "managers" || (verb == "permissions" && args != "") {
|
||||
return b.manageCommand(ctx, m, verb, args)
|
||||
}
|
||||
if need := commands.NeededPermission(verb, args); need != "" && !b.permitted(ctx, m.channel, m.threadTS, m.user, kind, need) {
|
||||
return true
|
||||
if commands.IsListen(verb) {
|
||||
c, err := commands.ParseListen(args)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
return b.listenReply(m, c), true
|
||||
}
|
||||
if need := commands.NeededPermission(verb, args); need != "" {
|
||||
if denied := b.denial(ctx, m.channel, m.user, kind, need); denied != "" {
|
||||
return denied, true
|
||||
}
|
||||
}
|
||||
if verb == "stop" || verb == "scale" || verb == "storage" || verb == "disk" {
|
||||
if b.blocked(ctx, m.channel, m.threadTS, ownerID) {
|
||||
return true
|
||||
if reply, ok := b.blocked(ctx, m.channel, ownerID, agent); ok {
|
||||
return reply, true
|
||||
}
|
||||
}
|
||||
|
||||
reply := ""
|
||||
switch {
|
||||
case verb == "" || verb == "help" && args == "":
|
||||
reply = helpText
|
||||
@@ -375,34 +404,27 @@ func (b *Bot) command(ctx context.Context, m incoming) bool {
|
||||
case verb == "sessions" && args == "":
|
||||
reply = b.sessionList(ctx, ownerID)
|
||||
case verb == "status" && args == "":
|
||||
if agent {
|
||||
return b.statusText(ctx, ownerID, kind), true
|
||||
}
|
||||
b.postStatus(ctx, m.channel, m.threadTS, ownerID, kind)
|
||||
return true
|
||||
return "", true
|
||||
case verb == "stop" && args == "":
|
||||
reply = b.stopFor(ctx, ownerID)
|
||||
case verb == "scale":
|
||||
var ok bool
|
||||
if reply, ok = b.scaleFor(ctx, ownerID, kind, args); !ok {
|
||||
return false
|
||||
}
|
||||
return b.scaleFor(ctx, ownerID, kind, args)
|
||||
case verb == "keep":
|
||||
var ok bool
|
||||
if reply, ok = b.keepFor(ownerID, kind, args); !ok {
|
||||
return false
|
||||
}
|
||||
return b.keepFor(ownerID, kind, args)
|
||||
case verb == "nodes" && args == "":
|
||||
reply = b.nodesList(ctx, ownerID)
|
||||
case verb == "permissions" && args == "":
|
||||
reply = b.permissionsList(ctx, m.channel, kind)
|
||||
case verb == "storage" || verb == "disk":
|
||||
var ok bool
|
||||
if reply, ok = b.storageFor(ctx, ownerID, kind, args); !ok {
|
||||
return false
|
||||
}
|
||||
return b.storageFor(ctx, ownerID, kind, args)
|
||||
default:
|
||||
return false
|
||||
return "", false
|
||||
}
|
||||
b.say(ctx, m.channel, m.threadTS, reply)
|
||||
return true
|
||||
return reply, true
|
||||
}
|
||||
|
||||
func (b *Bot) onAction(ctx context.Context, cb slack.InteractionCallback) {
|
||||
@@ -446,6 +468,11 @@ func (b *Bot) onAction(ctx context.Context, cb slack.InteractionCallback) {
|
||||
b.waiting[u.Node][cb.Channel.ID] = true
|
||||
b.waitMu.Unlock()
|
||||
b.say(ctx, cb.Channel.ID, thread, fmt.Sprintf("OK, waiting for %s. I'll post here when it's back up.", u.Node))
|
||||
case "restart":
|
||||
b.restartFor(ctx, cb, ownerID, kind)
|
||||
case "later":
|
||||
b.settlePrompt(ctx, cb, "OK, not now. The update applies the next time the container starts, "+
|
||||
"for example after `stop` and a new message.")
|
||||
case "stop", "scale":
|
||||
if b.mgr.State(u) == manager.StateOffline {
|
||||
b.deadSlave(ctx, cb.Channel.ID, "", ownerID, u.Node)
|
||||
@@ -479,7 +506,7 @@ func (b *Bot) sessionList(ctx context.Context, ownerID string) string {
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func (b *Bot) postStatus(ctx context.Context, channel, thread, ownerID string, kind model.OwnerKind) {
|
||||
func (b *Bot) statusText(ctx context.Context, ownerID string, kind model.OwnerKind) string {
|
||||
u := b.store.Owner(ownerID)
|
||||
state := b.mgr.State(u)
|
||||
size := b.cfg.Container
|
||||
@@ -512,8 +539,17 @@ func (b *Bot) postStatus(ctx context.Context, channel, thread, ownerID string, k
|
||||
for _, name := range b.mgr.OfflineNodes() {
|
||||
fmt.Fprintf(&sb, "\n• %s: offline", name)
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
text := sb.String()
|
||||
func (b *Bot) postStatus(ctx context.Context, channel, thread, ownerID string, kind model.OwnerKind) {
|
||||
u := b.store.Owner(ownerID)
|
||||
state := b.mgr.State(u)
|
||||
size := b.cfg.Container
|
||||
if u != nil {
|
||||
size = u.Size
|
||||
}
|
||||
text := b.statusText(ctx, ownerID, kind)
|
||||
blocks := []slack.Block{slack.NewSectionBlock(slack.NewTextBlockObject(slack.MarkdownType, text, false, false), nil, nil)}
|
||||
|
||||
var buttons []slack.BlockElement
|
||||
@@ -712,26 +748,34 @@ func (b *Bot) moveTarget(args string) (target string, ok bool) {
|
||||
}
|
||||
|
||||
func (b *Bot) permitted(ctx context.Context, channel, thread, user string, kind model.OwnerKind, a model.Action) bool {
|
||||
p := b.store.Permissions()
|
||||
if p.Allowed(kind, channel, user, a) {
|
||||
text := b.denial(ctx, channel, user, kind, a)
|
||||
if text == "" {
|
||||
return true
|
||||
}
|
||||
var text string
|
||||
if kind == model.OwnerUser {
|
||||
text = fmt.Sprintf(":lock: Changing *%s* from DMs is turned off on this server.", a)
|
||||
} else if holders := p.Holders(channel, a); len(holders) == 0 {
|
||||
text = fmt.Sprintf(":lock: Nobody here has *%s* permission. An admin can grant it in the config.", a)
|
||||
} else {
|
||||
names := make([]string, len(holders))
|
||||
for i, h := range holders {
|
||||
names[i] = b.displayName(ctx, h)
|
||||
}
|
||||
text = fmt.Sprintf(":lock: Only super users with *%s* permission can do that here: %s.", a, strings.Join(names, ", "))
|
||||
}
|
||||
b.say(ctx, channel, thread, text)
|
||||
return false
|
||||
}
|
||||
|
||||
// denial explains why the user may not do a, or is empty when they may.
|
||||
func (b *Bot) denial(ctx context.Context, channel, user string, kind model.OwnerKind, a model.Action) string {
|
||||
p := b.store.Permissions()
|
||||
if p.Allowed(kind, channel, user, a) {
|
||||
return ""
|
||||
}
|
||||
if kind == model.OwnerUser {
|
||||
return fmt.Sprintf(":lock: Changing *%s* from DMs is turned off on this server.", a)
|
||||
}
|
||||
holders := p.Holders(channel, a)
|
||||
if len(holders) == 0 {
|
||||
return fmt.Sprintf(":lock: Nobody here has *%s* permission. An admin can grant it in the config.", a)
|
||||
}
|
||||
names := make([]string, len(holders))
|
||||
for i, h := range holders {
|
||||
names[i] = b.displayName(ctx, h)
|
||||
}
|
||||
return fmt.Sprintf(":lock: Only super users with *%s* permission can do that here: %s.", a, strings.Join(names, ", "))
|
||||
}
|
||||
|
||||
func (b *Bot) permissionsList(ctx context.Context, channel string, kind model.OwnerKind) string {
|
||||
p := b.store.Permissions()
|
||||
if kind == model.OwnerUser {
|
||||
@@ -775,37 +819,54 @@ func (b *Bot) permissionsList(ctx context.Context, channel string, kind model.Ow
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func (b *Bot) blocked(ctx context.Context, channel, thread, ownerID string) bool {
|
||||
// blocked explains why the container can't be changed right now. In Slack a
|
||||
// dead node gets its recreate/wait buttons instead, and the reply is empty.
|
||||
func (b *Bot) blocked(ctx context.Context, channel, ownerID string, agent bool) (reply string, ok bool) {
|
||||
if b.mgr.IsMigrating(ownerID) {
|
||||
b.say(ctx, channel, thread, b.explain(manager.ErrMigrating))
|
||||
return true
|
||||
return b.explain(manager.ErrMigrating), true
|
||||
}
|
||||
if u := b.store.Owner(ownerID); b.mgr.State(u) == manager.StateOffline {
|
||||
if agent {
|
||||
return fmt.Sprintf("Node %s is offline right now.", u.Node), true
|
||||
}
|
||||
b.deadSlave(ctx, channel, "", ownerID, u.Node)
|
||||
return true
|
||||
return "", true
|
||||
}
|
||||
return false
|
||||
return "", false
|
||||
}
|
||||
|
||||
func (b *Bot) moveCommand(ctx context.Context, m incoming, replyThread string) bool {
|
||||
verb, args, _ := strings.Cut(strings.TrimSpace(m.text), " ")
|
||||
verb = strings.ToLower(strings.TrimRight(verb, ".!?"))
|
||||
verb, args := splitCommand(m.text)
|
||||
if verb != "move" && verb != "migrate" {
|
||||
return false
|
||||
}
|
||||
target, ok := b.moveTarget(strings.TrimRight(strings.TrimSpace(args), " .!?"))
|
||||
reply, ok := b.move(ctx, m, args, replyThread, false)
|
||||
if reply != "" {
|
||||
b.say(ctx, m.channel, replyThread, reply)
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
func (b *Bot) move(ctx context.Context, m incoming, args, replyThread string, agent bool) (reply string, ok bool) {
|
||||
target, ok := b.moveTarget(args)
|
||||
if !ok {
|
||||
return false
|
||||
return "", false
|
||||
}
|
||||
ownerID, kind := m.owner()
|
||||
if !b.permitted(ctx, m.channel, replyThread, m.user, kind, model.ActMove) {
|
||||
return true
|
||||
if denied := b.denial(ctx, m.channel, m.user, kind, model.ActMove); denied != "" {
|
||||
return denied, true
|
||||
}
|
||||
if b.blocked(ctx, m.channel, replyThread, ownerID) {
|
||||
return true
|
||||
if reply, ok := b.blocked(ctx, m.channel, ownerID, agent); ok {
|
||||
return reply, true
|
||||
}
|
||||
go b.moveFor(ctx, m.channel, ownerID, target, "<@"+m.user+">", replyThread)
|
||||
return true
|
||||
trigger := "<@" + m.user + ">"
|
||||
if !agent {
|
||||
go b.moveFor(ctx, m.channel, ownerID, target, trigger, replyThread)
|
||||
return "", true
|
||||
}
|
||||
go b.moveFor(ctx, m.channel, ownerID, target, "the agent, for "+trigger, replyThread)
|
||||
return "The move has started, and its progress is posted in Slack. The container is stopped briefly near the end, " +
|
||||
"so finish your reply now. The user can carry on in this thread once it's done.", true
|
||||
}
|
||||
|
||||
func (b *Bot) moveFor(ctx context.Context, channel, ownerID, target, trigger, replyThread string) {
|
||||
|
||||
@@ -32,14 +32,11 @@ func actionList(actions []model.Action) string {
|
||||
|
||||
// manageCommand handles permission changes. It returns false if the message
|
||||
// isn't one of these commands, so it goes to the agent.
|
||||
func (b *Bot) manageCommand(ctx context.Context, m incoming, verb, args string) bool {
|
||||
func (b *Bot) manageCommand(ctx context.Context, m incoming, verb, args string) (string, bool) {
|
||||
_, kind := m.owner()
|
||||
p := b.store.Permissions()
|
||||
reply := func(text string) bool {
|
||||
b.say(ctx, m.channel, m.threadTS, text)
|
||||
return true
|
||||
}
|
||||
denied := func(global bool) bool {
|
||||
reply := func(text string) (string, bool) { return text, true }
|
||||
denied := func(global bool) (string, bool) {
|
||||
who := "user managers"
|
||||
if !global {
|
||||
who = "user managers and people with *manage* permission here"
|
||||
@@ -58,7 +55,7 @@ func (b *Bot) manageCommand(ctx context.Context, m incoming, verb, args string)
|
||||
case "grant", "revoke":
|
||||
g, err := commands.ParseGrant(args)
|
||||
if errors.Is(err, commands.ErrNotCommand) {
|
||||
return false
|
||||
return "", false
|
||||
}
|
||||
if err != nil {
|
||||
return reply(":warning: " + err.Error() + ". Try `grant @alice move scale` or `revoke @alice`.")
|
||||
@@ -119,11 +116,11 @@ func (b *Bot) manageCommand(ctx context.Context, m incoming, verb, args string)
|
||||
case "dm":
|
||||
words := strings.Fields(strings.ToLower(args))
|
||||
if len(words) != 2 || !slices.Contains(model.AllActions, model.Action(words[0])) {
|
||||
return false
|
||||
return "", false
|
||||
}
|
||||
on, ok := commands.ParseToggle(words[1])
|
||||
if !ok {
|
||||
return false
|
||||
return "", false
|
||||
}
|
||||
if !p.IsManager(m.user) {
|
||||
return denied(true)
|
||||
@@ -145,7 +142,7 @@ func (b *Bot) manageCommand(ctx context.Context, m incoming, verb, args string)
|
||||
op := strings.ToLower(words[0])
|
||||
g, err := commands.ParseGrant(strings.Join(words[1:], " "))
|
||||
if (op != "add" && op != "remove") || err != nil || len(g.Actions) > 0 {
|
||||
return false
|
||||
return "", false
|
||||
}
|
||||
if !p.IsManager(m.user) {
|
||||
return denied(true)
|
||||
@@ -171,7 +168,7 @@ func (b *Bot) manageCommand(ctx context.Context, m incoming, verb, args string)
|
||||
|
||||
case "permissions":
|
||||
if strings.ToLower(args) != "reset" {
|
||||
return false
|
||||
return "", false
|
||||
}
|
||||
if kind == model.OwnerUser {
|
||||
return reply("DMs don't have a super-user list to reset.")
|
||||
@@ -184,5 +181,5 @@ func (b *Bot) manageCommand(ctx context.Context, m incoming, verb, args string)
|
||||
}
|
||||
return reply("Done. This channel uses the default super-user list again.")
|
||||
}
|
||||
return false
|
||||
return "", false
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/slack-go/slack"
|
||||
|
||||
"slackerbot/internal/manager"
|
||||
"slackerbot/internal/model"
|
||||
)
|
||||
|
||||
const updateText = ":arrows_counterclockwise: A system update is waiting for this container. " +
|
||||
"Restarting applies it. Files in /root and your sessions are kept."
|
||||
|
||||
// offerUpdate asks once per container whether to restart onto the node's
|
||||
// current system. Asking again needs a newer system or a bot restart.
|
||||
func (b *Bot) offerUpdate(ctx context.Context, u *model.Owner, channel, thread string) {
|
||||
if !b.mgr.Outdated(ctx, u) {
|
||||
b.updateAsked.Delete(u.Machine)
|
||||
return
|
||||
}
|
||||
if _, asked := b.updateAsked.LoadOrStore(u.Machine, true); asked {
|
||||
return
|
||||
}
|
||||
restart := slack.NewButtonBlockElement("restart", u.ID, slack.NewTextBlockObject(slack.PlainTextType, "Restart now", false, false))
|
||||
restart.Style = slack.StylePrimary
|
||||
later := slack.NewButtonBlockElement("later", u.ID, slack.NewTextBlockObject(slack.PlainTextType, "Later", false, false))
|
||||
blocks := []slack.Block{
|
||||
slack.NewSectionBlock(slack.NewTextBlockObject(slack.MarkdownType, updateText, false, false), nil, nil),
|
||||
slack.NewActionBlock("update", restart, later),
|
||||
}
|
||||
if _, _, err := b.api.PostMessageContext(ctx, channel, slack.MsgOptionText(updateText, false),
|
||||
slack.MsgOptionBlocks(blocks...), slack.MsgOptionTS(thread)); err != nil {
|
||||
log.Printf("slack post: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// settlePrompt replaces the update prompt, so its buttons can't be pressed twice.
|
||||
func (b *Bot) settlePrompt(ctx context.Context, cb slack.InteractionCallback, text string) {
|
||||
block := slack.NewSectionBlock(slack.NewTextBlockObject(slack.MarkdownType, text, false, false), nil, nil)
|
||||
if _, _, _, err := b.api.UpdateMessageContext(ctx, cb.Channel.ID, cb.Message.Timestamp,
|
||||
slack.MsgOptionText(text, false), slack.MsgOptionBlocks(block)); err != nil {
|
||||
log.Printf("slack update: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bot) restartFor(ctx context.Context, cb slack.InteractionCallback, ownerID string, kind model.OwnerKind) {
|
||||
channel, thread := cb.Channel.ID, cb.Message.ThreadTimestamp
|
||||
u := b.store.Owner(ownerID)
|
||||
switch b.mgr.State(u) {
|
||||
case manager.StateOffline:
|
||||
b.deadSlave(ctx, channel, "", ownerID, u.Node)
|
||||
return
|
||||
case manager.StateRunning:
|
||||
default:
|
||||
b.settlePrompt(ctx, cb, ":white_check_mark: The container isn't running, so it gets the update when it next starts.")
|
||||
return
|
||||
}
|
||||
if b.isBusy(u.Machine) {
|
||||
b.say(ctx, channel, thread, "The agent is still replying in this container. Press *Restart now* again once it's done.")
|
||||
return
|
||||
}
|
||||
b.settlePrompt(ctx, cb, ":arrows_counterclockwise: Restarting the container to apply the update…")
|
||||
b.currentLifecycle(ctx, u).post(ctx, ":octagonal_sign: Shutting down to apply a system update, asked by <@"+cb.User.ID+">.")
|
||||
b.dropClient(u)
|
||||
|
||||
sl := &startLog{b: b, m: incoming{user: cb.User.ID, channel: channel}, root: thread, ownerID: ownerID}
|
||||
u, err := b.mgr.Restart(ctx, ownerID, kind, func(ev manager.StartEvent) { sl.event(ctx, ev) })
|
||||
if err == nil {
|
||||
_, err = b.client(ctx, u)
|
||||
}
|
||||
if err != nil {
|
||||
sl.failed(ctx, b.explain(err))
|
||||
b.say(ctx, channel, thread, ":warning: The restart didn't finish: "+b.explain(err))
|
||||
return
|
||||
}
|
||||
sl.up(ctx)
|
||||
b.say(ctx, channel, thread, ":white_check_mark: Restarted with the update. Carry on in any thread.")
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/slack-go/slack"
|
||||
|
||||
"slackerbot/internal/acp"
|
||||
"slackerbot/internal/model"
|
||||
"slackerbot/internal/testutil"
|
||||
"slackerbot/internal/testutil/clustertest"
|
||||
)
|
||||
|
||||
func updateBot(t *testing.T) (*Bot, *clustertest.Cluster, *slackLog) {
|
||||
c := clustertest.New(t)
|
||||
c.AddOwner(t, testutil.HomeData(), true)
|
||||
log := &slackLog{text: map[string]string{}, under: map[string]string{}}
|
||||
srv := httptest.NewServer(log)
|
||||
t.Cleanup(srv.Close)
|
||||
b := &Bot{cfg: c.Cfg, store: c.Store, mgr: c.Mgr, api: slack.New("xoxb", slack.OptionAPIURL(srv.URL+"/")),
|
||||
acps: map[string]*acp.ACP{}, busy: map[string]int{}}
|
||||
return b, c, log
|
||||
}
|
||||
|
||||
func setOutdated(c *clustertest.Cluster, outdated bool) {
|
||||
c.Master.Mu.Lock()
|
||||
defer c.Master.Mu.Unlock()
|
||||
c.Master.Outdated["c-c1"] = outdated
|
||||
}
|
||||
|
||||
func (s *slackLog) prompts() int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
n := 0
|
||||
for _, text := range s.text {
|
||||
if strings.Contains(text, "A system update is waiting") {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func TestUpdatePromptOncePerSystem(t *testing.T) {
|
||||
b, c, log := updateBot(t)
|
||||
u := c.Store.Owner("C1")
|
||||
|
||||
b.offerUpdate(c.Ctx, u, "C1", "100.0")
|
||||
if log.prompts() != 0 {
|
||||
t.Fatal("no prompt for a container on the current system")
|
||||
}
|
||||
setOutdated(c, true)
|
||||
b.offerUpdate(c.Ctx, u, "C1", "100.0")
|
||||
b.offerUpdate(c.Ctx, u, "C1", "200.0")
|
||||
if log.prompts() != 1 {
|
||||
t.Fatalf("want one prompt for one pending update, got %d", log.prompts())
|
||||
}
|
||||
setOutdated(c, false)
|
||||
b.offerUpdate(c.Ctx, u, "C1", "100.0")
|
||||
setOutdated(c, true)
|
||||
b.offerUpdate(c.Ctx, u, "C1", "100.0")
|
||||
if log.prompts() != 2 {
|
||||
t.Fatalf("a newer update should be offered again, got %d prompts", log.prompts())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestartWaitsForReply(t *testing.T) {
|
||||
b, c, log := updateBot(t)
|
||||
setOutdated(c, true)
|
||||
b.setBusy("c-c1", +1)
|
||||
|
||||
cb := slack.InteractionCallback{Channel: slack.Channel{GroupConversation: slack.GroupConversation{
|
||||
Conversation: slack.Conversation{ID: "C1"}}}}
|
||||
cb.Message.Timestamp, cb.Message.ThreadTimestamp = "5.0", "100.0"
|
||||
b.restartFor(c.Ctx, cb, "C1", model.OwnerChannel)
|
||||
|
||||
c.Master.Mu.Lock()
|
||||
still := c.Master.Outdated["c-c1"]
|
||||
c.Master.Mu.Unlock()
|
||||
if !still {
|
||||
t.Fatal("a busy container must not be restarted")
|
||||
}
|
||||
log.mu.Lock()
|
||||
defer log.mu.Unlock()
|
||||
for _, text := range log.text {
|
||||
if strings.Contains(text, "still replying") {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatal("the user should be told to try again once the reply is done")
|
||||
}
|
||||
Reference in new issue
Block a user