Browse Source

Added list log API

Toby Chui 2 năm trước cách đây
mục cha
commit
aada156457
5 tập tin đã thay đổi với 142 bổ sung17 xóa
  1. 1 1
      auth.go
  2. 4 4
      console.go
  3. 10 11
      desktop.go
  4. 117 0
      mod/info/logviewer/logviewer.go
  5. 10 1
      system.info.go

+ 1 - 1
auth.go

@@ -33,7 +33,7 @@ func AuthInit() {
 	authAgent = auth.NewAuthenticationAgent("ao_auth", []byte(*session_key), sysdb, *allow_public_registry, func(w http.ResponseWriter, r *http.Request) {
 		//Login Redirection Handler, redirect it login.system
 		w.Header().Set("Cache-Control", "no-cache, no-store, no-transform, must-revalidate, private, max-age=0")
-		http.Redirect(w, r, utils.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect="+r.URL.Path, 307)
+		http.Redirect(w, r, utils.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect="+r.URL.Path, http.StatusTemporaryRedirect)
 	})
 
 	if *allow_autologin {

+ 4 - 4
console.go

@@ -4,13 +4,13 @@ import (
 	"encoding/json"
 	"errors"
 	"fmt"
-	"io/ioutil"
+	"os"
 	"strings"
 
 	"imuslab.com/arozos/mod/utils"
 )
 
-//Handle console command from the console module
+// Handle console command from the console module
 func consoleCommandHandler(input string) string {
 	//chunk := strings.Split(input, " ");
 	chunk, err := parseCommandLine(input)
@@ -24,7 +24,7 @@ func consoleCommandHandler(input string) string {
 			filename := chunk[2]
 			fmt.Println("Dumping user list to " + filename + " csv file")
 			csv := authAgent.ExportUserListAsCSV()
-			err := ioutil.WriteFile(filename, []byte(csv), 0755)
+			err := os.WriteFile(filename, []byte(csv), 0755)
 			if err != nil {
 				return err.Error()
 			}
@@ -211,7 +211,7 @@ func consoleCommandHandler(input string) string {
 	return "Invalid Command. Given: '" + strings.Join(chunk, " ") + "'"
 }
 
-//Check if the given line input match the requirement
+// Check if the given line input match the requirement
 func matchSubfix(chunk []string, match []string, minlength int, usageExample string) bool {
 	matching := true
 	//Check if the chunk contains minmium length of the command request

+ 10 - 11
desktop.go

@@ -3,7 +3,6 @@ package main
 import (
 	"encoding/json"
 	"errors"
-	"io/ioutil"
 	"log"
 	"net/http"
 	"os"
@@ -19,7 +18,7 @@ import (
 	"imuslab.com/arozos/mod/utils"
 )
 
-//Desktop script initiation
+// Desktop script initiation
 func DesktopInit() {
 	systemWideLogger.PrintAndLog("Desktop", "Starting Desktop Services", nil)
 
@@ -67,9 +66,9 @@ func DesktopInit() {
 }
 
 /*
-	FUNCTIONS RELATED TO PARSING DESKTOP FILE ICONS
+FUNCTIONS RELATED TO PARSING DESKTOP FILE ICONS
 
-	The functions in this section handle file listing and its icon locations.
+The functions in this section handle file listing and its icon locations.
 */
 func desktop_initUserFolderStructure(username string) {
 	//Call to filesystem for creating user file struture at root dir
@@ -88,15 +87,15 @@ func desktop_initUserFolderStructure(username string) {
 		if fs.FileExists(templateFolder) {
 			templateFiles, _ := filepath.Glob(templateFolder + "*")
 			for _, tfile := range templateFiles {
-				input, _ := ioutil.ReadFile(tfile)
-				ioutil.WriteFile(homedir+"Desktop/"+filepath.Base(tfile), input, 0755)
+				input, _ := os.ReadFile(tfile)
+				os.WriteFile(homedir+"Desktop/"+filepath.Base(tfile), input, 0755)
 			}
 		}
 	}
 
 }
 
-//Return the information about the host
+// Return the information about the host
 func desktop_hostdetailHandler(w http.ResponseWriter, r *http.Request) {
 	type returnStruct struct {
 		Hostname        string
@@ -294,7 +293,7 @@ func desktop_listFiles(w http.ResponseWriter, r *http.Request) {
 	utils.SendJSONResponse(w, string(jsonString))
 }
 
-//functions to handle desktop icon locations. Location is directly written into the center db.
+// functions to handle desktop icon locations. Location is directly written into the center db.
 func getDesktopLocatioFromPath(filename string, username string) (int, int, error) {
 	//As path include username, there is no different if there are username in the key
 	locationdata := ""
@@ -316,7 +315,7 @@ func getDesktopLocatioFromPath(filename string, username string) (int, int, erro
 	return thisFileLocation.X, thisFileLocation.Y, nil
 }
 
-//Set the icon location of a given filepath
+// Set the icon location of a given filepath
 func setDesktopLocationFromPath(filename string, username string, x int, y int) error {
 	//You cannot directly set path of others people's deskop. Hence, fullpath needed to be parsed from auth username
 	userinfo, _ := userHandler.GetUserInfoFromUsername(username)
@@ -356,7 +355,7 @@ func delDesktopLocationFromPath(filename string, username string) {
 	sysdb.Delete("desktop", username+"/filelocation/"+filename)
 }
 
-//Return the user information to the client
+// Return the user information to the client
 func desktop_handleUserInfo(w http.ResponseWriter, r *http.Request) {
 	userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
 	if err != nil {
@@ -404,7 +403,7 @@ func desktop_handleUserInfo(w http.ResponseWriter, r *http.Request) {
 	utils.SendJSONResponse(w, string(jsonString))
 }
 
-//Icon handling function for web endpoint
+// Icon handling function for web endpoint
 func desktop_fileLocation_handler(w http.ResponseWriter, r *http.Request) {
 	get, _ := utils.Mv(r, "get", true) //Check if there are get request for a given filepath
 	set, _ := utils.Mv(r, "set", true) //Check if there are any set request for a given filepath

+ 117 - 0
mod/info/logviewer/logviewer.go

@@ -0,0 +1,117 @@
+package logviewer
+
+import (
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io/fs"
+	"net/http"
+	"os"
+	"path/filepath"
+	"strings"
+
+	"imuslab.com/arozos/mod/filesystem/arozfs"
+	"imuslab.com/arozos/mod/utils"
+)
+
+type ViewerOption struct {
+	RootFolder string //The root folder to scan for log
+	Extension  string //The extension the root files use, include the . in your ext (e.g. .log)
+}
+
+type Viewer struct {
+	option *ViewerOption
+}
+
+type LogFile struct {
+	Title    string
+	Filename string
+	Fullpath string
+}
+
+func NewLogViewer(option *ViewerOption) *Viewer {
+	return &Viewer{option: option}
+}
+
+/*
+	Log Request Handlers
+*/
+//List all the log files in the log folder. Return in map[string]LogFile format
+func (v *Viewer) HandleListLog(w http.ResponseWriter, r *http.Request) {
+	logFiles := v.ListLogFiles(false)
+	fmt.Println(logFiles)
+	js, _ := json.Marshal(logFiles)
+	utils.SendJSONResponse(w, string(js))
+}
+
+// Read log of a given catergory and filename
+func (v *Viewer) HandleReadLog(w http.ResponseWriter, r *http.Request) {
+	filename, err := utils.Mv(r, "file", false)
+	if err != nil {
+		utils.SendErrorResponse(w, "invalid filename given")
+		return
+	}
+
+	catergory, err := utils.Mv(r, "catergory", false)
+	if err != nil {
+		utils.SendErrorResponse(w, "invalid catergory given")
+		return
+	}
+
+	content, err := v.LoadLogFile(strings.TrimSpace(filepath.Base(catergory)), strings.TrimSpace(filepath.Base(filename)))
+	if err != nil {
+		utils.SendErrorResponse(w, err.Error())
+		return
+	}
+
+	utils.SendTextResponse(w, content)
+}
+
+/*
+	Log Access Functions
+*/
+
+func (v *Viewer) ListLogFiles(showFullpath bool) map[string][]*LogFile {
+	result := map[string][]*LogFile{}
+	filepath.WalkDir(v.option.RootFolder, func(path string, di fs.DirEntry, err error) error {
+		if filepath.Ext(path) == v.option.Extension {
+			catergory := filepath.Base(filepath.Dir(path))
+			logList, ok := result[catergory]
+			if !ok {
+				//this catergory hasn't been scanned before.
+				logList = []*LogFile{}
+			}
+
+			fullpath := arozfs.ToSlash(path)
+			if !showFullpath {
+				fullpath = ""
+			}
+
+			logList = append(logList, &LogFile{
+				Title:    strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)),
+				Filename: filepath.Base(path),
+				Fullpath: fullpath,
+			})
+
+			result[catergory] = logList
+		}
+
+		return nil
+	})
+	return result
+}
+
+func (v *Viewer) LoadLogFile(catergory string, filename string) (string, error) {
+	logFilepath := filepath.Join(v.option.RootFolder, catergory, filename)
+	if utils.FileExists(logFilepath) {
+		//Load it
+		content, err := os.ReadFile(logFilepath)
+		if err != nil {
+			return "", err
+		}
+
+		return string(content), nil
+	} else {
+		return "", errors.New("log file not found")
+	}
+}

+ 10 - 1
system.info.go

@@ -7,13 +7,14 @@ import (
 	"time"
 
 	info "imuslab.com/arozos/mod/info/hardwareinfo"
+	"imuslab.com/arozos/mod/info/logviewer"
 	usage "imuslab.com/arozos/mod/info/usageinfo"
 	prout "imuslab.com/arozos/mod/prouter"
 	"imuslab.com/arozos/mod/updates"
 	"imuslab.com/arozos/mod/utils"
 )
 
-//InitShowSysInformation xxx
+// InitShowSysInformation xxx
 func SystemInfoInit() {
 	systemWideLogger.PrintAndLog("System", "Operation System: "+runtime.GOOS, nil)
 	systemWideLogger.PrintAndLog("System", "System Architecture: "+runtime.GOARCH, nil)
@@ -164,6 +165,14 @@ func SystemInfoInit() {
 		}
 	}()
 
+	//Log Viewer, so developers can debug inside arozos
+	logViewer := logviewer.NewLogViewer(&logviewer.ViewerOption{
+		RootFolder: "system/logs/",
+		Extension:  ".log",
+	})
+
+	adminRouter.HandleFunc("/system/log/list", logViewer.HandleListLog)
+	adminRouter.HandleFunc("/system/log/read", logViewer.HandleReadLog)
 }
 
 func InfoHandleGetRuntimeInfo(w http.ResponseWriter, r *http.Request) {