func checkTimer(cmd *exec.Cmd, comp *Compile, id int) { for { // if building process hava exit normally, exit timer if BuildProcessHaveExit { log.Blueln("Building Process Exit Normally.") return } stn := time.Now() now := stn.UnixNano() // over 10s if now-BuildStartTime > 10*1000000000 { comp.buildOverTime = true log.Warnln("Building Out of Time, Terminated!") cmd.Process.Kill() systemTag := com.SubString(runtime.GOOS, 0, 5) if systemTag == "linux" { // ps -ef|grep cc1|grep 5.c|awk '{print $2}'|xargs kill -9 cleanScript := fmt.Sprintf("ps -ef|grep cc1|grep %d.c|awk '{print $2}'|xargs kill -9", id) cleanCmd := exec.Command("sh", "-c", cleanScript, ) err := cleanCmd.Run() if err != nil { log.Warnln("clean orphan failed") } } return } } }
// run before get func (this *AdminBaseController) Prepare() { // login status user := this.GetSession("username") if user == nil { this.Redirect("/login", 302) } else { // find user id username := user.(string) u, err := models.FindUser(username) if err != nil { log.Warnln(err) } else { userLog := &models.UserLog{} // get ip ipPort := this.Ctx.Request.Header.Get("X-Forwarded-For") ipPortArr := strings.Split(ipPort, ":") ip := ipPortArr[0] // get location location := "" userLogIp, err := userLog.GetUserLogByIp(ip) if err == nil { locationData, err := com.JsonDecode(userLog.Location) if err == nil { locationJson := locationData.(map[string]interface{}) if userLog.IsValidLocation(locationJson) { location = userLogIp.Location } else { location, _ = utils.GetLocation(ip) } } else { location, _ = utils.GetLocation(ip) } } else { location, _ = utils.GetLocation(ip) } // get user agent ua := this.Ctx.Request.UserAgent() // save data _, err = userLog.AddUserlog(int64(u.Id), ip, ua, location, 0) if err != nil { log.Warnln(err) } } } this.Data["isAdmin"] = true this.Data["inDev"] = beego.AppConfig.String("runmode") == "dev" }
func InitCron() { if beego.AppConfig.String("runmode") == "prod" { tk := toolbox.NewTask("statistic", "0 0 * * * *", githubStat) err := tk.Run() if err != nil { log.Warnln("[Run Task Failed]") log.Warnln(err) } toolbox.AddTask("statistic", tk) toolbox.StartTask() defer toolbox.StopTask() } }
func InitCron() { tk := toolbox.NewTask("judger", "0/30 * * * * *", task.CheckJudger) if beego.AppConfig.String("runmode") == "dev" { err := tk.Run() if err != nil { log.Warnln("[Run Task Failed]") log.Warnln(err) } } toolbox.AddTask("judger", tk) toolbox.StartTask() }
// get top 10 problem func (this *Problem) GetTop10() ([]orm.Params, error) { sql := `SELECT problem.id as id, problem.title as title, count(*) AS count FROM submissions,problem where submissions.pid=problem.id GROUP BY pid ORDER BY count DESC limit 10` var maps []orm.Params o := orm.NewOrm() _, err := o.Raw(sql).Values(&maps) if err != nil { log.Warnln("execute sql error:") log.Warnln(err) return nil, err } else { return maps, err } }
func HandleJsonRpc(w http.ResponseWriter, r *http.Request) { // get request content p := make([]byte, r.ContentLength) r.Body.Read(p) content := string(p) log.Blueln(content) json, err := com.JsonDecode(content) if err != nil { log.Warnln("not json-rpc format") return } data := json.(map[string]interface{}) // get system password password := C.Get("", "password") // parse received password passwordRecv, ok := data["password"].(string) if !ok { result, _ := com.JsonEncode(map[string]interface{}{ "result": false, //bool, login result "msg": "invalid password, password must be string.", }) io.WriteString(w, result) return } // compare password if password != passwordRecv { result, _ := com.JsonEncode(map[string]interface{}{ "result": false, //bool, login failed }) io.WriteString(w, result) return } // trigger controller ctrl, exists := RouterMap[data["action"].(string)] if !exists { log.Warnln("not exist") return } ctrl.Http(data, w, r) }
// List Tags func (this *Tags) TagList() ([]orm.Params, error) { sql := "select * from tags order by time desc" var maps []orm.Params o := orm.NewOrm() _, err := o.Raw(sql).Values(&maps) if err != nil { log.Warnln("execute sql error:") log.Warnln(err) return nil, err } else { return maps, err } }
// call gcc compiler in other os func (this *Compile) gcc(id int) error { os.Chdir(this.itemBuildPath) var cmd *exec.Cmd log.Pinkln("cmd", "/K", this.compiler_c, this.codeFilePath, this.itemBuildPath, ) if runtime.GOOS == "windows" { cmd = exec.Command("cmd", "/K", this.compiler_c, this.codeFilePath, this.itemBuildPath, ) } else { cmd = exec.Command("sh", this.compiler_c, this.codeFilePath, this.itemBuildPath, ) } err := cmd.Start() if err != nil { log.Warnln("Start Failed") log.Warnln(err) } stn := time.Now() BuildStartTime = stn.UnixNano() go checkTimer(cmd, this, id) BuildProcessHaveExit = false err = cmd.Wait() BuildProcessHaveExit = true if err != nil { log.Warnln("Wait Failed") log.Warnln(err) } os.Chdir(this.currentPath) return err }
func GetCache(key string, to interface{}) error { if cc == nil { return errors.New("cc is nil") } defer func() { if r := recover(); r != nil { log.Redf("get cache error caught: %v\n", r) cc = nil } }() data := cc.Get(key) if data == nil { return errors.New("Cache不存在") } // log.Pinkln(data) err := Decode(data.([]byte), to) if err != nil { log.Warnln("获取Cache失败", key, err) } else { log.Greenln("获取Cache成功", key) } return err }
// start the session func (this *JClient) Start(ip string, port int, password string) error { // not login, first time this.login = false // default # to get the real sep this.mark = "#" addr := fmt.Sprintf("%s:%d", ip, port) conn, err := net.Dial("tcp", addr) if err != nil { if conn != nil { conn.Close() } log.Warnln("connect judge server failed in port:", port) return err } else { this.conn = conn this.connected = true content, err := this.read() if err != nil { return err } // get seperater mark reg := regexp.MustCompile(`/[\d\D]+$`) if arr := reg.FindAllString(content, -1); len(arr) > 0 { this.mark = com.SubString(arr[0], 1, 1) } log.Blueln(content) } // login loginRequest := map[string]interface{}{ "action": "login", "password": password, } response, err := this.Request(loginRequest) if err != nil { return err } result, ok := response["result"].(bool) if !result || !ok { return errors.New("login failed.") } sid, ok := response["sid"].(string) if ok { this.sid = sid } else { this.sid = "" } this.login = true return err }
func SetCache(key string, value interface{}, timeout int64) error { data, err := Encode(value) if err != nil { return err } if cc == nil { return errors.New("cc is nil") } defer func() { if r := recover(); r != nil { log.Redf("set cache error caught: %v\n", r) cc = nil } }() err = cc.Put(key, data, timeout) if err != nil { log.Warnln("Cache失败,key:", key) return err } else { log.Blueln("Cache成功,key:", key) return nil } }
func (this *AddArticleController) Post() { title := this.GetString("title") content := this.GetString("content") keywords := this.GetString("keywords") abstract := this.GetString("abstract") // if not login, permission deny user := this.GetSession("username") if user == nil { this.Data["json"] = map[string]interface{}{"result": false, "msg": "login first please", "refer": nil} this.ServeJson() return } if "" == title { this.Data["json"] = map[string]interface{}{"result": false, "msg": "title can not be empty", "refer": "/"} this.ServeJson() return } username := user.(string) id, err := AddArticle(title, content, keywords, abstract, username) if nil == err { this.Data["json"] = map[string]interface{}{"result": true, "msg": "success added, id " + fmt.Sprintf("[%d] ", id), "refer": nil} } else { log.Warnln(err) this.Data["json"] = map[string]interface{}{"result": false, "msg": "added failed", "refer": nil} } this.ServeJson() }
func (this *Compile) Run(code string, language string, id int, sid string) (string, error) { err := this.createDirs(id, sid) if err != nil { log.Warnln(err) return "", err } else { err = this.writeCode(code, id, language) if err != nil { log.Warnln(err) return "", err } } return this.itemBuildPath, this.gcc(id) }
// get avatar func (this *User) GetAvatar(id int, username string, email string, nickname string) (string, error) { user, err := this.GetUser(id, username, email, nickname) if nil == err { return beego.AppConfig.String("avatar") + com.Md5(user.Email), err } else { log.Warnln("GetAvatar Failed.", err) return "", err } }
func Get(name string) *client.JClient { jdg, ok := J[name].(*client.JClient) if !ok { log.Warnln("get failed") return nil } return jdg }
func CheckJudger() error { jdg := judger.Get("default") err := jdg.Ping() if err != nil { log.Warnln("reconnecting") reconnect() } return nil }
func Judger() { parseArg() dataPath := "data.db" if Mode == "docker" { log.Blueln("[mode]", "docker") if !com.FileExist("/data") { if err := com.Mkdir("/data"); err != nil { log.Warnln("[Warn]", "create dir /data failed") } else { log.Blueln("[info]", "create dir /data") } } if !com.FileExist("/data/config_docker.ini") { com.CopyFile("/data/config_docker.ini", "conf/config_docker.ini") } if !com.FileExist("/data/executer.json") { com.CopyFile("/data/executer.json", "sandbox/c/build/executer.json") } dataPath = "/data/data.db" } if configFile == "" { configFile = "conf/config.ini" } if !com.FileExist(configFile) { log.Dangerln("[Error]", configFile, "does not exist!") os.Exit(-1) } log.Blueln("[config]") log.Blueln(configFile) C = &Config{} C.NewConfig(configFile) GenScript() log.Blueln("[data]") log.Blueln(dataPath) DB = &Sqlite{} DB.NewSqlite(dataPath) createBuildDir() go TcpStart() HttpStart() }
func HttpStart() { http.HandleFunc("/", HandleJsonRpc) err := http.ListenAndServe(":1005", nil) if err != nil { log.Warnln("ListenAndServe: ", err) } else { log.Blueln("Http Server Started!") } }
func (this *Submissions) GetSubmissionStatus(id int) (string, error) { jdg := judger.Get("default") response, err := jdg.GetStatus(int64(id)) if err != nil { log.Warnln("send Request failed:", err) } info := response["info"].(map[string]interface{}) o := orm.NewOrm() var subm Submissions subm.Id = id err = o.Read(&subm, "Id") if err != nil { log.Warnf("记录[%d]不存在\n", id) return "", err } else { status := info["run_result"].(string) if status == "PEN" { subm.Status = "AC" } else if status == "PRE" { subm.Status = "RE" } else if status == "POM" { subm.Status = "MLE" } else if status == "POT" { subm.Status = "TLE" } else if status == "POL" { subm.Status = "OLE" } else if status == "PSF" { subm.Status = "PSF" } else if status == "EC" { subm.Status = "CE" } else { subm.Status = "UK" } subm.BuildLog = info["build_log"].(string) exe_debug, ok := info["executer_debug"].(string) if ok { subm.ExecuterDebug = exe_debug } o.Update(&subm) return subm.Status, err } }
// send request func (this *JClient) Request(msg map[string]interface{}) (map[string]interface{}, error) { msgStr, err := com.JsonEncode(msg) if err != nil { return nil, err } if this.conn == nil { log.Warnln("Connection Not Exist") return nil, errors.New("Connection Not Exist") } _, err = this.conn.Write([]byte(msgStr + this.mark)) if err != nil { log.Warnln("[Write Error]", err) this.conn.Close() return nil, err } content, err := this.read() if err != nil { return nil, err } // kick sep char reg := regexp.MustCompile(this.mark) content = reg.ReplaceAllString(content, "") if this.debug { log.Bluef("[judger/send:%s]\n%s\n", time.Now(), msgStr) log.Warnf("[judger/recv:%s]\n%s\n", time.Now(), content) } resp, err := com.JsonDecode(content) return resp.(map[string]interface{}), err }
func (this *AdminArticleController) AddArticle() { paramsBody := string(this.Ctx.Input.RequestBody) var params map[string]interface{} p, err := com.JsonDecode(paramsBody) if err != nil { this.Data["json"] = map[string]interface{}{"result": false, "msg": "parse params failed", "refer": "/"} this.ServeJson() return } else { params = p.(map[string]interface{})["params"].(map[string]interface{}) } // log.Pinkln(params) title := params["title"].(string) content := params["content"].(string) keywords := params["keywords"].(string) abstract := params["abstract"].(string) // if not login, permission deny user := this.GetSession("username") if user == nil { this.Data["json"] = map[string]interface{}{"result": false, "msg": "login first please", "refer": nil} this.ServeJson() return } if "" == title { this.Data["json"] = map[string]interface{}{"result": false, "msg": "title can not be empty", "refer": "/"} this.ServeJson() return } username := user.(string) id, err := AddArticle(title, content, keywords, abstract, username) if nil == err { this.Data["json"] = map[string]interface{}{ "result": true, "msg": "success added, id " + fmt.Sprintf("[%d] ", id), "data": id, "refer": nil, } } else { log.Warnln(err) this.Data["json"] = map[string]interface{}{"result": false, "msg": "added failed", "refer": nil} } this.ServeJson() }
func SetCache(key string, value interface{}, timeout int64) error { data, err := Encode(value) if err != nil { return err } err = cc.Put(key, data, timeout) if err != nil { log.Warnln("Cache失败,key:", key) return err } else { log.Blueln("Cache成功,key:", key) return nil } }
func GetCache(key string, to interface{}) error { data := cc.Get(key) if data == nil { return errors.New("Cache不存在") } // log.Pinkln(data) err := Decode(data.([]byte), to) if err != nil { log.Warnln("获取Cache失败", key, err) } else { log.Greenln("获取Cache成功", key) } return err }
func ConnectJudger(host string, port int, password string) error { J = make(map[string]interface{}) cli, err := client.New(host, port, password) J["default"] = cli if err != nil { log.Warnln(err) return err } cli.SetDebug(true) return nil }
// get the result func (this *Info) getResult(file string) int { path := filepath.Join(this.buildPath, this.sid, fmt.Sprintf("%d", this.id), file) if com.PathExist(path) { content := com.ReadFile(path) content = com.Strim(content) if result, err := strconv.Atoi(content); err != nil { log.Warnln(err) return -1 } else { return result } } else { return -1 } }
func (this *OAuthController) Post() { this.Forbbiden("is", "guest") password := this.GetString("password") token := this.GetString("token") username := this.Data["username"].(string) user := models.User{} oa := models.OAuth{} result, _ := user.Login(username, password) if result { u, err := user.GetUser(0, username, "", "") if err != nil { log.Warnln("get uid failed.") this.Data["json"] = map[string]interface{}{ "result": false, "msg": "get uid failed.", "refer": nil, } } if oa.GithubBind(token, "github", u.Id) { this.Data["json"] = map[string]interface{}{ "result": true, "msg": "binding success", "refer": nil, } } else { this.Data["json"] = map[string]interface{}{ "result": false, "msg": "binding failed", "refer": nil, } } } else { this.Data["json"] = map[string]interface{}{ "result": false, "msg": "wrong password.", "refer": nil, } } this.ServeJson() }
func (this *OAuthController) Get() { code := this.GetString("code") clientId := beego.AppConfig.String("github_client_id") clientSecret := beego.AppConfig.String("github_client_secret") oauthGithub := &oauth.GithubOAuth{} token, json, err := oauthGithub.GetData(clientId, clientSecret, code) if err != nil { this.Ctx.WriteString("Response Error! ") return } else { log.Blueln(json) } user := models.User{} oa := models.OAuth{} if this.Data["userIs"] == "guest" { result, usr := oa.GithubLogin(token, "github") if result { log.Blueln("github login success.") this.SetSession("username", usr.Username) this.SetSession("level", usr.Level) this.Redirect("/", 302) } else { log.Warnln("you have not register or bindding you github account.") this.Redirect("/register", 302) } } else { // have login, binding github oauth data := json.(map[string]interface{}) avatar := data["avatar_url"].(string) username := data["login"].(string) gojAvatar, _ := user.GetAvatar(0, this.Data["username"].(string), "", "") this.Data["title"] = "github绑定确认" this.Data["github_avatar"] = avatar this.Data["goj_avatar"] = gojAvatar this.Data["token"] = token this.Data["github_username"] = username this.TplNames = "user/github_binding_confirm.tpl" } }
func init() { var err error db, err = sql.Open("mysql", "root:lijun@tcp(127.0.0.1:3306)/blog") if err != nil { log.Warnln(err) } db.SetMaxOpenConns(2000) db.SetMaxIdleConns(1000) db.Ping() models = make(map[string]*Model) // data := query("users", 8) // log.Pinkln(data) }
func reconnect() { host := beego.AppConfig.String("judgerhost") port, err := beego.AppConfig.Int("judgerport") pass := beego.AppConfig.String("judgerpass") if err != nil { port = 1004 } jdg := judger.Get("default") err = jdg.Start(host, port, pass) if err != nil { log.Warnln("Reconnect Failed", err) } else { log.Blueln("Reconnected.") } }
// call runner in nix func runnerNix(runScript string, bin string, argTime string, argMem string) error { binPath := filepath.Join(bin) cmd := exec.Command("sh", runScript, // runner script argTime, // time limit argMem, // memory limit binPath, // executable name ) log.Warnln("[", runScript, binPath, argTime, argMem, "]") _, err := cmd.Output() if err != nil { fmt.Println("失败") fmt.Println(err) return err } return nil }