func (this *Sqlite) createTable() { o := orm.NewOrm() table1 := `CREATE TABLE [session] ( [id] INTEGER PRIMARY KEY NOT NULL, [session] VARCHAR(128) UNIQUE NOT NULL, [create_time] TIME DEFAULT CURRENT_TIMESTAMP NOT NULL )` table2 := `CREATE TABLE [task] ( [id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, [task_id] VARCHAR(128) UNIQUE NOT NULL, [language] VARCHAR(64) DEFAULT '''C''' NOT NULL, [type] VARCHAR(16) DEFAULT '''io''' NOT NULL, [io_data] TEXT NULL, [code] TEXT NULL, [time] TIME DEFAULT CURRENT_TIMESTAMP NOT NULL, [build_log] TEXT NULL, [build_result] VARCHAR(128) NULL, [run_result] VARCHAR(128) NULL, [debug_info] TEXT NULL )` _, err := o.Raw(table1).Exec() if err != nil { log.Blueln(err) } _, err = o.Raw(table2).Exec() if err != nil { log.Blueln(err) } }
func (this *Compile) NewCompile() { this.buildOverTime = false this.system = runtime.GOOS this.postfix_c = "c" this.postfix_cpp = "cpp" this.currentPath, _ = os.Getwd() this.buildPath = filepath.Join(this.currentPath, core.C.Get(runtime.GOOS, "buildpath")) this.compiler_c = filepath.Join(this.currentPath, core.C.Get(runtime.GOOS, "compiler_c")) log.Blueln("[current path]", this.currentPath) log.Blueln("[build path]", this.buildPath) log.Blueln("[compiler path]", this.compiler_c) }
// 通过problem // id bank中的ID func (this *ProblemBank) AcceptProblem(id int) error { o := orm.NewOrm() var prob ProblemBank var err error prob.Id = id // read problem in problem bank err = o.Read(&prob, "Id") if err != nil { return err } // create problem var pro Problem op := orm.NewOrm() pro.Title = prob.Title pro.Pbid = prob.Id pro.Type = prob.Type pro.Description = prob.Description pro.PreCode = prob.PreCode pro.IoData = prob.IoData pro.Tags = prob.Tags pro.Level = "public" log.Blueln("[problem copy from bank to list]") log.Blueln(pro) // insert into problem pid, err := op.Insert(&pro) if err != nil { return err } else if pid == 0 { return errors.New("insert error, id is 0.") } // update problem bank prob.Status = "ok" _, err = o.Update(&prob) if err != nil { return err } else { return nil } }
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 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 } } }
// 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 (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 HttpStart() { http.HandleFunc("/", HandleJsonRpc) err := http.ListenAndServe(":1005", nil) if err != nil { log.Warnln("ListenAndServe: ", err) } else { log.Blueln("Http Server Started!") } }
func (this *ArticleController) Get() { id, err := this.GetInt("id") uri := this.Ctx.Input.Param(":uri") log.Blueln("[uri]", uri) var art Article if nil == err && id != 0 { art, err = GetArticle(int(id)) } else if "" != uri { art, err = GetArticleByUri(uri) } else { this.Abort("404") this.TplNames = "error/404.tpl" return } if 0 == art.Id { this.Abort("404") this.TplNames = "error/404.tpl" return } maps, err := CountByMonth() if nil == err { this.Data["count_by_month"] = maps } hottest, err := HottestArticleList() if nil == err { this.Data["hottest"] = hottest } if nil != err { this.Data["json"] = map[string]interface{}{"result": false, "msg": "invalid request", "refer": "/"} this.ServeJson() } if 0 != art.Id { UpdateCount(art.Id) } this.Data["id"] = art.Id this.Data["title"] = art.Title this.Data["uri"] = art.Uri this.Data["content"] = art.Content this.Data["author"] = art.Author this.Data["time"] = art.Time this.Data["count"] = art.Count this.Data["keywords"] = art.Keywords this.Data["description"] = art.Title this.Data["duoshuo"] = beego.AppConfig.String("duoshuo_short_name") this.TplNames = "article.tpl" }
func (this *ProjectListController) Get() { page, err := this.GetInt64("page") if nil != err || page < 0 { page = 0 } s := this.Ctx.Input.Param(":page") pageParm, err := strconv.Atoi(s) if nil != err || pageParm < 0 { pageParm = 0 } else { page = int64(pageParm) } if 0 == page { page = 1 } // maps, err := CountByMonth() // if nil == err { // this.Data["count_by_month"] = maps // } maps, nextPageFlag, totalPages, err := ListProjects(int(page), 10) if totalPages < int(page) { page = int64(totalPages) } log.Blueln("[page]", page) var prevPageFlag bool if 1 >= page { prevPageFlag = false } else { prevPageFlag = true } if nil == err { this.Data["title"] = "项目" this.Data["keywords"] = "项目" this.Data["description"] = "独孤影的项目" this.Data["prev_page"] = fmt.Sprintf("/project/%d", page-1) this.Data["prev_page_flag"] = prevPageFlag this.Data["next_page"] = fmt.Sprintf("/project/%d", page+1) this.Data["next_page_flag"] = nextPageFlag this.Data["projects_in_page"] = maps } this.TplNames = "project.tpl" }
func (this *ProblemListController) Get() { pro := &models.Problem{} problems, hasNext, _, _ := pro.ListProblem(1, 10, "public") top10, _ := pro.GetTop10() log.Blueln("[top 10]", top10) tag := &models.Tags{} tagList, _ := tag.TagList() log.Blueln("[tags]", tagList) this.Data["title"] = this.Lang("title_problem_list") this.Data["problems"] = problems this.Data["title"] = this.Lang("title_problems") this.Data["has_next"] = hasNext this.Data["top10"] = top10 this.Data["tag_list"] = tagList this.TplNames = "problem/list.tpl" }
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) }
func (this *MarkdownController) Post() { content := this.GetString("content") log.Blueln(content) rst := utils.Markdown2HTML(content) this.Data["json"] = map[string]interface{}{ "result": true, "msg": "success", "preview": rst, "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 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() }
// run before get func (this *BaseController) Prepare() { // get user level var lev string stn := time.Now() st := stn.UnixNano() this.Data["start"] = st log.Blueln(this.Ctx.Request.UserAgent()) user := this.GetSession("username") if user == nil { lev = "guest" // guest, not login } else { level := this.GetSession("level") if level == nil { lev = "user" } else { if tmplev, ok := level.(string); !ok { lev = "user" } else { lev = tmplev } } username := user.(string) usr := models.User{} u, err := usr.GetUser(0, username, "", "") if err != nil { this.Data["nickname"] = "" this.Data["email_md5"] = "" } else { this.Data["username"] = username this.Data["nickname"] = u.Nickname this.Data["email_md5"] = com.Md5(u.Email) } } this.Data["userIs"] = lev // log.Pinkln(lev) }
func (this *ProfileController) Get() { username := this.Ctx.Input.Param(":username") ip := this.Ctx.Input.IP() log.Blueln(ip) if this.Data["userIs"] == "guest" { user := &models.User{} u, _ := user.GetUser(0, username, "", "") this.Data["title"] = u.Nickname + this.Lang("title_profile") } else { this.Data["title"] = this.Data["nickname"].(string) + this.Lang("title_profile") } this.TplNames = "user/profile.tpl" }
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.") } }
func TestConfig(t *testing.T) { Convey("Test Config sections", t, func() { conf := NewConfig("etc/test.ini") content, err := conf.readConfigFile() if err != nil { log.Redln(err) } else { log.Greenln("raw content") log.Pinkln("==============") log.Blueln(content) content = conf.filterComment() log.Greenln("filter comment") log.Pinkln("==============") log.Blueln(content) arraylize := conf.arraylize() log.Greenln("arraylize") log.Pinkln("==============") count := len(arraylize) log.Bluef("[%d]\n", count) for i := 0; i < count; i++ { log.Bluef("[%d]\t%s\n", i, arraylize[i]) } log.Greenln("parse items") log.Pinkln("==============") conf.parseItems() log.Greenln("warning stack") log.Pinkln("==============") log.Blueln(conf.GetWarnings()) log.Greenln("mistake value") log.Pinkln("==============") log.Blueln(conf.GetString("mysql", "host")) log.Greenln("about bool") log.Pinkln("==============") conf.SetBool("test", "dev", true) dev, _ := conf.GetBool("_", "dev") log.Blueln("%v", dev) content = conf.serialize() log.Greenln("serialize value") log.Pinkln("==============") log.Blueln(content) log.Greenln("hex") log.Pinkln("==============") hex, _ := conf.GetInt("_", "hex") log.Blueln(hex) log.Greenln("get empty") log.Pinkln("==============") _, err = conf.GetInt("_", "heloo") if err != nil { log.Blueln(err) } log.Greenln("save config file") log.Pinkln("==============") err := conf.Save("tmp/test.ini") if err == nil { log.Blueln("done!") } } val1, _ := conf.Get("_", "port") So(val1, ShouldEqual, 80) val2, _ := conf.GetString("_", "appname") So(val2, ShouldEqual, "my application") val3, _ := conf.GetString("mysql", "password") So(val3, ShouldEqual, "\"liju") val4, _ := conf.GetString("mysql", "host") So(val4, ShouldEqual, `"192.168.1.11" = GHJ`) val5, _ := conf.GetBool("_", "dev") So(val5, ShouldEqual, true) val6, _ := conf.GetFloat("_", "pi") So(val6, ShouldEqual, 3.14) val7, _ := conf.GetInt("_", "hex") So(val7, ShouldEqual, 0x24) val8 := conf.GetIntDefault("section", "key", 100) So(val8, ShouldEqual, 100) val9 := conf.GetStringDefault("mysql", "key", "") So(val9, ShouldEqual, "") }) }
// send message to client and print in server console func (this *Client) Write(str string) { str = str + MARK this.Conn.Write([]byte(str)) log.Blueln(str) }
// uri /api/problem/list/:page func (this *ProblemListController) Get() { page, err := this.GetInt("page") if nil != err || page < 0 { page = 0 } s := this.Ctx.Input.Param(":page") pageParm, err := strconv.Atoi(s) if nil != err || pageParm < 0 { pageParm = 0 } else { page = pageParm } if 0 == page { page = 1 } status := this.GetString("status") if len(status) <= 0 { status = "ok" } if status == "ok" { pro := models.Problem{} data, hasNext, totalPage, err := pro.ListProblem(page, 20, "") if err != nil { this.Data["json"] = map[string]interface{}{ "result": false, "msg": "get list failing", "list": nil, "has_next": false, "total_page": 0, "refer": nil, } } else { log.Blueln(data) this.Data["json"] = map[string]interface{}{ "result": true, "msg": "get list success", "list": data, "has_next": hasNext, "total_page": totalPage, "refer": nil, } } } else { if status != "audit" && status != "ok" && status != "deleted" { this.Data["json"] = map[string]interface{}{ "result": false, "msg": "invalid status", "list": nil, "has_next": false, "total_page": 0, "refer": nil, } } else { pro := models.ProblemBank{} data, hasNext, totalPage, err := pro.ListProblem(page, 20, status) if err != nil { this.Data["json"] = map[string]interface{}{ "result": false, "msg": "get list failing", "list": nil, "has_next": false, "total_page": 0, "refer": nil, } } else { log.Blueln(data) this.Data["json"] = map[string]interface{}{ "result": true, "msg": "get list success", "list": data, "has_next": hasNext, "total_page": totalPage, "refer": nil, } } } } this.ServeJson() }