2013-01-24 23:01:32 -05:00
|
|
|
package rcli
|
|
|
|
|
|
|
|
import (
|
2013-03-09 22:44:09 -05:00
|
|
|
"bufio"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2013-01-24 23:01:32 -05:00
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"log"
|
2013-03-09 22:44:09 -05:00
|
|
|
"net"
|
2013-01-24 23:01:32 -05:00
|
|
|
)
|
|
|
|
|
2013-03-22 14:44:12 -04:00
|
|
|
// Note: the globals are here to avoid import cycle
|
|
|
|
// FIXME: Handle debug levels mode?
|
|
|
|
var DEBUG_FLAG bool = false
|
|
|
|
var CLIENT_SOCKET io.Writer = nil
|
|
|
|
|
2013-02-12 11:37:12 -05:00
|
|
|
// Connect to a remote endpoint using protocol `proto` and address `addr`,
|
|
|
|
// issue a single call, and return the result.
|
|
|
|
// `proto` may be "tcp", "unix", etc. See the `net` package for available protocols.
|
|
|
|
func Call(proto, addr string, args ...string) (*net.TCPConn, error) {
|
2013-01-24 23:01:32 -05:00
|
|
|
cmd, err := json.Marshal(args)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2013-02-12 11:37:12 -05:00
|
|
|
conn, err := net.Dial(proto, addr)
|
2013-01-24 23:01:32 -05:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if _, err := fmt.Fprintln(conn, string(cmd)); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2013-01-25 14:27:47 -05:00
|
|
|
return conn.(*net.TCPConn), nil
|
2013-01-24 23:01:32 -05:00
|
|
|
}
|
|
|
|
|
2013-02-12 11:37:12 -05:00
|
|
|
// Listen on `addr`, using protocol `proto`, for incoming rcli calls,
|
|
|
|
// and pass them to `service`.
|
|
|
|
func ListenAndServe(proto, addr string, service Service) error {
|
|
|
|
listener, err := net.Listen(proto, addr)
|
2013-01-24 23:01:32 -05:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2013-02-12 11:37:12 -05:00
|
|
|
log.Printf("Listening for RCLI/%s on %s\n", proto, addr)
|
2013-01-24 23:01:32 -05:00
|
|
|
defer listener.Close()
|
|
|
|
for {
|
|
|
|
if conn, err := listener.Accept(); err != nil {
|
|
|
|
return err
|
|
|
|
} else {
|
|
|
|
go func() {
|
2013-03-22 14:44:12 -04:00
|
|
|
if DEBUG_FLAG {
|
|
|
|
CLIENT_SOCKET = conn
|
|
|
|
}
|
2013-01-24 23:01:32 -05:00
|
|
|
if err := Serve(conn, service); err != nil {
|
|
|
|
log.Printf("Error: " + err.Error() + "\n")
|
2013-03-09 22:44:09 -05:00
|
|
|
fmt.Fprintf(conn, "Error: "+err.Error()+"\n")
|
2013-01-24 23:01:32 -05:00
|
|
|
}
|
|
|
|
conn.Close()
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2013-02-12 11:42:15 -05:00
|
|
|
// Parse an rcli call on a new connection, and pass it to `service` if it
|
|
|
|
// is valid.
|
2013-01-24 23:01:32 -05:00
|
|
|
func Serve(conn io.ReadWriter, service Service) error {
|
|
|
|
r := bufio.NewReader(conn)
|
|
|
|
var args []string
|
|
|
|
if line, err := r.ReadString('\n'); err != nil {
|
|
|
|
return err
|
|
|
|
} else if err := json.Unmarshal([]byte(line), &args); err != nil {
|
|
|
|
return err
|
|
|
|
} else {
|
|
|
|
return call(service, ioutil.NopCloser(r), conn, args...)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|