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.

277 lines
6.9 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
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. "flag"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "net/http"
  12. "os"
  13. "reflect"
  14. "sync"
  15. "time"
  16. "github.com/tendermint/tendermint/binary"
  17. . "github.com/tendermint/tendermint/cmd/barak/types"
  18. . "github.com/tendermint/tendermint/common"
  19. pcm "github.com/tendermint/tendermint/process"
  20. "github.com/tendermint/tendermint/rpc"
  21. )
  22. var Routes = map[string]*rpc.RPCFunc{
  23. "status": rpc.NewRPCFunc(Status, []string{}),
  24. "run": rpc.NewRPCFunc(Run, []string{"auth_command"}),
  25. // NOTE: also, two special non-JSONRPC routes called "download" and "upload"
  26. }
  27. type Options struct {
  28. Validators []Validator
  29. ListenAddress string
  30. StartNonce uint64
  31. }
  32. // Global instance
  33. var barak = struct {
  34. mtx sync.Mutex
  35. pid int
  36. nonce uint64
  37. processes map[string]*pcm.Process
  38. validators []Validator
  39. rootDir string
  40. }{
  41. mtx: sync.Mutex{},
  42. pid: os.Getpid(),
  43. nonce: 0,
  44. processes: make(map[string]*pcm.Process),
  45. validators: nil,
  46. rootDir: "",
  47. }
  48. func main() {
  49. fmt.Printf("New Barak Process (PID: %d)\n", os.Getpid())
  50. // read flags to change options file.
  51. var optionsBytes []byte
  52. var optionsFile string
  53. var err error
  54. flag.StringVar(&optionsFile, "options-file", "", "Read options from file instead of stdin")
  55. flag.Parse()
  56. if optionsFile != "" {
  57. optionsBytes, err = ioutil.ReadFile(optionsFile)
  58. } else {
  59. optionsBytes, err = ioutil.ReadAll(os.Stdin)
  60. }
  61. if err != nil {
  62. panic(Fmt("Error reading input: %v", err))
  63. }
  64. options := binary.ReadJSON(&Options{}, optionsBytes, &err).(*Options)
  65. if err != nil {
  66. panic(Fmt("Error parsing input: %v", err))
  67. }
  68. barak.nonce = options.StartNonce
  69. barak.validators = options.Validators
  70. barak.rootDir = os.Getenv("BRKROOT")
  71. if barak.rootDir == "" {
  72. barak.rootDir = os.Getenv("HOME") + "/.barak"
  73. }
  74. // Write pid to file.
  75. AtomicWriteFile(barak.rootDir+"/pidfile", []byte(Fmt("%v", barak.pid)))
  76. // Debug.
  77. fmt.Printf("Options: %v\n", options)
  78. fmt.Printf("Barak: %v\n", barak)
  79. // Start rpc server.
  80. mux := http.NewServeMux()
  81. mux.HandleFunc("/download", ServeFile)
  82. // TODO: mux.HandleFunc("/upload", UploadFile)
  83. rpc.RegisterRPCFuncs(mux, Routes)
  84. rpc.StartHTTPServer(options.ListenAddress, mux)
  85. TrapSignal(func() {
  86. fmt.Println("Barak shutting down")
  87. })
  88. }
  89. //------------------------------------------------------------------------------
  90. // RPC functions
  91. func Status() (*ResponseStatus, error) {
  92. barak.mtx.Lock()
  93. pid := barak.pid
  94. nonce := barak.nonce
  95. validators := barak.validators
  96. barak.mtx.Unlock()
  97. return &ResponseStatus{
  98. Pid: pid,
  99. Nonce: nonce,
  100. Validators: validators,
  101. }, nil
  102. }
  103. func Run(authCommand AuthCommand) (interface{}, error) {
  104. command, err := parseValidateCommand(authCommand)
  105. if err != nil {
  106. return nil, err
  107. }
  108. log.Info(Fmt("Run() received command %v:\n%v", reflect.TypeOf(command), command))
  109. // Issue command
  110. switch c := command.(type) {
  111. case CommandRunProcess:
  112. return RunProcess(c.Wait, c.Label, c.ExecPath, c.Args, c.Input)
  113. case CommandStopProcess:
  114. return StopProcess(c.Label, c.Kill)
  115. case CommandListProcesses:
  116. return ListProcesses()
  117. default:
  118. return nil, errors.New("Invalid endpoint for command")
  119. }
  120. }
  121. func parseValidateCommandStr(authCommandStr string) (Command, error) {
  122. var err error
  123. authCommand := binary.ReadJSON(AuthCommand{}, []byte(authCommandStr), &err).(AuthCommand)
  124. if err != nil {
  125. fmt.Printf("Failed to parse auth_command")
  126. return nil, errors.New("AuthCommand parse error")
  127. }
  128. return parseValidateCommand(authCommand)
  129. }
  130. func parseValidateCommand(authCommand AuthCommand) (Command, error) {
  131. commandJSONStr := authCommand.CommandJSONStr
  132. signatures := authCommand.Signatures
  133. // Validate commandJSONStr
  134. if !validate([]byte(commandJSONStr), barak.validators, signatures) {
  135. fmt.Printf("Failed validation attempt")
  136. return nil, errors.New("Validation error")
  137. }
  138. // Parse command
  139. var err error
  140. command := binary.ReadJSON(NoncedCommand{}, []byte(commandJSONStr), &err).(NoncedCommand)
  141. if err != nil {
  142. fmt.Printf("Failed to parse command")
  143. return nil, errors.New("Command parse error")
  144. }
  145. // Prevent replays
  146. if barak.nonce+1 != command.Nonce {
  147. return nil, errors.New("Replay error")
  148. } else {
  149. barak.nonce += 1
  150. }
  151. return command.Command, nil
  152. }
  153. //------------------------------------------------------------------------------
  154. // RPC base commands
  155. // WARNING Not validated, do not export to routes.
  156. func RunProcess(wait bool, label string, execPath string, args []string, input string) (*ResponseRunProcess, error) {
  157. barak.mtx.Lock()
  158. // First, see if there already is a process labeled 'label'
  159. existing := barak.processes[label]
  160. if existing != nil && existing.EndTime.IsZero() {
  161. barak.mtx.Unlock()
  162. return nil, fmt.Errorf("Process already exists: %v", label)
  163. }
  164. // Otherwise, create one.
  165. err := EnsureDir(barak.rootDir + "/outputs")
  166. if err != nil {
  167. return nil, fmt.Errorf("Failed to create outputs dir: %v", err)
  168. }
  169. outPath := Fmt("%v/outputs/%v_%v.out", barak.rootDir, label, time.Now().Format("2006_01_02_15_04_05_MST"))
  170. proc, err := pcm.Create(pcm.ProcessModeDaemon, label, execPath, args, input, outPath)
  171. if err == nil {
  172. barak.processes[label] = proc
  173. }
  174. barak.mtx.Unlock()
  175. if err != nil {
  176. return nil, err
  177. }
  178. if wait {
  179. <-proc.WaitCh
  180. output := pcm.ReadOutput(proc)
  181. fmt.Println("Read output", output)
  182. if proc.ExitState == nil {
  183. return &ResponseRunProcess{
  184. Success: true,
  185. Output: output,
  186. }, nil
  187. } else {
  188. return &ResponseRunProcess{
  189. Success: proc.ExitState.Success(), // Would be always false?
  190. Output: output,
  191. }, nil
  192. }
  193. } else {
  194. return &ResponseRunProcess{
  195. Success: true,
  196. Output: "",
  197. }, nil
  198. }
  199. }
  200. func StopProcess(label string, kill bool) (*ResponseStopProcess, error) {
  201. barak.mtx.Lock()
  202. proc := barak.processes[label]
  203. barak.mtx.Unlock()
  204. if proc == nil {
  205. return nil, fmt.Errorf("Process does not exist: %v", label)
  206. }
  207. err := pcm.Stop(proc, kill)
  208. return &ResponseStopProcess{}, err
  209. }
  210. func ListProcesses() (*ResponseListProcesses, error) {
  211. var procs = []*pcm.Process{}
  212. barak.mtx.Lock()
  213. fmt.Println("Processes: %v", barak.processes)
  214. for _, proc := range barak.processes {
  215. procs = append(procs, proc)
  216. }
  217. barak.mtx.Unlock()
  218. return &ResponseListProcesses{
  219. Processes: procs,
  220. }, nil
  221. }
  222. func ServeFile(w http.ResponseWriter, req *http.Request) {
  223. authCommandStr := req.FormValue("auth_command")
  224. command, err := parseValidateCommandStr(authCommandStr)
  225. if err != nil {
  226. http.Error(w, Fmt("Invalid command: %v", err), 400)
  227. }
  228. serveCommand, ok := command.(CommandServeFile)
  229. if !ok {
  230. http.Error(w, "Invalid command", 400)
  231. }
  232. path := serveCommand.Path
  233. if path == "" {
  234. http.Error(w, "Must specify path", 400)
  235. return
  236. }
  237. file, err := os.Open(path)
  238. if err != nil {
  239. http.Error(w, Fmt("Error opening file: %v. %v", path, err), 400)
  240. return
  241. }
  242. _, err = io.Copy(w, file)
  243. if err != nil {
  244. fmt.Fprintf(os.Stderr, Fmt("Error serving file: %v. %v", path, err))
  245. return
  246. }
  247. }