From 944f82dc45cad57dd6d7f182a22c7ba04aab9e43 Mon Sep 17 00:00:00 2001 From: Gil Casadevall Date: Thu, 2 Jun 2016 17:05:10 +0200 Subject: [PATCH] Added first version of kubernetes chat plugin --- execute.go | 38 ++++++++++++++++++++++++++++++++++++++ kubebot.go | 35 +++++++++++++++++++++++++++++++++++ main.go | 10 ++++++++++ 3 files changed, 83 insertions(+) create mode 100644 execute.go create mode 100644 kubebot.go create mode 100644 main.go diff --git a/execute.go b/execute.go new file mode 100644 index 0000000..6396e52 --- /dev/null +++ b/execute.go @@ -0,0 +1,38 @@ +package main + +import ( + "fmt" + "io/ioutil" + "os" + "os/exec" +) + +func execute(name string, arg ...string) string { + rescueStdout := os.Stdout + r, w, _ := os.Pipe() + os.Stdout = w + + cmd := exec.Command(name, arg...) + + stdin, err := cmd.StdinPipe() + + if err != nil { + fmt.Println(err) + } + + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + + if err = cmd.Start(); err != nil { + fmt.Println("An error occured: ", err) + } + + stdin.Close() + cmd.Wait() + + w.Close() + out, _ := ioutil.ReadAll(r) + os.Stdout = rescueStdout + + return string(out) +} diff --git a/kubebot.go b/kubebot.go new file mode 100644 index 0000000..79380c7 --- /dev/null +++ b/kubebot.go @@ -0,0 +1,35 @@ +package main + +import ( + "fmt" + "github.com/go-chat-bot/bot" + "regexp" + "strings" +) + +const ( + pattern = "(?i)\\b(k|kubectl)\\b" +) + +var ( + re = regexp.MustCompile(pattern) +) + +func kubernetes(command *bot.PassiveCmd) (string, error) { + if !re.MatchString(command.Raw) { + return "", nil + } + + kubecmd := re.ReplaceAllString(command.Raw, "") + kubecmd = strings.Trim(kubecmd, " ") + params := strings.Split(kubecmd, " ") + output := execute("kubectl", params...) + + return fmt.Sprintf("```\n%s\n```", output), nil +} + +func init() { + bot.RegisterPassiveCommand( + "kubernetes", + kubernetes) +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..5af30e1 --- /dev/null +++ b/main.go @@ -0,0 +1,10 @@ +package main + +import ( + "github.com/go-chat-bot/bot/slack" + "os" +) + +func main() { + slack.Run(os.Getenv("KUBEBOT_SLACK_TOKEN")) +}