You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

209 lines
5.3 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package main
  2. // A note on the origin of the name.
  3. // http://en.wikipedia.org/wiki/Barak
  4. // TODO: Nonrepudiable command log
  5. import (
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "os"
  12. "reflect"
  13. "sync"
  14. "github.com/tendermint/tendermint/binary"
  15. . "github.com/tendermint/tendermint/cmd/barak/types"
  16. . "github.com/tendermint/tendermint/common"
  17. pcm "github.com/tendermint/tendermint/process"
  18. "github.com/tendermint/tendermint/rpc"
  19. )
  20. var Routes = map[string]*rpc.RPCFunc{
  21. "run": rpc.NewRPCFunc(Run, []string{"auth_command"}),
  22. // NOTE: also, two special non-JSONRPC routes called "download" and "upload"
  23. }
  24. type Options struct {
  25. Validators []Validator
  26. ListenAddress string
  27. StartNonce uint64
  28. }
  29. // Global instance
  30. var barak = struct {
  31. mtx sync.Mutex
  32. processes map[string]*pcm.Process
  33. validators []Validator
  34. nonce uint64
  35. }{sync.Mutex{}, make(map[string]*pcm.Process), nil, 0}
  36. func main() {
  37. // read options from stdin.
  38. var err error
  39. optionsBytes, err := ioutil.ReadAll(os.Stdin)
  40. if err != nil {
  41. panic(Fmt("Error reading input: %v", err))
  42. }
  43. options := binary.ReadJSON(&Options{}, optionsBytes, &err).(*Options)
  44. if err != nil {
  45. panic(Fmt("Error parsing input: %v", err))
  46. }
  47. barak.nonce = options.StartNonce
  48. barak.validators = options.Validators
  49. // Debug.
  50. fmt.Printf("Options: %v\n", options)
  51. fmt.Printf("Barak: %v\n", barak)
  52. // Start rpc server.
  53. mux := http.NewServeMux()
  54. mux.HandleFunc("/download", ServeFile)
  55. // TODO: mux.HandleFunc("/upload", UploadFile)
  56. rpc.RegisterRPCFuncs(mux, Routes)
  57. rpc.StartHTTPServer(options.ListenAddress, mux)
  58. TrapSignal(func() {
  59. fmt.Println("Barak shutting down")
  60. })
  61. }
  62. //------------------------------------------------------------------------------
  63. // RPC main function
  64. func Run(authCommand AuthCommand) (interface{}, error) {
  65. command, err := parseValidateCommand(authCommand)
  66. if err != nil {
  67. return nil, err
  68. }
  69. log.Info(Fmt("Run() received command %v", reflect.TypeOf(command)))
  70. // Issue command
  71. switch c := command.(type) {
  72. case CommandRunProcess:
  73. return RunProcess(c.Wait, c.Label, c.ExecPath, c.Args, c.Input)
  74. case CommandStopProcess:
  75. return StopProcess(c.Label, c.Kill)
  76. case CommandListProcesses:
  77. return ListProcesses()
  78. default:
  79. return nil, errors.New("Invalid endpoint for command")
  80. }
  81. }
  82. func parseValidateCommandStr(authCommandStr string) (Command, error) {
  83. var err error
  84. authCommand := binary.ReadJSON(AuthCommand{}, []byte(authCommandStr), &err).(AuthCommand)
  85. if err != nil {
  86. fmt.Printf("Failed to parse auth_command")
  87. return nil, errors.New("AuthCommand parse error")
  88. }
  89. return parseValidateCommand(authCommand)
  90. }
  91. func parseValidateCommand(authCommand AuthCommand) (Command, error) {
  92. commandJSONStr := authCommand.CommandJSONStr
  93. signatures := authCommand.Signatures
  94. // Validate commandJSONStr
  95. if !validate([]byte(commandJSONStr), barak.validators, signatures) {
  96. fmt.Printf("Failed validation attempt")
  97. return nil, errors.New("Validation error")
  98. }
  99. // Parse command
  100. var err error
  101. command := binary.ReadJSON(NoncedCommand{}, []byte(commandJSONStr), &err).(NoncedCommand)
  102. if err != nil {
  103. fmt.Printf("Failed to parse command")
  104. return nil, errors.New("Command parse error")
  105. }
  106. // Prevent replays
  107. if barak.nonce+1 != command.Nonce {
  108. return nil, errors.New("Replay error")
  109. } else {
  110. barak.nonce += 1
  111. }
  112. return command.Command, nil
  113. }
  114. //------------------------------------------------------------------------------
  115. // RPC base commands
  116. // WARNING Not validated, do not export to routes.
  117. func RunProcess(wait bool, label string, execPath string, args []string, input string) (*ResponseRunProcess, error) {
  118. barak.mtx.Lock()
  119. // First, see if there already is a process labeled 'label'
  120. existing := barak.processes[label]
  121. if existing != nil {
  122. barak.mtx.Unlock()
  123. return nil, Errorf("Process already exists: %v", label)
  124. }
  125. // Otherwise, create one.
  126. proc := pcm.Create(pcm.ProcessModeDaemon, label, execPath, args, input)
  127. barak.processes[label] = proc
  128. barak.mtx.Unlock()
  129. if wait {
  130. exitErr := pcm.Wait(proc)
  131. return nil, exitErr
  132. } else {
  133. return &ResponseRunProcess{}, nil
  134. }
  135. }
  136. func StopProcess(label string, kill bool) (*ResponseStopProcess, error) {
  137. barak.mtx.Lock()
  138. proc := barak.processes[label]
  139. barak.mtx.Unlock()
  140. if proc == nil {
  141. return nil, Errorf("Process does not exist: %v", label)
  142. }
  143. err := pcm.Stop(proc, kill)
  144. return &ResponseStopProcess{}, err
  145. }
  146. func ListProcesses() (*ResponseListProcesses, error) {
  147. var procs = []*pcm.Process{}
  148. barak.mtx.Lock()
  149. for _, proc := range barak.processes {
  150. procs = append(procs, proc)
  151. }
  152. barak.mtx.Unlock()
  153. return &ResponseListProcesses{
  154. Processes: procs,
  155. }, nil
  156. }
  157. func ServeFile(w http.ResponseWriter, req *http.Request) {
  158. authCommandStr := req.FormValue("auth_command")
  159. command, err := parseValidateCommandStr(authCommandStr)
  160. if err != nil {
  161. http.Error(w, Fmt("Invalid command: %v", err), 400)
  162. }
  163. serveCommand, ok := command.(CommandServeFile)
  164. if !ok {
  165. http.Error(w, "Invalid command", 400)
  166. }
  167. path := serveCommand.Path
  168. if path == "" {
  169. http.Error(w, "Must specify path", 400)
  170. return
  171. }
  172. file, err := os.Open(path)
  173. if err != nil {
  174. http.Error(w, Fmt("Error opening file: %v. %v", path, err), 400)
  175. return
  176. }
  177. _, err = io.Copy(w, file)
  178. if err != nil {
  179. fmt.Fprintf(os.Stderr, Fmt("Error serving file: %v. %v", path, err))
  180. return
  181. }
  182. }