backend: Don't watch symlinks nor temporary directories
[fic/server.git] / backend / main.go
1 package main
2
3 import (
4 "flag"
5 "io/ioutil"
6 "log"
7 "math/rand"
8 "os"
9 "path"
10 "strings"
11 "time"
12
13 "srs.epita.fr/fic-server/libfic"
14 "srs.epita.fr/fic-server/settings"
15
16 "gopkg.in/fsnotify.v1"
17 )
18
19 var TeamsDir string
20 var SubmissionDir string
21
22 func watchsubdir(watcher *fsnotify.Watcher, pathname string) error {
23 log.Println("Watch new directory:", pathname)
24 if err := watcher.Add(pathname); err != nil {
25 return err
26 }
27
28 if ds, err := ioutil.ReadDir(pathname); err != nil {
29 return err
30 } else {
31 for _, d := range ds {
32 p := path.Join(pathname, d.Name())
33 if d.IsDir() && d.Name() != ".tmp" && d.Mode() & os.ModeSymlink == 0 {
34 if err := watchsubdir(watcher, p); err != nil {
35 return err
36 }
37 } else if d.Mode().IsRegular() {
38 go treat(p)
39 }
40 }
41 return nil
42 }
43 }
44
45 var lastRegeneration time.Time
46
47 func reloadSettings(config settings.FICSettings) {
48 if lastRegeneration != config.Generation || fic.PartialValidation != config.PartialValidation || fic.UnlockedChallenges != !config.EnableExerciceDepend || fic.FirstBlood != config.FirstBlood || fic.SubmissionCostBase != config.SubmissionCostBase {
49 lastRegeneration = config.Generation
50
51 fic.PartialValidation = config.PartialValidation
52 fic.UnlockedChallenges = !config.EnableExerciceDepend
53
54 fic.FirstBlood = config.FirstBlood
55 fic.SubmissionCostBase = config.SubmissionCostBase
56
57 log.Println("Generating files...")
58 go func() {
59 genAll()
60 log.Println("Full generation done")
61 }()
62 } else {
63 log.Println("No change found. Skipping regeneration.")
64 }
65 }
66
67 func main() {
68 var dsn = flag.String("dsn", fic.DSNGenerator(), "DSN to connect to the MySQL server")
69 flag.StringVar(&settings.SettingsDir, "settings", settings.SettingsDir, "Base directory where load and save settings")
70 flag.StringVar(&SubmissionDir, "submission", "./submissions", "Base directory where save submissions")
71 flag.StringVar(&TeamsDir, "teams", "./TEAMS", "Base directory where save teams JSON files")
72 flag.StringVar(&fic.FilesDir, "files", "/files", "Request path prefix to reach files")
73 var debugINotify = flag.Bool("debuginotify", false, "Show skipped inotofy events")
74 flag.Parse()
75
76 log.SetPrefix("[backend] ")
77
78 settings.SettingsDir = path.Clean(settings.SettingsDir)
79 SubmissionDir = path.Clean(SubmissionDir)
80 TeamsDir = path.Clean(TeamsDir)
81
82 rand.Seed(time.Now().UnixNano())
83
84 log.Println("Creating submission directory...")
85 if _, err := os.Stat(SubmissionDir); os.IsNotExist(err) {
86 if err := os.MkdirAll(SubmissionDir, 0777); err != nil {
87 log.Fatal("Unable to create submission directory: ", err)
88 }
89 }
90
91 log.Println("Opening DB...")
92 if err := fic.DBInit(*dsn); err != nil {
93 log.Fatal("Cannot open the database: ", err)
94 }
95 defer fic.DBClose()
96
97 // Load configuration
98 settings.LoadAndWatchSettings(path.Join(settings.SettingsDir, settings.SettingsFile), reloadSettings)
99
100 log.Println("Registering directory events...")
101 watcher, err := fsnotify.NewWatcher()
102 if err != nil {
103 log.Fatal(err)
104 }
105 defer watcher.Close()
106
107 if err := watchsubdir(watcher, SubmissionDir); err != nil {
108 log.Fatal(err)
109 }
110
111 watchedNotify := fsnotify.Create
112
113 for {
114 select {
115 case ev := <-watcher.Events:
116 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" {
117 // Register new subdirectory
118 if err := watchsubdir(watcher, ev.Name); err != nil {
119 log.Println(err)
120 }
121 } else if ev.Op & watchedNotify == watchedNotify && d.Mode().IsRegular() {
122 if *debugINotify {
123 log.Println("Treating event:", ev, "for", ev.Name)
124 }
125 go treat(ev.Name)
126 } else if ev.Op & fsnotify.Write == fsnotify.Write {
127 log.Println("FSNOTIFY WRITE SEEN. Prefer looking at them, as it appears files are not atomically moved.")
128 watchedNotify = fsnotify.Write
129 } else if *debugINotify {
130 log.Println("Skipped event:", ev, "for", ev.Name)
131 }
132 case err := <-watcher.Errors:
133 log.Println("error:", err)
134 }
135 }
136 }
137
138 func treat(raw_path string) {
139 // Extract
140 spath := strings.Split(strings.TrimPrefix(raw_path, SubmissionDir), "/")
141
142 if len(spath) == 3 {
143 if spath[1] == "_registration" {
144 treatRegistration(raw_path, spath[2])
145 } else if team, err := fic.GetTeamByInitialName(spath[1]); err != nil {
146 log.Println("[ERR]", err)
147 } else if spath[2] == "name" {
148 treatRename(raw_path, team)
149 } else if spath[2] == "hint" {
150 treatOpeningHint(raw_path, team)
151 } else {
152 treatSubmission(raw_path, team, spath[2])
153 }
154 } else {
155 log.Println("Invalid new file:", raw_path)
156 }
157 }