func GetServerState(address string) int { result := common.SERVER_STATE_OFFLINE req, err1 := http.NewRequest("GET", address, nil) if nil != err1 { log.WriteLog("errror %v", err1) return result } httpClient := http.Client{ Transport: &http.Transport{ Dial: func(netw, addr string) (net.Conn, error) { deadline := time.Now().Add(SERVER_STATE_CHECK_INTERVAL_SEC * time.Second) c, err := net.DialTimeout(netw, addr, time.Second*SERVER_STATE_CHECK_INTERVAL_SEC) if err != nil { return nil, err } c.SetDeadline(deadline) return c, nil }, }, } resp, err := httpClient.Do(req) if err != nil { log.WriteLog("errror %v", err) return result } // 保证I/O正常关闭 defer resp.Body.Close() // 判断返回状态 if resp.StatusCode == http.StatusOK { result = common.SERVER_STATE_ONLINE } return result }
func (setupInfoServiceXmlImpl *setupInfoServiceXmlImpl) SaveSetupInfo(setupInfo interface{}, fileName string, encoding string) error { fout, err := os.Create(fileName) if nil != err { log.WriteLog("error: %v", err) return err } defer fout.Close() if nil == setupInfo { log.WriteLog("没有配置对象") return err } output, err := xml.MarshalIndent(setupInfo, " ", " ") if nil != err { log.WriteLog("error: %v\n", err) return err } head := `<?xml version="1.0" ` if !utils.IsEmptyStr(encoding) { head = head + "encoding=\"" + encoding + "\"" } head = head + "?>\n" fout.Write([]byte(head)) if nil != setupInfoServiceXmlImpl.saveXMLContentBefore { err = setupInfoServiceXmlImpl.saveXMLContentBefore.saveContentBefore(setupInfo, fout) if nil != err { return err } } fout.Write(output) return nil }
func (routeUserDelete *RouteUserDelete) Routes(m *martini.ClassicMartini) { m.Post("/user/delete", func(w http.ResponseWriter, r *http.Request) string { log.WriteLog("addr: /user/delete") SetResponseJsonHeader(w) setupInfo := model.SetupInfo{} setupHandle := model.NewSetupHandle() if !setupHandle.GetSetupInfo(&setupInfo) { return model.GetErrorDtoJson("读取用户信息失败") } r.ParseForm() log.WriteLog("user delete %v", r.Form) userName := r.Form.Get("username") if common.USER_NAME_ADMIN == userName { log.WriteLog("删除admin失败") return model.GetErrorDtoJson("删除管理员信息失败") } if !setupInfo.DeleteUserByUserName(userName) { log.WriteLog("删除用户信息失败") return model.GetErrorDtoJson("删除用户信息失败") } if !setupHandle.SaveSetupInfo(&setupInfo) { log.WriteLog("保存删除用户信息失败") return model.GetErrorDtoJson("保存删除用户信息失败") } return model.GetDataDtoJson(nil) }) }
func (setupInfoServiceXmlImpl *setupInfoServiceXmlImpl) GetSetupInfo(setupInfo interface{}, fileName string) error { file, err := os.Open(fileName) // For read access. if nil != err { log.WriteLog("error: %v", err) return err } defer file.Close() data, err := ioutil.ReadAll(file) if nil != err { log.WriteLog("error: %v", err) return err } if nil == setupInfo { log.WriteLog("没有配置对象") return err } decoder := xml.NewDecoder(bytes.NewBuffer(data)) decoder.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) { if charset != common.XML_ENCODE_GB2312 && charset != "GB2312" { return input, errors.New("xml: encoding gb2312 is not declared") } return input, nil } err = decoder.Decode(setupInfo) if nil != err { log.WriteLog("error: %v", err) return err } return nil }
func (getListenPortInfoLinux *GetListenPortInfoLinux) GetInfo() ([]int64, error) { osErr := getLinuxOSError() if nil != osErr { return []int64{}, osErr } bs, err := utils.CmdOutputBytes("ss", "-n", "-l") if nil != err { return []int64{}, err } reader := bufio.NewReader(bytes.NewBuffer(bs)) // ignore the first line var line []byte line, _, err = reader.ReadLine() if err == io.EOF || nil != err { return []int64{}, err } ret := []int64{} for { line, _, err = reader.ReadLine() if err == io.EOF || nil != err { break } arr := strings.Fields(string(line)) arrlen := len(arr) if arrlen != 4 && arrlen != 5 { log.WriteLog("output of [ss -n -l] format error") continue } ci := 2 if arrlen == 5 { ci = 3 } location := strings.LastIndex(arr[ci], ":") port := arr[ci][location+1:] if p, e := strconv.ParseInt(port, 10, 64); e != nil { log.WriteLog("parse port to int64 fail: %s", e) continue } else { ret = append(ret, p) } } ret = utils.SliceUniqueInt64(ret) return ret, nil }
func (routeUserSave *RouteUserSave) Routes(m *martini.ClassicMartini) { m.Post("/user/save", func(w http.ResponseWriter, r *http.Request) string { log.WriteLog("addr: /user/save") SetResponseJsonHeader(w) setupInfo := model.SetupInfo{} setupHandle := model.NewSetupHandle() if !setupHandle.GetSetupInfo(&setupInfo) { return model.GetErrorDtoJson("读取用户信息失败") } r.ParseForm() log.WriteLog("user save %v", r.Form) ousername := r.Form.Get("ousername") username := r.Form.Get("username") addFlag := utils.IsEmptyStr(ousername) password := r.Form.Get("password") if utils.IsEmptyStr(username) { return model.GetErrorDtoJson("没有用户名称") } if utils.IsEmptyStr(password) { return model.GetErrorDtoJson("没有密码") } index := setupInfo.GetUserIndexByUserName(username) oindex := setupInfo.GetUserIndexByUserName(ousername) var pUserInfo *model.UserInfo = nil if addFlag { if index > -1 { return model.GetErrorDtoJson("用户名称输入重复") } userInfo := model.UserInfo{UserName: username, Password: password} setupInfo.AddUserInfo(userInfo) pUserInfo = &userInfo } else { if oindex < 0 { return model.GetErrorDtoJson("没有找到用户") } else { if index > -1 && oindex != index { return model.GetErrorDtoJson("用户名称输入重复") } } setupInfo.Users[oindex].UserName = username setupInfo.Users[oindex].Password = password pUserInfo = &setupInfo.Users[oindex] } if !setupHandle.SaveSetupInfo(&setupInfo) { log.WriteLog("保存删除用户信息失败") return model.GetErrorDtoJson("保存删除用信息失败") } return model.GetDataDtoJson(model.UserSaveInfo{UserInfo: *pUserInfo, OUserName: ousername, AddFlag: addFlag}) }) }
func (setupInfo *SetupInfo) DeleteUserByUserName(userName string) bool { if nil == setupInfo { log.WriteLog("没有配置对象") return false } index := setupInfo.GetUserIndexByUserName(userName) if index < 0 { log.WriteLog("通过名称%s找不到用户对象", userName) return false } users := setupInfo.Users[0:index] setupInfo.Users = append(users, setupInfo.Users[index+1:len(setupInfo.Users)]...) return true }
func (setupInfo *SetupInfo) DeleteServerByServerName(serverName string) bool { if nil == setupInfo { log.WriteLog("没有配置对象") return false } index := setupInfo.GetServerIndexByServerName(serverName) if index < 0 { log.WriteLog("通过名称%s找不到服务器对象", serverName) return false } servers := setupInfo.Servers[0:index] setupInfo.Servers = append(servers, setupInfo.Servers[index+1:len(setupInfo.Servers)]...) return true }
func StartHttp(routeHandle model.RouteHandle) { checkEnv() port := 9500 setupInfo := &model.SetupInfo{} if model.NewSetupHandle().GetSetupInfo(setupInfo) { if setupInfo.Port > 0 { port = setupInfo.Port } } m := martini.Classic() m.Use(render.Renderer(render.Options{ Funcs: []template.FuncMap{{ "pageStartIndex": getPageStartIndex, "pageEndIndex": getPageEndIndex, "pageIndexHtml": getPageIndexHtml, "serverType": getServerType, }}, })) routeHandle.Routes(m) error := http.ListenAndServe(":"+strconv.Itoa(port), m) if nil != error { log.WriteLog("start http %d failed %s", port, error.Error()) } }
func (routeServerGeneralInfo *RouteServerGeneralInfo) Routes(m *martini.ClassicMartini) { m.Get("/server/info/general", func(w http.ResponseWriter, r *http.Request) string { log.WriteLog("addr: /server/info/general") shttp.SetResponseJsonHeader(w) result := map[string]string{} val, err := service.NewGetSystemTimeInfo().GetInfo() if nil != err { return model.GetErrorObjDtoJson(err) } result["time"] = val runTimeInfo, err1 := service.NewGetSystemRunTimeInfo().GetInfo() if nil != err1 { return model.GetErrorObjDtoJson(err1) } result["runtime"] = fmt.Sprintf("%d天 %d小时 %d分钟", runTimeInfo.Day, runTimeInfo.Hour, runTimeInfo.Min) hostname, err3 := os.Hostname() if nil != err3 { return model.GetErrorObjDtoJson(err3) } result["hostname"] = hostname ver, err2 := utils.CmdOutputNoLn("uname", "-r") if nil != err2 { return model.GetErrorObjDtoJson(err2) } result["kernel"] = ver return model.GetDataDtoJson(result) }) }
func (getAllProcessInfoLinux *GetAllProcessInfoLinux) getCpuMemRate(processInfo *model.ProcessInfo) error { bs, err := utils.CmdOutputBytes("ps", "aux") if nil != err { return err } reader := bufio.NewReader(bytes.NewBuffer(bs)) var line []byte line, _, err = reader.ReadLine() if err == io.EOF || nil != err { return errors.New("ps no content") } var pid int for { line, _, err = reader.ReadLine() if err == io.EOF || nil != err { break } arr := strings.Fields(string(line)) arrlen := len(arr) if arrlen < 7 { log.WriteLog("output of [ps aux] format error") continue } pid, err = strconv.Atoi(arr[1]) if nil != err { log.WriteLog("err %v", err) continue } if pid == processInfo.Id { processInfo.CPURate, err = strconv.ParseFloat(arr[2], 32) if nil != err { return err } processInfo.MemRate, err = strconv.ParseFloat(arr[3], 32) if nil != err { return err } } } return nil }
func (getAllProcessInfoLinux *GetAllProcessInfoLinux) GetInfo() ([]model.ProcessInfo, error) { result := []model.ProcessInfo{} dirs, err := utils.GetDirChildDirs("/proc") if nil != err { return result, err } // id dir is a number, it should be a pid. but don't trust it dirs_len := len(dirs) if dirs_len == 0 { return result, nil } var pid int for _, pidstr := range dirs { if pid, err = strconv.Atoi(pidstr); nil != err { err = nil continue } else { p := model.ProcessInfo{Id: pid} err = getAllProcessInfoLinux.getCmdLine(&p) if nil != err { log.WriteLog("read %s fail: %s", fmt.Sprintf("/proc/%d/cmdline", p.Id), err) continue } err = getAllProcessInfoLinux.getProcStatus(&p) if nil != err { log.WriteLog("read %s fail: %s", fmt.Sprintf("/proc/%d/status", p.Id), err) continue } err = getAllProcessInfoLinux.getCpuMemRate(&p) if nil != err { log.WriteLog("read mem: %s", err) continue } err = getAllProcessInfoLinux.getRealPath(&p) if nil != err { continue } result = append(result, p) } } return result, nil }
func logOut(w http.ResponseWriter, r *http.Request, re render.Render) { log.WriteLog("addr: /logout") userInfo := shttp.GetSessionUserInfo(w, r) retInfos := getStrMapRetInfo() if nil != userInfo { userInfo.Logout() retInfos["userName"] = userInfo.UserName } re.HTML(200, "login", retInfos) }
func (executeLinuxProcForkChildImpl *executeLinuxProcForkChildImpl) Exec(cmdLine string, dir string) error { executeLinuxProc := executeLinuxProcStartProcessImpl{} pid, _, errno := syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0) if errno != 0 { return syscall.Errno(errno) } if pid > 0 { puid := int(pid) processInfo, _ := os.FindProcess(puid) if nil != processInfo { _, err := processInfo.Wait() if nil != err { log.WriteLog("Error: find process %s", err.Error()) } } return nil } else if pid < 0 { return errors.New("fork error") } // pid1, _, errno1 := syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0) // if errno1 != 0 { // os.Exit(0) // return errors.New("fork error") // } // if pid1 > 0 { // os.Exit(0) // return nil // } else if pid1 < 0 { // os.Exit(0) // return errors.New("fork error") // } _ = syscall.Umask(0) _, s_errno := syscall.Setsid() if s_errno != nil { log.WriteLog("Error: syscall.Setsid errno: %d", s_errno) } os.Chdir("/") result := executeLinuxProc.Exec(cmdLine, dir) os.Exit(0) return result }
func gotoLoginPage(w http.ResponseWriter, r *http.Request, re render.Render) { userInfo := shttp.GetSessionUserInfo(w, r) retInfos := getStrMapRetInfo() if nil == userInfo { log.WriteLog("not session user name") } else { retInfos["userName"] = userInfo.UserName } re.HTML(200, "login", retInfos) }
func (routeRoot *RouteRoot) Routes(m *martini.ClassicMartini) { m.Get("/", func(w http.ResponseWriter, r *http.Request, re render.Render) { log.WriteLog("addr: /") if !CheckSessionUserLogin(w, r) { gotoLoginPage(w, r, re) } else { gotoRootPage(re, GetSessionUserInfo(w, r)) } }) }
func gotoLoginPage(w http.ResponseWriter, r *http.Request, re render.Render) { userInfo := GetSessionUserInfo(w, r) if nil == userInfo { log.WriteLog("not session user name") re.HTML(200, "login", nil) } else { retInfos := make(map[string]string) retInfos["userName"] = userInfo.UserName re.HTML(200, "login", retInfos) } }
func (routeServerNetCardInfo *RouteServerNetCardInfo) Routes(m *martini.ClassicMartini) { m.Get("/server/info/netcard", func(w http.ResponseWriter, r *http.Request) string { log.WriteLog("addr: /server/info/netcard") shttp.SetResponseJsonHeader(w) result, err := service.NewGetNetStatisticsInfo().GetInfo() if nil != err { return model.GetErrorObjDtoJson(err) } return model.GetDataDtoJson(result) }) }
func (routeServerConfigSave *routeServerConfigSave) Routes(m *martini.ClassicMartini) { m.Post("/server/saveconfig", func(w http.ResponseWriter, r *http.Request, re render.Render) string { log.WriteLog("addr: /server/saveconfig") shttp.SetResponseJsonHeader(w) r.ParseForm() err := service.NewServerConfigSaveRequestHandle().Save(r) if nil != err { return model.GetErrorObjDtoJson(err) } return model.GetDataDtoJson("") }) }
func (routeServerMemInfo *RouteServerMemInfo) Routes(m *martini.ClassicMartini) { m.Get("/server/info/mem", func(w http.ResponseWriter, r *http.Request) string { log.WriteLog("addr: /server/info/mem") shttp.SetResponseJsonHeader(w) mem, err := service.NewGetMemInfo().GetInfo() if nil != err { return model.GetErrorObjDtoJson(err) } memFree := mem.MemFree + mem.Buffers + mem.Cached memUsed := mem.MemTotal - memFree return model.GetDataDtoJson([]interface{}{mem.MemTotal, memUsed, memFree}) }) }
func (routeServerList *RouteServerList) Routes(m *martini.ClassicMartini) { m.Get("/serverList", func(w http.ResponseWriter, r *http.Request, re render.Render) { log.WriteLog("addr: /serverList") serverName := getUniqueServerName() if utils.IsEmptyStr(serverName) { routeServerList.routeMoreServer(r, re) } else { gotoServerInfo(w, r, re) } }) }
func (routeServerDelete *RouteServerDelete) Routes(m *martini.ClassicMartini) { m.Post("/server/delete", func(w http.ResponseWriter, r *http.Request) string { log.WriteLog("addr: /server/delete") SetResponseJsonHeader(w) setupInfo := model.SetupInfo{} setupHandle := model.NewSetupHandle() if !setupHandle.GetSetupInfo(&setupInfo) { return model.GetErrorDtoJson("读取服务器信息失败") } r.ParseForm() log.WriteLog("server delete %v", r.Form) serverName := r.Form.Get("servername") if !setupInfo.DeleteServerByServerName(serverName) { log.WriteLog("删除服务器信息失败") return model.GetErrorDtoJson("删除服务器信息失败") } if !setupHandle.SaveSetupInfo(&setupInfo) { log.WriteLog("保存删除服务器信息失败") return model.GetErrorDtoJson("保存删除服务器信息失败") } return model.GetDataDtoJson(nil) }) }
func (routeServerConfigRoot *routeServerConfigRoot) Routes(m *martini.ClassicMartini) { m.Get("/serverconfig", func(w http.ResponseWriter, r *http.Request, re render.Render) string { log.WriteLog("addr: /serverconfig") shttp.SetResponseJsonHeader(w) r.ParseForm() serverName := r.FormValue("servername") if utils.IsEmptyStr(serverName) { return model.GetErrorDtoJson("没有服务器名称") } serverInfo, serverSetupInfo, err := service.NewGetServerSetupInfo().GetInfo(serverName) if nil != err { return model.GetErrorObjDtoJson(err) } return model.GetDataDtoJson([]interface{}{serverInfo, serverSetupInfo}) }) }
func (routeServerList *RouteServerList) Routes(m *martini.ClassicMartini) { m.Get("/serverList", func(w http.ResponseWriter, r *http.Request, re render.Render) { log.WriteLog("addr: /serverList") r.ParseForm() startPage, err := strconv.Atoi(r.FormValue("pageNo")) if nil != err { startPage = 0 } serverPageInfo := model.NewServerPageHandle().GetServerPageInfo(startPage, 10) for index, _ := range serverPageInfo.Servers { serverPageInfo.Servers[index].Status = utils.GetServerState(serverPageInfo.Servers[index].Address) } re.HTML(200, "serverList", serverPageInfo) }) }
func gotoServerInfo(w http.ResponseWriter, r *http.Request, re render.Render) { log.WriteLog("addr: /serverinfo") if !shttp.CheckSessionUserLogin(w, r) { gotoLoginPage(w, r, re) return } r.ParseForm() servername := r.FormValue("servername") if utils.IsEmptyStr(servername) { servername = getFirstServerName() } retInfos := make(map[string]string) retInfos["serverName"] = servername if utils.IsEmptyStr(servername) { retInfos["errorInfo"] = "没有服务器" } re.HTML(200, "serverInfo", retInfos) }
func (routeServerProcessInfo *RouteServerProcessInfo) Routes(m *martini.ClassicMartini) { m.Get("/server/info/process", func(w http.ResponseWriter, r *http.Request) string { log.WriteLog("addr: /server/info/process") shttp.SetResponseJsonHeader(w) r.ParseForm() serverName := r.FormValue("servername") if utils.IsEmptyStr(serverName) { return model.GetErrorDtoJson("没有服务器名称") } serverProcessInfo, err := service.NewGetServerProcessInfo().GetInfo(serverName) if nil != err { return model.GetErrorObjDtoJson(err) } result := map[string]string{} result["cpuRate"] = fmt.Sprintf("%.1f%%", serverProcessInfo.CPURate) result["memRate"] = fmt.Sprintf("%.1f%%", serverProcessInfo.MemRate) result["realMem"] = fmt.Sprintf("%s", utils.DisplaySizeStr(float64(serverProcessInfo.MemRealSize))) result["virtualMem"] = fmt.Sprintf("%s", utils.DisplaySizeStr(float64(serverProcessInfo.MemVmSize))) result["state"] = serverProcessInfo.State return model.GetDataDtoJson(result) }) }
func (routeServerSave *RouteServerSave) Routes(m *martini.ClassicMartini) { m.Post("/server/save", func(w http.ResponseWriter, r *http.Request) string { log.WriteLog("addr: /server/save") SetResponseJsonHeader(w) setupInfo := model.SetupInfo{} setupHandle := model.NewSetupHandle() if !setupHandle.GetSetupInfo(&setupInfo) { return model.GetErrorDtoJson("读取服务器信息失败") } r.ParseForm() log.WriteLog("server save %v", r.Form) oservername := r.Form.Get("oservername") servername := r.Form.Get("servername") addFlag := utils.IsEmptyStr(oservername) address := r.Form.Get("address") iType, err := strconv.Atoi(r.FormValue("servertype")) if nil != err { log.WriteLog("error: %v", err) iType = common.SERVER_TYPE_CMS } if utils.IsEmptyStr(servername) { return model.GetErrorDtoJson("没有服务器名称") } if utils.IsEmptyStr(address) { return model.GetErrorDtoJson("没有服务器地址") } index := setupInfo.GetServerIndexByServerName(servername) oindex := setupInfo.GetServerIndexByServerName(oservername) var pServerInfo *model.ServerInfo = nil if addFlag { if index > -1 { return model.GetErrorDtoJson("服务器名称输入重复") } serverInfo := model.ServerInfo{ServerName: servername, Address: address, Type: iType} setupInfo.AddServerInfo(serverInfo) pServerInfo = &serverInfo } else { if oindex < 0 { return model.GetErrorDtoJson("没有找到服务器") } else { if index > -1 && oindex != index { return model.GetErrorDtoJson("服务器名称输入重复") } } setupInfo.Servers[oindex].ServerName = servername setupInfo.Servers[oindex].Address = address setupInfo.Servers[oindex].Type = iType pServerInfo = &setupInfo.Servers[oindex] } if nil != routeServerSave.CheckServerSave { err := routeServerSave.CheckServerSave.CheckServerSave(oservername, pServerInfo) if nil != err { return model.GetErrorObjDtoJson(err) } } if !setupHandle.SaveSetupInfo(&setupInfo) { log.WriteLog("保存删除服务器信息失败") return model.GetErrorDtoJson("保存删除服务器信息失败") } return model.GetDataDtoJson(model.ServerSaveInfo{ServerInfo: *pServerInfo, OServerName: oservername, AddFlag: addFlag}) }) }