subservice.go 18 KB

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