server/backend/main.go

245 lines
7.4 KiB
Go
Raw Normal View History

2016-01-13 19:38:45 +00:00
package main
import (
"flag"
"io/ioutil"
"log"
2016-01-14 17:17:35 +00:00
"math/rand"
2016-01-13 19:38:45 +00:00
"os"
"os/signal"
2016-01-13 19:38:45 +00:00
"path"
"strconv"
2016-01-13 19:38:45 +00:00
"strings"
"syscall"
2016-01-14 17:17:35 +00:00
"time"
2016-01-13 19:38:45 +00:00
"srs.epita.fr/fic-server/libfic"
"srs.epita.fr/fic-server/settings"
"gopkg.in/fsnotify.v1"
2016-01-13 19:38:45 +00:00
)
var TeamsDir string
2016-01-13 19:38:45 +00:00
var SubmissionDir string
func watchsubdir(watcher *fsnotify.Watcher, pathname string) error {
2016-01-13 19:38:45 +00:00
log.Println("Watch new directory:", pathname)
if err := watcher.Add(pathname); err != nil {
2016-01-13 19:38:45 +00:00
return err
}
if ds, err := ioutil.ReadDir(pathname); err != nil {
return err
} else {
for _, d := range ds {
p := path.Join(pathname, d.Name())
2019-07-11 17:52:13 +00:00
if d.IsDir() && d.Name() != ".tmp" && d.Mode()&os.ModeSymlink == 0 {
2016-01-13 19:38:45 +00:00
if err := watchsubdir(watcher, p); err != nil {
return err
}
} else if d.Mode().IsRegular() {
go treat(p)
2016-01-13 19:38:45 +00:00
}
}
return nil
}
}
func walkAndTreat(pathname string) error {
if ds, err := ioutil.ReadDir(pathname); err != nil {
return err
} else {
for _, d := range ds {
p := path.Join(pathname, d.Name())
if d.IsDir() && d.Name() != ".tmp" && d.Mode()&os.ModeSymlink == 0 {
if err := walkAndTreat(p); err != nil {
return err
}
} else if d.Mode().IsRegular() {
treat(p)
}
}
return nil
}
}
var ChStarted = false
2017-01-24 01:14:28 +00:00
var lastRegeneration time.Time
var skipInitialGeneration = false
2017-01-24 01:14:28 +00:00
func reloadSettings(config *settings.Settings) {
2019-02-04 17:14:46 +00:00
allowRegistration = config.AllowRegistration
canJoinTeam = config.CanJoinTeam
denyTeamCreation = config.DenyTeamCreation
fic.HintCoefficient = config.HintCurCoefficient
fic.WChoiceCoefficient = config.WChoiceCurCoefficient
fic.ExerciceCurrentCoefficient = config.ExerciceCurCoefficient
ChStarted = config.Start.Unix() > 0 && time.Since(config.Start) >= 0
if lastRegeneration != config.Generation || fic.PartialValidation != config.PartialValidation || fic.UnlockedChallengeDepth != config.UnlockedChallengeDepth || fic.DisplayAllFlags != config.DisplayAllFlags || fic.FirstBlood != config.FirstBlood || fic.SubmissionCostBase != config.SubmissionCostBase || fic.SubmissionUniqueness != config.SubmissionUniqueness {
fic.PartialValidation = config.PartialValidation
fic.UnlockedChallengeDepth = config.UnlockedChallengeDepth
fic.DisplayAllFlags = config.DisplayAllFlags
fic.FirstBlood = config.FirstBlood
fic.SubmissionCostBase = config.SubmissionCostBase
fic.SubmissionUniqueness = config.SubmissionUniqueness
2021-09-06 09:58:03 +00:00
fic.GlobalScoreCoefficient = config.GlobalScoreCoefficient
fic.CountOnlyNotGoodTries = config.CountOnlyNotGoodTries
if !skipInitialGeneration {
log.Println("Generating files...")
go func() {
genAll()
log.Println("Full generation done")
}()
} else {
skipInitialGeneration = false
log.Println("Regeneration skipped by option.")
}
lastRegeneration = config.Generation
} else {
log.Println("No change found. Skipping regeneration.")
}
}
2016-01-13 19:38:45 +00:00
func main() {
if v, exists := os.LookupEnv("FIC_BASEURL"); exists {
fic.FilesDir = v + "files"
} else {
fic.FilesDir = "/files"
}
2017-10-17 04:47:10 +00:00
var dsn = flag.String("dsn", fic.DSNGenerator(), "DSN to connect to the MySQL server")
flag.StringVar(&settings.SettingsDir, "settings", settings.SettingsDir, "Base directory where load and save settings")
2016-01-13 19:38:45 +00:00
flag.StringVar(&SubmissionDir, "submission", "./submissions", "Base directory where save submissions")
flag.StringVar(&TeamsDir, "teams", "./TEAMS", "Base directory where save teams JSON files")
flag.StringVar(&fic.FilesDir, "files", fic.FilesDir, "Request path prefix to reach files")
var debugINotify = flag.Bool("debuginotify", false, "Show skipped inotofy events")
flag.BoolVar(&skipInitialGeneration, "skipfullgeneration", skipInitialGeneration, "Skip the initial regeneration")
flag.IntVar(&parallelJobs, "jobs", parallelJobs, "Number of generation workers")
2016-01-13 19:38:45 +00:00
flag.Parse()
2016-10-13 17:02:41 +00:00
log.SetPrefix("[backend] ")
settings.SettingsDir = path.Clean(settings.SettingsDir)
2016-01-13 19:38:45 +00:00
SubmissionDir = path.Clean(SubmissionDir)
TeamsDir = path.Clean(TeamsDir)
2016-01-13 19:38:45 +00:00
2016-01-14 17:17:35 +00:00
rand.Seed(time.Now().UnixNano())
launchWorkers()
2016-01-13 19:38:45 +00:00
log.Println("Creating submission directory...")
if _, err := os.Stat(path.Join(SubmissionDir, ".tmp")); os.IsNotExist(err) {
if err := os.MkdirAll(path.Join(SubmissionDir, ".tmp"), 0777); err != nil {
2016-01-13 19:38:45 +00:00
log.Fatal("Unable to create submission directory: ", err)
}
}
log.Println("Opening DB...")
2017-10-17 04:47:10 +00:00
if err := fic.DBInit(*dsn); err != nil {
2016-01-13 19:38:45 +00:00
log.Fatal("Cannot open the database: ", err)
}
defer fic.DBClose()
// Load configuration
settings.LoadAndWatchSettings(path.Join(settings.SettingsDir, settings.SettingsFile), reloadSettings)
2016-01-13 19:38:45 +00:00
log.Println("Registering directory events...")
watcher, err := fsnotify.NewWatcher()
2016-01-13 19:38:45 +00:00
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
2016-01-13 19:38:45 +00:00
if err := watchsubdir(watcher, SubmissionDir); err != nil {
log.Fatal(err)
}
// Register SIGUSR1, SIGUSR2
interrupt1 := make(chan os.Signal, 1)
signal.Notify(interrupt1, syscall.SIGUSR1)
interrupt2 := make(chan os.Signal, 1)
signal.Notify(interrupt2, syscall.SIGUSR2)
watchedNotify := fsnotify.Create
2016-01-13 19:38:45 +00:00
for {
select {
case <-interrupt1:
log.Println("SIGUSR1 received, retreating all files in queue...")
walkAndTreat(SubmissionDir)
log.Println("SIGUSR1 treated.")
case <-interrupt2:
inQueueMutex.Lock()
log.Printf("SIGUSR2 received, dumping statistics:\n parallelJobs: %d\n genTeamQueue size: %d\n genQueue: %d\n Teams in queue: %v\n Challenge started: %v\n Last regeneration: %v\n", parallelJobs, len(genTeamQueue), len(genQueue), inGenQueue, ChStarted, lastRegeneration)
inQueueMutex.Unlock()
case ev := <-watcher.Events:
2019-07-11 17:52:13 +00:00
if d, err := os.Lstat(ev.Name); err == nil && ev.Op&fsnotify.Create == fsnotify.Create && d.Mode().IsDir() && d.Mode()&os.ModeSymlink == 0 && d.Name() != ".tmp" {
2016-01-13 19:38:45 +00:00
// Register new subdirectory
2017-04-05 00:02:10 +00:00
if err := watchsubdir(watcher, ev.Name); err != nil {
log.Println(err)
2016-01-13 19:38:45 +00:00
}
2019-07-11 17:52:13 +00:00
} else if ev.Op&watchedNotify == watchedNotify && d.Mode().IsRegular() {
2018-01-16 22:59:51 +00:00
if *debugINotify {
log.Println("Treating event:", ev, "for", ev.Name)
}
go treat(ev.Name)
2019-07-11 17:52:13 +00:00
} else if ev.Op&fsnotify.Write == fsnotify.Write {
log.Println("FSNOTIFY WRITE SEEN. Prefer looking at them, as it appears files are not atomically moved.")
watchedNotify = fsnotify.Write
} else if *debugINotify {
log.Println("Skipped event:", ev, "for", ev.Name)
2016-01-13 19:38:45 +00:00
}
case err := <-watcher.Errors:
2016-01-13 19:38:45 +00:00
log.Println("error:", err)
}
}
}
func treat(raw_path string) {
// Extract
spath := strings.Split(strings.TrimPrefix(raw_path, SubmissionDir), "/")
2016-03-06 17:59:33 +00:00
if len(spath) == 3 {
if spath[1] == "_registration" {
2017-12-21 21:18:18 +00:00
treatRegistration(raw_path, spath[2])
2018-01-21 13:18:26 +00:00
return
}
var teamid int64
var err error
2018-01-21 13:18:26 +00:00
if teamid, err = strconv.ParseInt(spath[1], 10, 64); err != nil {
if lnk, err := os.Readlink(path.Join(TeamsDir, spath[1])); err != nil {
log.Printf("[ERR] Unable to readlink %q: %s\n", path.Join(TeamsDir, spath[1]), err)
2019-01-16 16:16:11 +00:00
return
} else if teamid, err = strconv.ParseInt(lnk, 10, 64); err != nil {
log.Printf("[ERR] Error during ParseInt team %q: %s\n", lnk, err)
2019-01-16 16:16:11 +00:00
return
}
}
2021-11-22 14:35:07 +00:00
var team *fic.Team
if team, err = fic.GetTeam(teamid); err != nil {
log.Printf("[ERR] Unable to retrieve team %d: %s\n", teamid, err)
2018-01-21 13:18:26 +00:00
return
}
switch spath[2] {
case "name":
2016-03-06 17:59:33 +00:00
treatRename(raw_path, team)
case "issue":
treatIssue(raw_path, team)
2018-01-21 13:18:26 +00:00
case "hint":
2016-12-09 10:49:29 +00:00
treatOpeningHint(raw_path, team)
2018-12-02 22:18:32 +00:00
case "choices":
treatWantChoices(raw_path, team)
2018-01-21 13:18:26 +00:00
default:
2016-03-06 17:59:33 +00:00
treatSubmission(raw_path, team, spath[2])
}
} else {
log.Println("Invalid new file:", raw_path)
}
}