subservice.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. cmd := exec.Command(absolutePath, "-port", ":"+intToString(thisServicePort), "-rpt", "http://localhost:"+intToString(sr.listenPort)+"/api/ajgi/interface")
  229. cmd.Stdout = os.Stdout
  230. cmd.Stderr = os.Stderr
  231. cmd.Dir = filepath.ToSlash(servicePath + "/")
  232. //log.Println(cmd.Dir,binaryExecPath)
  233. //Spawn a new go routine to run this subservice
  234. go func(cmdObject *exec.Cmd) {
  235. if err := cmd.Start(); err != nil {
  236. panic(err)
  237. }
  238. }(cmd)
  239. //Create a subservice object for this subservice
  240. thisSubService = SubService{
  241. Port: thisServicePort,
  242. Path: binaryExecPath,
  243. ServiceDir: serviceRoot,
  244. RpEndpoint: rProxyEndpoint,
  245. Info: thisModuleInfo,
  246. Process: cmd,
  247. }
  248. //Create a new proxy object
  249. path, _ := url.Parse("http://localhost:" + intToString(thisServicePort))
  250. proxy := reverseproxy.NewReverseProxy(path)
  251. thisSubService.ProxyHandler = proxy
  252. }
  253. //Append this subservice into the list
  254. sr.RunningSubService = append(sr.RunningSubService, thisSubService)
  255. //Append this module into the loaded module list
  256. sr.moduleHandler.LoadedModule = append(sr.moduleHandler.LoadedModule, thisModuleInfo)
  257. return nil
  258. }
  259. func (sr *SubServiceRouter) HandleListing(w http.ResponseWriter, r *http.Request) {
  260. //List all subservice running in the background
  261. type visableInfo struct {
  262. Port int
  263. ServiceDir string
  264. Path string
  265. RpEndpoint string
  266. ProcessID int
  267. Info modules.ModuleInfo
  268. }
  269. type disabledServiceInfo struct {
  270. ServiceDir string
  271. Path string
  272. }
  273. enabled := []visableInfo{}
  274. disabled := []disabledServiceInfo{}
  275. for _, thisSubservice := range sr.RunningSubService {
  276. enabled = append(enabled, visableInfo{
  277. Port: thisSubservice.Port,
  278. Path: thisSubservice.Path,
  279. ServiceDir: thisSubservice.ServiceDir,
  280. RpEndpoint: thisSubservice.RpEndpoint,
  281. ProcessID: thisSubservice.Process.Process.Pid,
  282. Info: thisSubservice.Info,
  283. })
  284. }
  285. disabledModules, _ := filepath.Glob("subservice/*/.disabled")
  286. for _, modFile := range disabledModules {
  287. thisdsi := new(disabledServiceInfo)
  288. thisdsi.ServiceDir = filepath.Base(filepath.Dir(modFile))
  289. thisdsi.Path = filepath.Base(filepath.Dir(modFile))
  290. if runtime.GOOS == "windows" {
  291. thisdsi.Path = thisdsi.Path + ".exe"
  292. }
  293. disabled = append(disabled, *thisdsi)
  294. }
  295. jsonString, err := json.Marshal(struct {
  296. Enabled []visableInfo
  297. Disabled []disabledServiceInfo
  298. }{
  299. Enabled: enabled,
  300. Disabled: disabled,
  301. })
  302. if err != nil {
  303. log.Println(err)
  304. }
  305. sendJSONResponse(w, string(jsonString))
  306. }
  307. //Kill the subservice that is currently running
  308. func (sr *SubServiceRouter) HandleKillSubService(w http.ResponseWriter, r *http.Request) {
  309. userinfo, _ := sr.userHandler.GetUserInfoFromRequest(w, r)
  310. //Require admin permission
  311. if !userinfo.IsAdmin() {
  312. sendErrorResponse(w, "Permission denied")
  313. return
  314. }
  315. //OK. Get paramters
  316. serviceDir, _ := mv(r, "serviceDir", true)
  317. //moduleName, _ := mv(r, "moduleName", true)
  318. err := sr.KillSubService(serviceDir)
  319. if err != nil {
  320. sendErrorResponse(w, err.Error())
  321. } else {
  322. sendOK(w)
  323. }
  324. }
  325. func (sr *SubServiceRouter) HandleStartSubService(w http.ResponseWriter, r *http.Request) {
  326. userinfo, _ := sr.userHandler.GetUserInfoFromRequest(w, r)
  327. //Require admin permission
  328. if !userinfo.IsAdmin() {
  329. sendErrorResponse(w, "Permission denied")
  330. return
  331. }
  332. //OK. Get which dir to start
  333. serviceDir, _ := mv(r, "serviceDir", true)
  334. err := sr.StartSubService(serviceDir)
  335. if err != nil {
  336. sendErrorResponse(w, err.Error())
  337. } else {
  338. sendOK(w)
  339. }
  340. }
  341. //Check if the user has permission to access such proxy module
  342. func (sr *SubServiceRouter) CheckUserPermissionOnSubservice(ss *SubService, u *user.User) bool {
  343. moduleName := ss.Info.Name
  344. return u.GetModuleAccessPermission(moduleName)
  345. }
  346. //Check if the target is reverse proxy. If yes, return the proxy handler and the rewritten url in string
  347. func (sr *SubServiceRouter) CheckIfReverseProxyPath(r *http.Request) (bool, *reverseproxy.ReverseProxy, string, *SubService) {
  348. requestURL := r.URL.Path
  349. for _, subservice := range sr.RunningSubService {
  350. thisServiceProxyEP := subservice.RpEndpoint
  351. if thisServiceProxyEP != "" {
  352. if len(requestURL) > len(thisServiceProxyEP)+1 && requestURL[1:len(thisServiceProxyEP)+1] == thisServiceProxyEP {
  353. //This is a proxy path. Generate the rewrite URL
  354. //Get all GET paramters from URL
  355. values := r.URL.Query()
  356. counter := 0
  357. parsedGetTail := ""
  358. for k, v := range values {
  359. if counter == 0 {
  360. parsedGetTail = "?" + k + "=" + url.QueryEscape(v[0])
  361. } else {
  362. parsedGetTail = parsedGetTail + "&" + k + "=" + url.QueryEscape(v[0])
  363. }
  364. counter++
  365. }
  366. return true, subservice.ProxyHandler, requestURL[len(thisServiceProxyEP)+1:] + parsedGetTail, &subservice
  367. }
  368. }
  369. }
  370. return false, nil, "", &SubService{}
  371. }
  372. func (sr *SubServiceRouter) Close() {
  373. //Handle shutdown of subprocesses. Kill all of them
  374. for _, subservice := range sr.RunningSubService {
  375. cmd := subservice.Process
  376. if cmd != nil {
  377. if runtime.GOOS == "windows" {
  378. //Force kill with the power of CMD
  379. kill := exec.Command("TASKKILL", "/T", "/F", "/PID", strconv.Itoa(cmd.Process.Pid))
  380. //kill.Stderr = os.Stderr
  381. //kill.Stdout = os.Stdout
  382. kill.Run()
  383. } else {
  384. //Send sigkill to process
  385. cmd.Process.Kill()
  386. }
  387. }
  388. }
  389. }
  390. func (sr *SubServiceRouter) KillSubService(serviceDir string) error {
  391. //Remove them from the system
  392. ssi := -1
  393. moduleName := ""
  394. for i, ss := range sr.RunningSubService {
  395. if ss.ServiceDir == serviceDir {
  396. ssi = i
  397. moduleName = ss.Info.Name
  398. //Kill the module cmd
  399. cmd := ss.Process
  400. if cmd != nil {
  401. if runtime.GOOS == "windows" {
  402. //Force kill with the power of CMD
  403. kill := exec.Command("TASKKILL", "/T", "/F", "/PID", strconv.Itoa(cmd.Process.Pid))
  404. kill.Run()
  405. } else {
  406. err := cmd.Process.Kill()
  407. if err != nil {
  408. return err
  409. }
  410. }
  411. }
  412. //Write a suspended file into the module
  413. ioutil.WriteFile("subservice/"+ss.ServiceDir+"/.disabled", []byte(""), 0755)
  414. }
  415. }
  416. //Pop this service from running Subservice
  417. if ssi != -1 {
  418. i := ssi
  419. copy(sr.RunningSubService[i:], sr.RunningSubService[i+1:])
  420. sr.RunningSubService = sr.RunningSubService[:len(sr.RunningSubService)-1]
  421. }
  422. //Pop the related module from the loadedModule list
  423. mi := -1
  424. for i, m := range sr.moduleHandler.LoadedModule {
  425. if m.Name == moduleName {
  426. mi = i
  427. }
  428. }
  429. if mi != -1 {
  430. i := mi
  431. copy(sr.moduleHandler.LoadedModule[i:], sr.moduleHandler.LoadedModule[i+1:])
  432. sr.moduleHandler.LoadedModule = sr.moduleHandler.LoadedModule[:len(sr.moduleHandler.LoadedModule)-1]
  433. }
  434. return nil
  435. }
  436. func (sr *SubServiceRouter) StartSubService(serviceDir string) error {
  437. if fileExists("subservice/" + serviceDir) {
  438. err := sr.Launch("subservice/"+serviceDir, false)
  439. if err != nil {
  440. return err
  441. }
  442. } else {
  443. return errors.New("Subservice directory not exists.")
  444. }
  445. //Sort the list
  446. sort.Slice(sr.moduleHandler.LoadedModule, func(i, j int) bool {
  447. return sr.moduleHandler.LoadedModule[i].Name < sr.moduleHandler.LoadedModule[j].Name
  448. })
  449. sort.Slice(sr.RunningSubService, func(i, j int) bool {
  450. return sr.RunningSubService[i].Info.Name < sr.RunningSubService[j].Info.Name
  451. })
  452. return nil
  453. }
  454. //Get a list of subservice roots in realpath
  455. func (sr *SubServiceRouter) GetSubserviceRoot() []string {
  456. subserviceRoots := []string{}
  457. for _, subService := range sr.RunningSubService {
  458. subserviceRoots = append(subserviceRoots, subService.Path)
  459. }
  460. return subserviceRoots
  461. }
  462. //Scan and get the next avaible port for subservice from its basePort
  463. func (sr *SubServiceRouter) GetNextUsablePort() int {
  464. basePort := sr.BasePort
  465. for sr.CheckIfPortInUse(basePort) {
  466. basePort++
  467. }
  468. return basePort
  469. }
  470. func (sr *SubServiceRouter) CheckIfPortInUse(port int) bool {
  471. for _, service := range sr.RunningSubService {
  472. if service.Port == port {
  473. return true
  474. }
  475. }
  476. return false
  477. }
  478. func (sr *SubServiceRouter) HandleRoutingRequest(w http.ResponseWriter, r *http.Request, proxy *reverseproxy.ReverseProxy, subserviceObject *SubService, rewriteURL string) {
  479. u, _ := sr.userHandler.GetUserInfoFromRequest(w, r)
  480. if !sr.CheckUserPermissionOnSubservice(subserviceObject, u) {
  481. //Permission denied
  482. http.NotFound(w, r)
  483. return
  484. }
  485. //Perform reverse proxy serving
  486. r.URL, _ = url.Parse(rewriteURL)
  487. token, _ := sr.userHandler.GetAuthAgent().NewTokenFromRequest(w, r)
  488. r.Header.Set("aouser", u.Username)
  489. r.Header.Set("aotoken", token)
  490. r.Header.Set("X-Forwarded-Host", r.Host)
  491. if r.Header["Upgrade"] != nil && r.Header["Upgrade"][0] == "websocket" {
  492. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  493. r.Header.Set("A-Upgrade", "websocket")
  494. u, _ := url.Parse("ws://localhost:" + strconv.Itoa(subserviceObject.Port) + r.URL.String())
  495. wspHandler := websocketproxy.NewProxy(u)
  496. wspHandler.ServeHTTP(w, r)
  497. return
  498. }
  499. r.Host = r.URL.Host
  500. err := proxy.ServeHTTP(w, r)
  501. if err != nil {
  502. //Check if it is cancelling events.
  503. if !strings.Contains(err.Error(), "cancel") {
  504. log.Println(subserviceObject.Info.Name + " IS NOT RESPONDING!")
  505. sr.RestartSubService(subserviceObject)
  506. }
  507. }
  508. }
  509. //Handle fail start over when the remote target is not responding
  510. func (sr *SubServiceRouter) RestartSubService(ss *SubService) {
  511. go func(ss *SubService) {
  512. //Kill the original subservice
  513. sr.KillSubService(ss.ServiceDir)
  514. log.Println("RESTARTING SUBSERVICE " + ss.Info.Name + " IN 10 SECOUNDS")
  515. time.Sleep(10000 * time.Millisecond)
  516. sr.StartSubService(ss.ServiceDir)
  517. log.Println("SUBSERVICE " + ss.Info.Name + " RESTARTED")
  518. }(ss)
  519. }