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.

317 lines
8.2 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. Registries []string
  32. }
  33. // Global instance
  34. var barak = struct {
  35. mtx sync.Mutex
  36. pid int
  37. nonce uint64
  38. processes map[string]*pcm.Process
  39. validators []Validator
  40. rootDir string
  41. registries []string
  42. }{
  43. mtx: sync.Mutex{},
  44. pid: os.Getpid(),
  45. nonce: 0,
  46. processes: make(map[string]*pcm.Process),
  47. validators: nil,
  48. rootDir: "",
  49. registries: nil,
  50. }
  51. func main() {
  52. fmt.Printf("New Barak Process (PID: %d)\n", os.Getpid())
  53. // read flags to change options file.
  54. var optionsBytes []byte
  55. var optionsFile string
  56. var err error
  57. flag.StringVar(&optionsFile, "options-file", "", "Read options from file instead of stdin")
  58. flag.Parse()
  59. if optionsFile != "" {
  60. optionsBytes, err = ioutil.ReadFile(optionsFile)
  61. } else {
  62. optionsBytes, err = ioutil.ReadAll(os.Stdin)
  63. }
  64. if err != nil {
  65. panic(Fmt("Error reading input: %v", err))
  66. }
  67. options := binary.ReadJSON(&Options{}, optionsBytes, &err).(*Options)
  68. if err != nil {
  69. panic(Fmt("Error parsing input: %v", err))
  70. }
  71. barak.nonce = options.StartNonce
  72. barak.validators = options.Validators
  73. barak.rootDir = os.Getenv("BRKROOT")
  74. if barak.rootDir == "" {
  75. barak.rootDir = os.Getenv("HOME") + "/.barak"
  76. }
  77. err = EnsureDir(barak.rootDir)
  78. if err != nil {
  79. panic(Fmt("Error creating barak rootDir: %v", err))
  80. }
  81. barak.registries = options.Registries
  82. // Write pid to file.
  83. err = AtomicWriteFile(barak.rootDir+"/pidfile", []byte(Fmt("%v", barak.pid)))
  84. if err != nil {
  85. panic(Fmt("Error writing pidfile: %v", err))
  86. }
  87. // Debug.
  88. fmt.Printf("Options: %v\n", options)
  89. fmt.Printf("Barak: %v\n", barak)
  90. // Start rpc server.
  91. mux := http.NewServeMux()
  92. mux.HandleFunc("/download", ServeFile)
  93. mux.HandleFunc("/register", Register)
  94. // TODO: mux.HandleFunc("/upload", UploadFile)
  95. rpc.RegisterRPCFuncs(mux, Routes)
  96. rpc.StartHTTPServer(options.ListenAddress, mux)
  97. // Register this barak with central listener
  98. for _, registry := range barak.registries {
  99. go func(registry string) {
  100. resp, err := http.Get(registry + "/register")
  101. if err != nil {
  102. fmt.Printf("Error registering to registry %v:\n %v\n", registry, err)
  103. return
  104. }
  105. body, _ := ioutil.ReadAll(resp.Body)
  106. fmt.Printf("Successfully registered with registry %v\n %v\n", registry, string(body))
  107. }(registry)
  108. }
  109. TrapSignal(func() {
  110. fmt.Println("Barak shutting down")
  111. })
  112. }
  113. //------------------------------------------------------------------------------
  114. // RPC functions
  115. func Status() (*ResponseStatus, error) {
  116. barak.mtx.Lock()
  117. pid := barak.pid
  118. nonce := barak.nonce
  119. validators := barak.validators
  120. barak.mtx.Unlock()
  121. return &ResponseStatus{
  122. Pid: pid,
  123. Nonce: nonce,
  124. Validators: validators,
  125. }, nil
  126. }
  127. func Run(authCommand AuthCommand) (interface{}, error) {
  128. command, err := parseValidateCommand(authCommand)
  129. if err != nil {
  130. return nil, err
  131. }
  132. log.Info(Fmt("Run() received command %v:\n%v", reflect.TypeOf(command), command))
  133. // Issue command
  134. switch c := command.(type) {
  135. case CommandRunProcess:
  136. return RunProcess(c.Wait, c.Label, c.ExecPath, c.Args, c.Input)
  137. case CommandStopProcess:
  138. return StopProcess(c.Label, c.Kill)
  139. case CommandListProcesses:
  140. return ListProcesses()
  141. default:
  142. return nil, errors.New("Invalid endpoint for command")
  143. }
  144. }
  145. func parseValidateCommandStr(authCommandStr string) (Command, error) {
  146. var err error
  147. authCommand := binary.ReadJSON(AuthCommand{}, []byte(authCommandStr), &err).(AuthCommand)
  148. if err != nil {
  149. fmt.Printf("Failed to parse auth_command")
  150. return nil, errors.New("AuthCommand parse error")
  151. }
  152. return parseValidateCommand(authCommand)
  153. }
  154. func parseValidateCommand(authCommand AuthCommand) (Command, error) {
  155. commandJSONStr := authCommand.CommandJSONStr
  156. signatures := authCommand.Signatures
  157. // Validate commandJSONStr
  158. if !validate([]byte(commandJSONStr), barak.validators, signatures) {
  159. fmt.Printf("Failed validation attempt")
  160. return nil, errors.New("Validation error")
  161. }
  162. // Parse command
  163. var err error
  164. command := binary.ReadJSON(NoncedCommand{}, []byte(commandJSONStr), &err).(NoncedCommand)
  165. if err != nil {
  166. fmt.Printf("Failed to parse command")
  167. return nil, errors.New("Command parse error")
  168. }
  169. // Prevent replays
  170. if barak.nonce+1 != command.Nonce {
  171. return nil, errors.New("Replay error")
  172. } else {
  173. barak.nonce += 1
  174. }
  175. return command.Command, nil
  176. }
  177. //------------------------------------------------------------------------------
  178. // RPC base commands
  179. // WARNING Not validated, do not export to routes.
  180. func RunProcess(wait bool, label string, execPath string, args []string, input string) (*ResponseRunProcess, error) {
  181. barak.mtx.Lock()
  182. // First, see if there already is a process labeled 'label'
  183. existing := barak.processes[label]
  184. if existing != nil && existing.EndTime.IsZero() {
  185. barak.mtx.Unlock()
  186. return nil, fmt.Errorf("Process already exists: %v", label)
  187. }
  188. // Otherwise, create one.
  189. err := EnsureDir(barak.rootDir + "/outputs")
  190. if err != nil {
  191. return nil, fmt.Errorf("Failed to create outputs dir: %v", err)
  192. }
  193. outPath := Fmt("%v/outputs/%v_%v.out", barak.rootDir, label, time.Now().Format("2006_01_02_15_04_05_MST"))
  194. proc, err := pcm.Create(pcm.ProcessModeDaemon, label, execPath, args, input, outPath)
  195. if err == nil {
  196. barak.processes[label] = proc
  197. }
  198. barak.mtx.Unlock()
  199. if err != nil {
  200. return nil, err
  201. }
  202. if wait {
  203. <-proc.WaitCh
  204. output := pcm.ReadOutput(proc)
  205. fmt.Println("Read output", output)
  206. if proc.ExitState == nil {
  207. return &ResponseRunProcess{
  208. Success: true,
  209. Output: output,
  210. }, nil
  211. } else {
  212. return &ResponseRunProcess{
  213. Success: proc.ExitState.Success(), // Would be always false?
  214. Output: output,
  215. }, nil
  216. }
  217. } else {
  218. return &ResponseRunProcess{
  219. Success: true,
  220. Output: "",
  221. }, nil
  222. }
  223. }
  224. func StopProcess(label string, kill bool) (*ResponseStopProcess, error) {
  225. barak.mtx.Lock()
  226. proc := barak.processes[label]
  227. barak.mtx.Unlock()
  228. if proc == nil {
  229. return nil, fmt.Errorf("Process does not exist: %v", label)
  230. }
  231. err := pcm.Stop(proc, kill)
  232. return &ResponseStopProcess{}, err
  233. }
  234. func ListProcesses() (*ResponseListProcesses, error) {
  235. var procs = []*pcm.Process{}
  236. barak.mtx.Lock()
  237. fmt.Println("Processes: %v", barak.processes)
  238. for _, proc := range barak.processes {
  239. procs = append(procs, proc)
  240. }
  241. barak.mtx.Unlock()
  242. return &ResponseListProcesses{
  243. Processes: procs,
  244. }, nil
  245. }
  246. // Another barak instance registering its external
  247. // address to a remote barak.
  248. func Register(w http.ResponseWriter, req *http.Request) {
  249. registry, err := os.OpenFile(barak.rootDir+"/registry.log", os.O_RDWR|os.O_APPEND, 0x600)
  250. if err != nil {
  251. http.Error(w, "Could not open registry file. Please contact the administrator", 500)
  252. return
  253. }
  254. // TODO: Also check the X-FORWARDED-FOR or whatever it's called.
  255. registry.Write([]byte(Fmt("++ %v\n", req.RemoteAddr)))
  256. registry.Close()
  257. w.Header().Set("Content-Type", "application/json")
  258. w.WriteHeader(200)
  259. w.Write([]byte("Noted!"))
  260. }
  261. func ServeFile(w http.ResponseWriter, req *http.Request) {
  262. authCommandStr := req.FormValue("auth_command")
  263. command, err := parseValidateCommandStr(authCommandStr)
  264. if err != nil {
  265. http.Error(w, Fmt("Invalid command: %v", err), 400)
  266. }
  267. serveCommand, ok := command.(CommandServeFile)
  268. if !ok {
  269. http.Error(w, "Invalid command", 400)
  270. }
  271. path := serveCommand.Path
  272. if path == "" {
  273. http.Error(w, "Must specify path", 400)
  274. return
  275. }
  276. file, err := os.Open(path)
  277. if err != nil {
  278. http.Error(w, Fmt("Error opening file: %v. %v", path, err), 400)
  279. return
  280. }
  281. _, err = io.Copy(w, file)
  282. if err != nil {
  283. fmt.Fprintf(os.Stderr, Fmt("Error serving file: %v. %v", path, err))
  284. return
  285. }
  286. }