subservice.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. package subservice
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "runtime"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "time"
  17. modules "imuslab.com/arozos/mod/modules"
  18. "imuslab.com/arozos/mod/network/reverseproxy"
  19. "imuslab.com/arozos/mod/network/websocketproxy"
  20. user "imuslab.com/arozos/mod/user"
  21. )
  22. /*
  23. ArOZ Online System - Dynamic Subsystem loading services
  24. author: tobychui
  25. This module load in ArOZ Online Subservice using authorized reverse proxy channel.
  26. Please see the demo subservice module for more information on implementing a subservice module.
  27. */
  28. type SubService struct {
  29. Port int //Port that this subservice use
  30. ServiceDir string //The directory where the service is located
  31. Path string //Path that this subservice is located
  32. RpEndpoint string //Reverse Proxy Endpoint
  33. ProxyHandler *reverseproxy.ReverseProxy //Reverse Proxy Object
  34. Info modules.ModuleInfo //Module information for this subservice
  35. Process *exec.Cmd //The CMD runtime object of the process
  36. }
  37. type SubServiceRouter struct {
  38. ReservePaths []string
  39. RunningSubService []SubService
  40. BasePort int
  41. listenPort int
  42. userHandler *user.UserHandler
  43. moduleHandler *modules.ModuleHandler
  44. }
  45. func NewSubServiceRouter(ReservePaths []string, basePort int, userHandler *user.UserHandler, moduleHandler *modules.ModuleHandler, parentPort int) *SubServiceRouter {
  46. return &SubServiceRouter{
  47. ReservePaths: ReservePaths,
  48. RunningSubService: []SubService{},
  49. BasePort: basePort,
  50. listenPort: parentPort,
  51. userHandler: userHandler,
  52. moduleHandler: moduleHandler,
  53. }
  54. }
  55. //Load and start all the subservices inside this rootpath
  56. func (sr *SubServiceRouter) LoadSubservicesFromRootPath(rootpath string) {
  57. scanningPath := filepath.ToSlash(filepath.Clean(rootpath)) + "/*"
  58. subservices, _ := filepath.Glob(scanningPath)
  59. for _, servicePath := range subservices {
  60. if !fileExists(servicePath + "/.disabled") {
  61. //Only enable module with no suspended config file
  62. err := sr.Launch(servicePath, true)
  63. if err != nil {
  64. log.Println(err)
  65. }
  66. }
  67. }
  68. }
  69. func (sr *SubServiceRouter) Launch(servicePath string, startupMode bool) error {
  70. //Get the executable name from its path
  71. binaryname := filepath.Base(servicePath)
  72. serviceRoot := filepath.Base(servicePath)
  73. binaryExecPath := filepath.ToSlash(binaryname)
  74. if runtime.GOOS == "windows" {
  75. binaryExecPath = binaryExecPath + ".exe"
  76. } else {
  77. binaryExecPath = binaryExecPath + "_" + runtime.GOOS + "_" + runtime.GOARCH
  78. }
  79. if runtime.GOOS == "windows" && !fileExists(servicePath+"/"+binaryExecPath) {
  80. if startupMode {
  81. log.Println("Failed to load subservice: "+serviceRoot, " File not exists "+servicePath+"/"+binaryExecPath+". Skipping this service")
  82. return errors.New("Failed to load subservice")
  83. } else {
  84. return errors.New("Failed to load subservice")
  85. }
  86. } else if runtime.GOOS == "linux" {
  87. //Check if service installed using which
  88. cmd := exec.Command("which", serviceRoot)
  89. searchResults, _ := cmd.CombinedOutput()
  90. if len(strings.TrimSpace(string(searchResults))) == 0 {
  91. //This is not installed. Check if it exists as a binary (aka ./myservice)
  92. if !fileExists(servicePath + "/" + binaryExecPath) {
  93. if startupMode {
  94. log.Println("Package not installed. " + serviceRoot)
  95. return errors.New("Failed to load subservice: Package not installed")
  96. } else {
  97. return errors.New("Package not installed.")
  98. }
  99. }
  100. }
  101. } else if runtime.GOOS == "darwin" {
  102. //Skip the whereis approach that linux use
  103. if !fileExists(servicePath + "/" + binaryExecPath) {
  104. log.Println("Failed to load subservice: "+serviceRoot, " File not exists "+servicePath+"/"+binaryExecPath+". Skipping this service")
  105. return errors.New("Failed to load subservice")
  106. }
  107. }
  108. //Check if the suspend file exists. If yes, clear it
  109. if fileExists(servicePath + "/.disabled") {
  110. os.Remove(servicePath + "/.disabled")
  111. }
  112. //Check if there are config files that replace the -info tag. If yes, use it instead.
  113. out := []byte{}
  114. if fileExists(servicePath + "/moduleInfo.json") {
  115. launchConfig, err := ioutil.ReadFile(servicePath + "/moduleInfo.json")
  116. if err != nil {
  117. if startupMode {
  118. log.Fatal("Failed to read moduleInfo.json: "+binaryname, err)
  119. } else {
  120. return errors.New("Failed to read moduleInfo.json: " + binaryname)
  121. }
  122. }
  123. out = launchConfig
  124. } else {
  125. infocmd := exec.Command(servicePath+"/"+binaryExecPath, "-info")
  126. launchConfig, err := infocmd.CombinedOutput()
  127. if err != nil {
  128. log.Println("*Subservice* startup flag -info return no JSON string and moduleInfo.json does not exists.")
  129. if startupMode {
  130. log.Fatal("Unable to start service: "+binaryname, err)
  131. } else {
  132. return errors.New("Unable to start service: " + binaryname)
  133. }
  134. }
  135. out = launchConfig
  136. }
  137. //Clean the module info and append it into the module list
  138. serviceLaunchInfo := strings.TrimSpace(string(out))
  139. thisModuleInfo := modules.ModuleInfo{}
  140. err := json.Unmarshal([]byte(serviceLaunchInfo), &thisModuleInfo)
  141. if err != nil {
  142. if startupMode {
  143. log.Fatal("Failed to load subservice: "+serviceRoot+"\n", err.Error())
  144. } else {
  145. return errors.New("Failed to load subservice: " + serviceRoot)
  146. }
  147. }
  148. var thisSubService SubService
  149. if fileExists(servicePath + "/.noproxy") {
  150. //Adaptive mode. This is designed for modules that do not designed with ArOZ Online in mind.
  151. //Ignore proxy setup and startup the application
  152. absolutePath, _ := filepath.Abs(servicePath + "/" + binaryExecPath)
  153. if fileExists(servicePath + "/.startscript") {
  154. initPath := servicePath + "/start.sh"
  155. if runtime.GOOS == "windows" {
  156. initPath = servicePath + "/start.bat"
  157. }
  158. if !fileExists(initPath) {
  159. if startupMode {
  160. log.Fatal("start.sh not found. Unable to startup service " + serviceRoot)
  161. } else {
  162. return errors.New("start.sh not found. Unable to startup service " + serviceRoot)
  163. }
  164. }
  165. absolutePath, _ = filepath.Abs(initPath)
  166. }
  167. cmd := exec.Command(absolutePath)
  168. cmd.Stdout = os.Stdout
  169. cmd.Stderr = os.Stderr
  170. cmd.Dir = filepath.ToSlash(servicePath + "/")
  171. //Spawn a new go routine to run this subservice
  172. go func(cmdObject *exec.Cmd) {
  173. if err := cmd.Start(); err != nil {
  174. panic(err)
  175. }
  176. }(cmd)
  177. //Create the servie object
  178. thisSubService = SubService{
  179. Path: binaryExecPath,
  180. Info: thisModuleInfo,
  181. ServiceDir: serviceRoot,
  182. Process: cmd,
  183. }
  184. log.Println("[Subservice] Starting service " + serviceRoot + " in compatibility mode.")
  185. } else {
  186. //Create a proxy for this service
  187. //Get proxy endpoint from startDir dir
  188. rProxyEndpoint := filepath.Dir(thisModuleInfo.StartDir)
  189. //Check if this path is reversed
  190. if stringInSlice(rProxyEndpoint, sr.ReservePaths) || rProxyEndpoint == "" {
  191. if startupMode {
  192. log.Fatal(serviceRoot + " service try to request system reserve path as Reverse Proxy endpoint.")
  193. } else {
  194. return errors.New(serviceRoot + " service try to request system reserve path as Reverse Proxy endpoint.")
  195. }
  196. }
  197. //Assign a port for this subservice
  198. thisServicePort := sr.GetNextUsablePort()
  199. //Run the subservice with the given port
  200. absolutePath, _ := filepath.Abs(servicePath + "/" + binaryExecPath)
  201. if fileExists(servicePath + "/.startscript") {
  202. initPath := servicePath + "/start.sh"
  203. if runtime.GOOS == "windows" {
  204. initPath = servicePath + "/start.bat"
  205. }
  206. if !fileExists(initPath) {
  207. if startupMode {
  208. log.Fatal("start.sh not found. Unable to startup service " + serviceRoot)
  209. } else {
  210. return errors.New(serviceRoot + "start.sh not found. Unable to startup service " + serviceRoot)
  211. }
  212. }
  213. absolutePath, _ = filepath.Abs(initPath)
  214. }
  215. servicePort := ":" + intToString(thisServicePort)
  216. if fileExists(filepath.Join(servicePath, "/.intport")) {
  217. servicePort = intToString(thisServicePort)
  218. }
  219. cmd := exec.Command(absolutePath, "-port", servicePort, "-rpt", "http://localhost:"+intToString(sr.listenPort)+"/api/ajgi/interface")
  220. cmd.Stdout = os.Stdout
  221. cmd.Stderr = os.Stderr
  222. cmd.Dir = filepath.ToSlash(servicePath + "/")
  223. //log.Println(cmd.Dir,binaryExecPath)
  224. //Spawn a new go routine to run this subservice
  225. go func(cmdObject *exec.Cmd) {
  226. if err := cmd.Start(); err != nil {
  227. panic(err)
  228. }
  229. }(cmd)
  230. //Create a subservice object for this subservice
  231. thisSubService = SubService{
  232. Port: thisServicePort,
  233. Path: binaryExecPath,
  234. ServiceDir: serviceRoot,
  235. RpEndpoint: rProxyEndpoint,
  236. Info: thisModuleInfo,
  237. Process: cmd,
  238. }
  239. //Create a new proxy object
  240. path, _ := url.Parse("http://localhost:" + intToString(thisServicePort))
  241. proxy := reverseproxy.NewReverseProxy(path)
  242. thisSubService.ProxyHandler = proxy
  243. }
  244. //Append this subservice into the list
  245. sr.RunningSubService = append(sr.RunningSubService, thisSubService)
  246. //Append this module into the loaded module list
  247. sr.moduleHandler.LoadedModule = append(sr.moduleHandler.LoadedModule, thisModuleInfo)
  248. return nil
  249. }
  250. func (sr *SubServiceRouter) HandleListing(w http.ResponseWriter, r *http.Request) {
  251. //List all subservice running in the background
  252. type visableInfo struct {
  253. Port int
  254. ServiceDir string
  255. Path string
  256. RpEndpoint string
  257. ProcessID int
  258. Info modules.ModuleInfo
  259. }
  260. type disabledServiceInfo struct {
  261. ServiceDir string
  262. Path string
  263. }
  264. enabled := []visableInfo{}
  265. disabled := []disabledServiceInfo{}
  266. for _, thisSubservice := range sr.RunningSubService {
  267. enabled = append(enabled, visableInfo{
  268. Port: thisSubservice.Port,
  269. Path: thisSubservice.Path,
  270. ServiceDir: thisSubservice.ServiceDir,
  271. RpEndpoint: thisSubservice.RpEndpoint,
  272. ProcessID: thisSubservice.Process.Process.Pid,
  273. Info: thisSubservice.Info,
  274. })
  275. }
  276. disabledModules, _ := filepath.Glob("subservice/*/.disabled")
  277. for _, modFile := range disabledModules {
  278. thisdsi := new(disabledServiceInfo)
  279. thisdsi.ServiceDir = filepath.Base(filepath.Dir(modFile))
  280. thisdsi.Path = filepath.Base(filepath.Dir(modFile))
  281. if runtime.GOOS == "windows" {
  282. thisdsi.Path = thisdsi.Path + ".exe"
  283. }
  284. disabled = append(disabled, *thisdsi)
  285. }
  286. jsonString, err := json.Marshal(struct {
  287. Enabled []visableInfo
  288. Disabled []disabledServiceInfo
  289. }{
  290. Enabled: enabled,
  291. Disabled: disabled,
  292. })
  293. if err != nil {
  294. log.Println(err)
  295. }
  296. sendJSONResponse(w, string(jsonString))
  297. }
  298. //Kill the subservice that is currently running
  299. func (sr *SubServiceRouter) HandleKillSubService(w http.ResponseWriter, r *http.Request) {
  300. userinfo, _ := sr.userHandler.GetUserInfoFromRequest(w, r)
  301. //Require admin permission
  302. if !userinfo.IsAdmin() {
  303. sendErrorResponse(w, "Permission denied")
  304. return
  305. }
  306. //OK. Get paramters
  307. serviceDir, _ := mv(r, "serviceDir", true)
  308. //moduleName, _ := mv(r, "moduleName", true)
  309. err := sr.KillSubService(serviceDir)
  310. if err != nil {
  311. sendErrorResponse(w, err.Error())
  312. } else {
  313. sendOK(w)
  314. }
  315. }
  316. func (sr *SubServiceRouter) HandleStartSubService(w http.ResponseWriter, r *http.Request) {
  317. userinfo, _ := sr.userHandler.GetUserInfoFromRequest(w, r)
  318. //Require admin permission
  319. if !userinfo.IsAdmin() {
  320. sendErrorResponse(w, "Permission denied")
  321. return
  322. }
  323. //OK. Get which dir to start
  324. serviceDir, _ := mv(r, "serviceDir", true)
  325. err := sr.StartSubService(serviceDir)
  326. if err != nil {
  327. sendErrorResponse(w, err.Error())
  328. } else {
  329. sendOK(w)
  330. }
  331. }
  332. //Check if the user has permission to access such proxy module
  333. func (sr *SubServiceRouter) CheckUserPermissionOnSubservice(ss *SubService, u *user.User) bool {
  334. moduleName := ss.Info.Name
  335. return u.GetModuleAccessPermission(moduleName)
  336. }
  337. //Check if the target is reverse proxy. If yes, return the proxy handler and the rewritten url in string
  338. func (sr *SubServiceRouter) CheckIfReverseProxyPath(r *http.Request) (bool, *reverseproxy.ReverseProxy, string, *SubService) {
  339. requestURL := r.URL.Path
  340. for _, subservice := range sr.RunningSubService {
  341. thisServiceProxyEP := subservice.RpEndpoint
  342. if thisServiceProxyEP != "" {
  343. if len(requestURL) > len(thisServiceProxyEP)+1 && requestURL[1:len(thisServiceProxyEP)+1] == thisServiceProxyEP {
  344. //This is a proxy path. Generate the rewrite URL
  345. //Get all GET paramters from URL
  346. values := r.URL.Query()
  347. counter := 0
  348. parsedGetTail := ""
  349. for k, v := range values {
  350. if counter == 0 {
  351. parsedGetTail = "?" + k + "=" + url.QueryEscape(v[0])
  352. } else {
  353. parsedGetTail = parsedGetTail + "&" + k + "=" + url.QueryEscape(v[0])
  354. }
  355. counter++
  356. }
  357. return true, subservice.ProxyHandler, requestURL[len(thisServiceProxyEP)+1:] + parsedGetTail, &subservice
  358. }
  359. }
  360. }
  361. return false, nil, "", &SubService{}
  362. }
  363. func (sr *SubServiceRouter) Close() {
  364. //Handle shutdown of subprocesses. Kill all of them
  365. for _, subservice := range sr.RunningSubService {
  366. cmd := subservice.Process
  367. if cmd != nil {
  368. if runtime.GOOS == "windows" {
  369. //Force kill with the power of CMD
  370. kill := exec.Command("TASKKILL", "/T", "/F", "/PID", strconv.Itoa(cmd.Process.Pid))
  371. //kill.Stderr = os.Stderr
  372. //kill.Stdout = os.Stdout
  373. kill.Run()
  374. } else {
  375. //Send sigkill to process
  376. cmd.Process.Kill()
  377. }
  378. }
  379. }
  380. }
  381. func (sr *SubServiceRouter) KillSubService(serviceDir string) error {
  382. //Remove them from the system
  383. ssi := -1
  384. moduleName := ""
  385. for i, ss := range sr.RunningSubService {
  386. if ss.ServiceDir == serviceDir {
  387. ssi = i
  388. moduleName = ss.Info.Name
  389. //Kill the module cmd
  390. cmd := ss.Process
  391. if cmd != nil {
  392. if runtime.GOOS == "windows" {
  393. //Force kill with the power of CMD
  394. kill := exec.Command("TASKKILL", "/T", "/F", "/PID", strconv.Itoa(cmd.Process.Pid))
  395. kill.Run()
  396. } else {
  397. err := cmd.Process.Kill()
  398. if err != nil {
  399. return err
  400. }
  401. }
  402. }
  403. //Write a suspended file into the module
  404. ioutil.WriteFile("subservice/"+ss.ServiceDir+"/.disabled", []byte(""), 0755)
  405. }
  406. }
  407. //Pop this service from running Subservice
  408. if ssi != -1 {
  409. i := ssi
  410. copy(sr.RunningSubService[i:], sr.RunningSubService[i+1:])
  411. sr.RunningSubService = sr.RunningSubService[:len(sr.RunningSubService)-1]
  412. }
  413. //Pop the related module from the loadedModule list
  414. mi := -1
  415. for i, m := range sr.moduleHandler.LoadedModule {
  416. if m.Name == moduleName {
  417. mi = i
  418. }
  419. }
  420. if mi != -1 {
  421. i := mi
  422. copy(sr.moduleHandler.LoadedModule[i:], sr.moduleHandler.LoadedModule[i+1:])
  423. sr.moduleHandler.LoadedModule = sr.moduleHandler.LoadedModule[:len(sr.moduleHandler.LoadedModule)-1]
  424. }
  425. return nil
  426. }
  427. func (sr *SubServiceRouter) StartSubService(serviceDir string) error {
  428. if fileExists("subservice/" + serviceDir) {
  429. err := sr.Launch("subservice/"+serviceDir, false)
  430. if err != nil {
  431. return err
  432. }
  433. } else {
  434. return errors.New("Subservice directory not exists.")
  435. }
  436. //Sort the list
  437. sort.Slice(sr.moduleHandler.LoadedModule, func(i, j int) bool {
  438. return sr.moduleHandler.LoadedModule[i].Name < sr.moduleHandler.LoadedModule[j].Name
  439. })
  440. sort.Slice(sr.RunningSubService, func(i, j int) bool {
  441. return sr.RunningSubService[i].Info.Name < sr.RunningSubService[j].Info.Name
  442. })
  443. return nil
  444. }
  445. //Get a list of subservice roots in realpath
  446. func (sr *SubServiceRouter) GetSubserviceRoot() []string {
  447. subserviceRoots := []string{}
  448. for _, subService := range sr.RunningSubService {
  449. subserviceRoots = append(subserviceRoots, subService.Path)
  450. }
  451. return subserviceRoots
  452. }
  453. //Scan and get the next avaible port for subservice from its basePort
  454. func (sr *SubServiceRouter) GetNextUsablePort() int {
  455. basePort := sr.BasePort
  456. for sr.CheckIfPortInUse(basePort) {
  457. basePort++
  458. }
  459. return basePort
  460. }
  461. func (sr *SubServiceRouter) CheckIfPortInUse(port int) bool {
  462. for _, service := range sr.RunningSubService {
  463. if service.Port == port {
  464. return true
  465. }
  466. }
  467. return false
  468. }
  469. func (sr *SubServiceRouter) HandleRoutingRequest(w http.ResponseWriter, r *http.Request, proxy *reverseproxy.ReverseProxy, subserviceObject *SubService, rewriteURL string) {
  470. u, _ := sr.userHandler.GetUserInfoFromRequest(w, r)
  471. if !sr.CheckUserPermissionOnSubservice(subserviceObject, u) {
  472. //Permission denied
  473. http.NotFound(w, r)
  474. return
  475. }
  476. //Perform reverse proxy serving
  477. r.URL, _ = url.Parse(rewriteURL)
  478. token, _ := sr.userHandler.GetAuthAgent().NewTokenFromRequest(w, r)
  479. r.Header.Set("aouser", u.Username)
  480. r.Header.Set("aotoken", token)
  481. r.Header.Set("X-Forwarded-Host", r.Host)
  482. if r.Header["Upgrade"] != nil && r.Header["Upgrade"][0] == "websocket" {
  483. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  484. r.Header.Set("A-Upgrade", "websocket")
  485. u, _ := url.Parse("ws://localhost:" + strconv.Itoa(subserviceObject.Port) + r.URL.String())
  486. wspHandler := websocketproxy.NewProxy(u)
  487. wspHandler.ServeHTTP(w, r)
  488. return
  489. }
  490. r.Host = r.URL.Host
  491. err := proxy.ServeHTTP(w, r)
  492. if err != nil {
  493. //Check if it is cancelling events.
  494. if !strings.Contains(err.Error(), "cancel") {
  495. log.Println(subserviceObject.Info.Name + " IS NOT RESPONDING!")
  496. sr.RestartSubService(subserviceObject)
  497. }
  498. }
  499. }
  500. //Handle fail start over when the remote target is not responding
  501. func (sr *SubServiceRouter) RestartSubService(ss *SubService) {
  502. go func(ss *SubService) {
  503. //Kill the original subservice
  504. sr.KillSubService(ss.ServiceDir)
  505. log.Println("RESTARTING SUBSERVICE " + ss.Info.Name + " IN 10 SECOUNDS")
  506. time.Sleep(10000 * time.Millisecond)
  507. sr.StartSubService(ss.ServiceDir)
  508. log.Println("SUBSERVICE " + ss.Info.Name + " RESTARTED")
  509. }(ss)
  510. }