Created
May 12, 2015 21:52
-
-
Save iffy/c0f404a889fd198fb807 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"os" | |
"os/exec" | |
"fmt" | |
"flag" | |
"log" | |
"net" | |
"net/rpc" | |
"net/http" | |
) | |
func main() { | |
if len(os.Args) < 2 { | |
panic("Call this as either `master` or `minion`") | |
} | |
switch os.Args[1] { | |
case "minion": | |
StartMinion(os.Args[2:]) | |
case "run": | |
RunCommand(os.Args[2:]) | |
} | |
} | |
type ExecArgs struct { | |
Args []string | |
} | |
type Reply struct { | |
Stdout string | |
} | |
type Exec int | |
func (t *Exec) Run(args *ExecArgs, reply *Reply) error { | |
fmt.Println("Run called", args.Args) | |
command := exec.Command(args.Args[0], args.Args[1:]...) | |
output, err := command.Output() | |
if err != nil { | |
fmt.Println(err) | |
reply.Stdout = ""; | |
} else { | |
fmt.Println("output") | |
fmt.Println(string(output)) | |
reply.Stdout = string(output) | |
} | |
return nil | |
} | |
func StartMinion(args []string) { | |
flags := flag.NewFlagSet("minion", flag.ExitOnError) | |
var host = flags.String("host", "0.0.0.0", "Interface to listen on") | |
var port = flags.Int("port", 7799, "Port to listen on") | |
if err := flags.Parse(args); err == nil { | |
exec_rpc := new(Exec) | |
rpc.Register(exec_rpc) | |
rpc.HandleHTTP() | |
endpoint := fmt.Sprint(*host, ":", *port) | |
fmt.Println("Minion listening on", endpoint) | |
l, e := net.Listen("tcp", endpoint) | |
if e != nil { | |
log.Fatal("listen error:", e) | |
} | |
http.Serve(l, nil) | |
} | |
} | |
func RunCommand(args []string) { | |
flags := flag.NewFlagSet("run", flag.ExitOnError) | |
var host = flags.String("host", "127.0.0.1", "Minion host") | |
var port = flags.Int("port", 7799, "Minion port") | |
if err := flags.Parse(args); err == nil { | |
fmt.Println("executing?") | |
endpoint := fmt.Sprint(*host, ":", *port) | |
fmt.Println("host", endpoint) | |
client, err := rpc.DialHTTP("tcp", endpoint) | |
if err != nil { | |
panic(err) | |
} | |
var args = ExecArgs{ | |
Args: flags.Args(), | |
} | |
var reply Reply | |
err = client.Call("Exec.Run", args, &reply) | |
if err != nil { | |
log.Fatal("Error:", err) | |
} | |
fmt.Println("Result:", reply) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment