blob: bf352fb13178b0573a4128365f8695a1ac255c19 [file] [log] [blame]
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +00001package main
2
3import (
4 "bytes"
5 "crypto/md5"
commit-bot@chromium.org282333f2014-04-14 14:54:07 +00006 "database/sql"
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +00007 "encoding/base64"
8 "encoding/json"
9 "flag"
10 "fmt"
commit-bot@chromium.org282333f2014-04-14 14:54:07 +000011 _ "github.com/go-sql-driver/mysql"
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +000012 _ "github.com/mattn/go-sqlite3"
13 htemplate "html/template"
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000014 "io/ioutil"
15 "log"
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +000016 "math/rand"
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000017 "net/http"
18 "os"
19 "os/exec"
20 "path/filepath"
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +000021 "regexp"
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000022 "strings"
23 "text/template"
commit-bot@chromium.org06aca012014-04-14 20:12:08 +000024 "time"
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000025)
26
27const (
commit-bot@chromium.org89126a62014-04-30 19:38:51 +000028 RESULT_COMPILE = `../../experimental/webtry/safec++ -DSK_GAMMA_SRGB -DSK_GAMMA_APPLY_TO_A8 -DSK_SCALAR_TO_FLOAT_EXCLUDED -DSK_ALLOW_STATIC_GLOBAL_INITIALIZERS=1 -DSK_SUPPORT_GPU=0 -DSK_SUPPORT_OPENCL=0 -DSK_FORCE_DISTANCEFIELD_FONTS=0 -DSK_SCALAR_IS_FLOAT -DSK_CAN_USE_FLOAT -DSK_SAMPLES_FOR_X -DSK_BUILD_FOR_UNIX -DSK_USE_POSIX_THREADS -DSK_SYSTEM_ZLIB=1 -DSK_DEBUG -DSK_DEVELOPER=1 -I../../src/core -I../../src/images -I../../tools/flags -I../../include/config -I../../include/core -I../../include/pathops -I../../include/pipe -I../../include/effects -I../../include/ports -I../../src/sfnt -I../../include/utils -I../../src/utils -I../../include/images -g -fno-exceptions -fstrict-aliasing -Wall -Wextra -Winit-self -Wpointer-arith -Wno-unused-parameter -m64 -fno-rtti -Wnon-virtual-dtor -c ../../../cache/%s.cpp -o ../../../cache/%s.o`
29 LINK = `../../experimental/webtry/safec++ -m64 -lstdc++ -lm -o ../../../inout/%s -Wl,--start-group ../../../cache/%s.o obj/experimental/webtry/webtry.main.o obj/gyp/libflags.a libskia_images.a libskia_core.a libskia_effects.a obj/gyp/libjpeg.a obj/gyp/libwebp_dec.a obj/gyp/libwebp_demux.a obj/gyp/libwebp_dsp.a obj/gyp/libwebp_enc.a obj/gyp/libwebp_utils.a libskia_utils.a libskia_opts.a libskia_opts_ssse3.a libskia_ports.a libskia_sfnt.a -Wl,--end-group -lpng -lz -lgif -lpthread -lfontconfig -ldl -lfreetype`
fmalita@google.com950306c2014-05-01 15:14:56 +000030 DEFAULT_SAMPLE = `void draw(SkCanvas* canvas) {
31 SkPaint p;
32 p.setColor(SK_ColorRED);
33 p.setAntiAlias(true);
34 p.setStyle(SkPaint::kStroke_Style);
35 p.setStrokeWidth(10);
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +000036
fmalita@google.com950306c2014-05-01 15:14:56 +000037 canvas->drawLine(20, 20, 100, 100, p);
38}`
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +000039 // Don't increase above 2^16 w/o altering the db tables to accept something bigger than TEXT.
40 MAX_TRY_SIZE = 64000
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000041)
42
43var (
44 // codeTemplate is the cpp code template the user's code is copied into.
45 codeTemplate *template.Template = nil
46
commit-bot@chromium.org06aca012014-04-14 20:12:08 +000047 // indexTemplate is the main index.html page we serve.
48 indexTemplate *htemplate.Template = nil
49
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +000050 // iframeTemplate is the main index.html page we serve.
51 iframeTemplate *htemplate.Template = nil
52
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +000053 // recentTemplate is a list of recent images.
commit-bot@chromium.org06aca012014-04-14 20:12:08 +000054 recentTemplate *htemplate.Template = nil
commit-bot@chromium.org282333f2014-04-14 14:54:07 +000055
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +000056 // workspaceTemplate is the page for workspaces, a series of webtrys.
57 workspaceTemplate *htemplate.Template = nil
58
commit-bot@chromium.org282333f2014-04-14 14:54:07 +000059 // db is the database, nil if we don't have an SQL database to store data into.
60 db *sql.DB = nil
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +000061
62 // directLink is the regex that matches URLs paths that are direct links.
commit-bot@chromium.org06aca012014-04-14 20:12:08 +000063 directLink = regexp.MustCompile("^/c/([a-f0-9]+)$")
64
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +000065 // iframeLink is the regex that matches URLs paths that are links to iframes.
66 iframeLink = regexp.MustCompile("^/iframe/([a-f0-9]+)$")
67
commit-bot@chromium.org06aca012014-04-14 20:12:08 +000068 // imageLink is the regex that matches URLs paths that are direct links to PNGs.
69 imageLink = regexp.MustCompile("^/i/([a-f0-9]+.png)$")
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +000070
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +000071 // tryInfoLink is the regex that matches URLs paths that are direct links to data about a single try.
72 tryInfoLink = regexp.MustCompile("^/json/([a-f0-9]+)$")
73
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +000074 // workspaceLink is the regex that matches URLs paths for workspaces.
75 workspaceLink = regexp.MustCompile("^/w/([a-z0-9-]+)$")
76
77 // workspaceNameAdj is a list of adjectives for building workspace names.
78 workspaceNameAdj = []string{
79 "autumn", "hidden", "bitter", "misty", "silent", "empty", "dry", "dark",
80 "summer", "icy", "delicate", "quiet", "white", "cool", "spring", "winter",
81 "patient", "twilight", "dawn", "crimson", "wispy", "weathered", "blue",
82 "billowing", "broken", "cold", "damp", "falling", "frosty", "green",
83 "long", "late", "lingering", "bold", "little", "morning", "muddy", "old",
84 "red", "rough", "still", "small", "sparkling", "throbbing", "shy",
85 "wandering", "withered", "wild", "black", "young", "holy", "solitary",
86 "fragrant", "aged", "snowy", "proud", "floral", "restless", "divine",
87 "polished", "ancient", "purple", "lively", "nameless",
88 }
89
90 // workspaceNameNoun is a list of nouns for building workspace names.
91 workspaceNameNoun = []string{
92 "waterfall", "river", "breeze", "moon", "rain", "wind", "sea", "morning",
93 "snow", "lake", "sunset", "pine", "shadow", "leaf", "dawn", "glitter",
94 "forest", "hill", "cloud", "meadow", "sun", "glade", "bird", "brook",
95 "butterfly", "bush", "dew", "dust", "field", "fire", "flower", "firefly",
96 "feather", "grass", "haze", "mountain", "night", "pond", "darkness",
97 "snowflake", "silence", "sound", "sky", "shape", "surf", "thunder",
98 "violet", "water", "wildflower", "wave", "water", "resonance", "sun",
99 "wood", "dream", "cherry", "tree", "fog", "frost", "voice", "paper",
100 "frog", "smoke", "star",
101 }
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000102
103 gitHash = ""
104 gitInfo = ""
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000105)
106
107// flags
108var (
109 useChroot = flag.Bool("use_chroot", false, "Run the compiled code in the schroot jail.")
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000110 port = flag.String("port", ":8000", "HTTP service address (e.g., ':8000')")
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000111)
112
113// lineNumbers adds #line numbering to the user's code.
114func LineNumbers(c string) string {
115 lines := strings.Split(c, "\n")
116 ret := []string{}
117 for i, line := range lines {
118 ret = append(ret, fmt.Sprintf("#line %d", i+1))
119 ret = append(ret, line)
120 }
121 return strings.Join(ret, "\n")
122}
123
124func init() {
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000125 rand.Seed(time.Now().UnixNano())
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000126
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000127 // Change the current working directory to the directory of the executable.
128 var err error
129 cwd, err := filepath.Abs(filepath.Dir(os.Args[0]))
130 if err != nil {
131 log.Fatal(err)
132 }
133 os.Chdir(cwd)
134
135 codeTemplate, err = template.ParseFiles(filepath.Join(cwd, "templates/template.cpp"))
136 if err != nil {
137 panic(err)
138 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000139 indexTemplate, err = htemplate.ParseFiles(
140 filepath.Join(cwd, "templates/index.html"),
141 filepath.Join(cwd, "templates/titlebar.html"),
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000142 filepath.Join(cwd, "templates/content.html"),
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000143 )
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000144 if err != nil {
145 panic(err)
146 }
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000147 iframeTemplate, err = htemplate.ParseFiles(
148 filepath.Join(cwd, "templates/iframe.html"),
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000149 filepath.Join(cwd, "templates/content.html"),
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000150 )
151 if err != nil {
152 panic(err)
153 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000154 recentTemplate, err = htemplate.ParseFiles(
155 filepath.Join(cwd, "templates/recent.html"),
156 filepath.Join(cwd, "templates/titlebar.html"),
157 )
158 if err != nil {
159 panic(err)
160 }
161 workspaceTemplate, err = htemplate.ParseFiles(
162 filepath.Join(cwd, "templates/workspace.html"),
163 filepath.Join(cwd, "templates/titlebar.html"),
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000164 filepath.Join(cwd, "templates/content.html"),
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000165 )
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000166 if err != nil {
167 panic(err)
168 }
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000169
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000170 // The git command returns output of the format:
171 //
172 // f672cead70404080a991ebfb86c38316a4589b23 2014-04-27 19:21:51 +0000
173 //
174 logOutput, err := doCmd(`git log --format=%H%x20%ai HEAD^..HEAD`, true)
175 if err != nil {
176 panic(err)
177 }
178 logInfo := strings.Split(logOutput, " ")
179 gitHash = logInfo[0]
180 gitInfo = logInfo[1] + " " + logInfo[2] + " " + logInfo[0][0:6]
181
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000182 // Connect to MySQL server. First, get the password from the metadata server.
183 // See https://developers.google.com/compute/docs/metadata#custom.
184 req, err := http.NewRequest("GET", "http://metadata/computeMetadata/v1/instance/attributes/password", nil)
185 if err != nil {
186 panic(err)
187 }
188 client := http.Client{}
189 req.Header.Add("X-Google-Metadata-Request", "True")
190 if resp, err := client.Do(req); err == nil {
191 password, err := ioutil.ReadAll(resp.Body)
192 if err != nil {
193 log.Printf("ERROR: Failed to read password from metadata server: %q\n", err)
194 panic(err)
195 }
196 // The IP address of the database is found here:
197 // https://console.developers.google.com/project/31977622648/sql/instances/webtry/overview
198 // And 3306 is the default port for MySQL.
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000199 db, err = sql.Open("mysql", fmt.Sprintf("webtry:%s@tcp(173.194.83.52:3306)/webtry?parseTime=true", password))
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000200 if err != nil {
201 log.Printf("ERROR: Failed to open connection to SQL server: %q\n", err)
202 panic(err)
203 }
204 } else {
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000205 log.Printf("INFO: Failed to find metadata, unable to connect to MySQL server (Expected when running locally): %q\n", err)
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000206 // Fallback to sqlite for local use.
207 db, err = sql.Open("sqlite3", "./webtry.db")
208 if err != nil {
209 log.Printf("ERROR: Failed to open: %q\n", err)
210 panic(err)
211 }
212 sql := `CREATE TABLE webtry (
213 code TEXT DEFAULT '' NOT NULL,
214 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
215 hash CHAR(64) DEFAULT '' NOT NULL,
216 PRIMARY KEY(hash)
217 )`
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000218 _, err = db.Exec(sql)
219 log.Printf("Info: status creating sqlite table for webtry: %q\n", err)
220 sql = `CREATE TABLE workspace (
221 name CHAR(64) DEFAULT '' NOT NULL,
222 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
223 PRIMARY KEY(name)
224 )`
225 _, err = db.Exec(sql)
226 log.Printf("Info: status creating sqlite table for workspace: %q\n", err)
227 sql = `CREATE TABLE workspacetry (
228 name CHAR(64) DEFAULT '' NOT NULL,
229 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
230 hash CHAR(64) DEFAULT '' NOT NULL,
231 hidden INTEGER DEFAULT 0 NOT NULL,
232
233 FOREIGN KEY (name) REFERENCES workspace(name)
234 )`
235 _, err = db.Exec(sql)
236 log.Printf("Info: status creating sqlite table for workspace try: %q\n", err)
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000237 }
commit-bot@chromium.org9f3b9252014-05-14 12:55:34 +0000238
239 // Ping the database to keep the connection fresh.
240 go func() {
241 c := time.Tick(1 * time.Minute)
242 for _ = range c {
243 if err := db.Ping(); err != nil {
244 log.Printf("ERROR: Database failed to respond: %q\n", err)
245 }
246 }
247 }()
248
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000249}
250
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000251// Titlebar is used in titlebar template expansion.
252type Titlebar struct {
253 GitHash string
254 GitInfo string
255}
256
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000257// userCode is used in template expansion.
258type userCode struct {
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000259 Code string
260 Hash string
261 Titlebar Titlebar
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000262}
263
264// expandToFile expands the template and writes the result to the file.
265func expandToFile(filename string, code string, t *template.Template) error {
266 f, err := os.Create(filename)
267 if err != nil {
268 return err
269 }
270 defer f.Close()
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000271 return t.Execute(f, userCode{Code: code, Titlebar: Titlebar{GitHash: gitHash, GitInfo: gitInfo}})
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000272}
273
274// expandCode expands the template into a file and calculate the MD5 hash.
275func expandCode(code string) (string, error) {
276 h := md5.New()
277 h.Write([]byte(code))
278 hash := fmt.Sprintf("%x", h.Sum(nil))
279 // At this point we are running in skia/experimental/webtry, making cache a
280 // peer directory to skia.
281 // TODO(jcgregorio) Make all relative directories into flags.
282 err := expandToFile(fmt.Sprintf("../../../cache/%s.cpp", hash), code, codeTemplate)
283 return hash, err
284}
285
286// response is serialized to JSON as a response to POSTs.
287type response struct {
288 Message string `json:"message"`
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000289 StdOut string `json:"stdout"`
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000290 Img string `json:"img"`
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000291 Hash string `json:"hash"`
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000292}
293
294// doCmd executes the given command line string in either the out/Debug
commit-bot@chromium.org15b29812014-04-28 14:56:32 +0000295// directory or the inout directory. Returns the stdout and stderr.
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000296func doCmd(commandLine string, moveToDebug bool) (string, error) {
297 log.Printf("Command: %q\n", commandLine)
298 programAndArgs := strings.SplitN(commandLine, " ", 2)
299 program := programAndArgs[0]
300 args := []string{}
301 if len(programAndArgs) > 1 {
302 args = strings.Split(programAndArgs[1], " ")
303 }
304 cmd := exec.Command(program, args...)
305 abs, err := filepath.Abs("../../out/Debug")
306 if err != nil {
307 return "", fmt.Errorf("Failed to find absolute path to Debug directory.")
308 }
309 if moveToDebug {
310 cmd.Dir = abs
311 } else if !*useChroot { // Don't set cmd.Dir when using chroot.
312 abs, err := filepath.Abs("../../../inout")
313 if err != nil {
314 return "", fmt.Errorf("Failed to find absolute path to inout directory.")
315 }
316 cmd.Dir = abs
317 }
318 log.Printf("Run in directory: %q\n", cmd.Dir)
commit-bot@chromium.org15b29812014-04-28 14:56:32 +0000319 message, err := cmd.CombinedOutput()
320 log.Printf("StdOut + StdErr: %s\n", string(message))
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000321 if err != nil {
322 log.Printf("Exit status: %s\n", err.Error())
commit-bot@chromium.org15b29812014-04-28 14:56:32 +0000323 return string(message), fmt.Errorf("Failed to run command.")
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000324 }
commit-bot@chromium.org15b29812014-04-28 14:56:32 +0000325 return string(message), nil
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000326}
327
328// reportError formats an HTTP error response and also logs the detailed error message.
329func reportError(w http.ResponseWriter, r *http.Request, err error, message string) {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000330 log.Printf("Error: %s\n%s", message, err.Error())
331 http.Error(w, message, 500)
332}
333
334// reportTryError formats an HTTP error response in JSON and also logs the detailed error message.
335func reportTryError(w http.ResponseWriter, r *http.Request, err error, message, hash string) {
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000336 m := response{
337 Message: message,
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000338 Hash: hash,
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000339 }
340 log.Printf("Error: %s\n%s", message, err.Error())
341 resp, err := json.Marshal(m)
342 if err != nil {
343 http.Error(w, "Failed to serialize a response", 500)
344 return
345 }
346 w.Write(resp)
347}
348
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000349func writeToDatabase(hash string, code string, workspaceName string) {
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000350 if db == nil {
351 return
352 }
353 if _, err := db.Exec("INSERT INTO webtry (code, hash) VALUES(?, ?)", code, hash); err != nil {
354 log.Printf("ERROR: Failed to insert code into database: %q\n", err)
355 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000356 if workspaceName != "" {
357 if _, err := db.Exec("INSERT INTO workspacetry (name, hash) VALUES(?, ?)", workspaceName, hash); err != nil {
358 log.Printf("ERROR: Failed to insert into workspacetry table: %q\n", err)
359 }
360 }
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000361}
362
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000363// imageHandler serves up the PNG of a specific try.
364func imageHandler(w http.ResponseWriter, r *http.Request) {
365 log.Printf("Image Handler: %q\n", r.URL.Path)
366 if r.Method != "GET" {
367 http.NotFound(w, r)
368 return
369 }
370 match := imageLink.FindStringSubmatch(r.URL.Path)
371 if len(match) != 2 {
372 http.NotFound(w, r)
373 return
374 }
375 filename := match[1]
376 http.ServeFile(w, r, fmt.Sprintf("../../../inout/%s", filename))
377}
378
379type Try struct {
commit-bot@chromium.orgc3b738a2014-04-21 17:36:44 +0000380 Hash string `json:"hash"`
381 CreateTS string `json:"create_ts"`
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000382}
383
384type Recent struct {
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000385 Tries []Try
386 Titlebar Titlebar
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000387}
388
389// recentHandler shows the last 20 tries.
390func recentHandler(w http.ResponseWriter, r *http.Request) {
391 log.Printf("Recent Handler: %q\n", r.URL.Path)
392
393 var err error
394 rows, err := db.Query("SELECT create_ts, hash FROM webtry ORDER BY create_ts DESC LIMIT 20")
395 if err != nil {
396 http.NotFound(w, r)
397 return
398 }
399 recent := []Try{}
400 for rows.Next() {
401 var hash string
402 var create_ts time.Time
403 if err := rows.Scan(&create_ts, &hash); err != nil {
404 log.Printf("Error: failed to fetch from database: %q", err)
405 continue
406 }
407 recent = append(recent, Try{Hash: hash, CreateTS: create_ts.Format("2006-02-01")})
408 }
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000409 if err := recentTemplate.Execute(w, Recent{Tries: recent, Titlebar: Titlebar{GitHash: gitHash, GitInfo: gitInfo}}); err != nil {
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000410 log.Printf("ERROR: Failed to expand template: %q\n", err)
411 }
412}
413
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000414type Workspace struct {
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000415 Name string
416 Code string
417 Hash string
418 Tries []Try
419 Titlebar Titlebar
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000420}
421
422// newWorkspace generates a new random workspace name and stores it in the database.
423func newWorkspace() (string, error) {
424 for i := 0; i < 10; i++ {
425 adj := workspaceNameAdj[rand.Intn(len(workspaceNameAdj))]
426 noun := workspaceNameNoun[rand.Intn(len(workspaceNameNoun))]
427 suffix := rand.Intn(1000)
428 name := fmt.Sprintf("%s-%s-%d", adj, noun, suffix)
429 if _, err := db.Exec("INSERT INTO workspace (name) VALUES(?)", name); err == nil {
430 return name, nil
431 } else {
432 log.Printf("ERROR: Failed to insert workspace into database: %q\n", err)
433 }
434 }
435 return "", fmt.Errorf("Failed to create a new workspace")
436}
437
438// getCode returns the code for a given hash, or the empty string if not found.
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000439func getCode(hash string) (string, error) {
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000440 code := ""
441 if err := db.QueryRow("SELECT code FROM webtry WHERE hash=?", hash).Scan(&code); err != nil {
442 log.Printf("ERROR: Code for hash is missing: %q\n", err)
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000443 return code, err
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000444 }
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000445 return code, nil
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000446}
447
448func workspaceHandler(w http.ResponseWriter, r *http.Request) {
449 log.Printf("Workspace Handler: %q\n", r.URL.Path)
450 if r.Method == "GET" {
451 tries := []Try{}
452 match := workspaceLink.FindStringSubmatch(r.URL.Path)
453 name := ""
454 if len(match) == 2 {
455 name = match[1]
commit-bot@chromium.orgc3b738a2014-04-21 17:36:44 +0000456 rows, err := db.Query("SELECT create_ts, hash FROM workspacetry WHERE name=? ORDER BY create_ts", name)
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000457 if err != nil {
458 reportError(w, r, err, "Failed to select.")
459 return
460 }
461 for rows.Next() {
462 var hash string
463 var create_ts time.Time
464 if err := rows.Scan(&create_ts, &hash); err != nil {
465 log.Printf("Error: failed to fetch from database: %q", err)
466 continue
467 }
468 tries = append(tries, Try{Hash: hash, CreateTS: create_ts.Format("2006-02-01")})
469 }
470 }
471 var code string
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000472 var hash string
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000473 if len(tries) == 0 {
474 code = DEFAULT_SAMPLE
475 } else {
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000476 hash = tries[len(tries)-1].Hash
477 code, _ = getCode(hash)
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000478 }
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000479 if err := workspaceTemplate.Execute(w, Workspace{Tries: tries, Code: code, Name: name, Hash: hash, Titlebar: Titlebar{GitHash: gitHash, GitInfo: gitInfo}}); err != nil {
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000480 log.Printf("ERROR: Failed to expand template: %q\n", err)
481 }
482 } else if r.Method == "POST" {
483 name, err := newWorkspace()
484 if err != nil {
485 http.Error(w, "Failed to create a new workspace.", 500)
486 return
487 }
488 http.Redirect(w, r, "/w/"+name, 302)
489 }
490}
491
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000492// hasPreProcessor returns true if any line in the code begins with a # char.
493func hasPreProcessor(code string) bool {
494 lines := strings.Split(code, "\n")
495 for _, s := range lines {
496 if strings.HasPrefix(strings.TrimSpace(s), "#") {
497 return true
498 }
499 }
500 return false
501}
502
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000503type TryRequest struct {
504 Code string `json:"code"`
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000505 Name string `json:"name"` // Optional name of the workspace the code is in.
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000506}
507
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000508// iframeHandler handles the GET and POST of the main page.
509func iframeHandler(w http.ResponseWriter, r *http.Request) {
510 log.Printf("IFrame Handler: %q\n", r.URL.Path)
511 if r.Method != "GET" {
512 http.NotFound(w, r)
513 return
514 }
515 match := iframeLink.FindStringSubmatch(r.URL.Path)
516 if len(match) != 2 {
517 http.NotFound(w, r)
518 return
519 }
520 hash := match[1]
521 if db == nil {
522 http.NotFound(w, r)
523 return
524 }
525 var code string
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000526 code, err := getCode(hash)
527 if err != nil {
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000528 http.NotFound(w, r)
529 return
530 }
531 // Expand the template.
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000532 if err := iframeTemplate.Execute(w, userCode{Code: code, Hash: hash}); err != nil {
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000533 log.Printf("ERROR: Failed to expand template: %q\n", err)
534 }
535}
536
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000537type TryInfo struct {
538 Hash string `json:"hash"`
539 Code string `json:"code"`
540}
541
542// tryInfoHandler returns information about a specific try.
543func tryInfoHandler(w http.ResponseWriter, r *http.Request) {
544 log.Printf("Try Info Handler: %q\n", r.URL.Path)
545 if r.Method != "GET" {
546 http.NotFound(w, r)
547 return
548 }
549 match := tryInfoLink.FindStringSubmatch(r.URL.Path)
550 if len(match) != 2 {
551 http.NotFound(w, r)
552 return
553 }
554 hash := match[1]
555 code, err := getCode(hash)
556 if err != nil {
557 http.NotFound(w, r)
558 return
559 }
560 m := TryInfo{
561 Hash: hash,
562 Code: code,
563 }
564 resp, err := json.Marshal(m)
565 if err != nil {
566 reportError(w, r, err, "Failed to serialize a response.")
567 return
568 }
569 w.Header().Set("Content-Type", "application/json")
570 w.Write(resp)
571}
572
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000573func cleanCompileOutput(s, hash string) string {
574 old := "../../../cache/" + hash + ".cpp:"
575 log.Printf("INFO: replacing %q\n", old)
576 return strings.Replace(s, old, "usercode.cpp:", -1)
577}
578
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000579// mainHandler handles the GET and POST of the main page.
580func mainHandler(w http.ResponseWriter, r *http.Request) {
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000581 log.Printf("Main Handler: %q\n", r.URL.Path)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000582 if r.Method == "GET" {
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000583 code := DEFAULT_SAMPLE
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000584 match := directLink.FindStringSubmatch(r.URL.Path)
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000585 var hash string
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000586 if len(match) == 2 && r.URL.Path != "/" {
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000587 hash = match[1]
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000588 if db == nil {
589 http.NotFound(w, r)
590 return
591 }
592 // Update 'code' with the code found in the database.
593 if err := db.QueryRow("SELECT code FROM webtry WHERE hash=?", hash).Scan(&code); err != nil {
594 http.NotFound(w, r)
595 return
596 }
597 }
598 // Expand the template.
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000599 if err := indexTemplate.Execute(w, userCode{Code: code, Hash: hash, Titlebar: Titlebar{GitHash: gitHash, GitInfo: gitInfo}}); err != nil {
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000600 log.Printf("ERROR: Failed to expand template: %q\n", err)
601 }
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000602 } else if r.Method == "POST" {
603 w.Header().Set("Content-Type", "application/json")
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000604 buf := bytes.NewBuffer(make([]byte, 0, MAX_TRY_SIZE))
605 n, err := buf.ReadFrom(r.Body)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000606 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000607 reportTryError(w, r, err, "Failed to read a request body.", "")
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000608 return
609 }
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000610 if n == MAX_TRY_SIZE {
611 err := fmt.Errorf("Code length equal to, or exceeded, %d", MAX_TRY_SIZE)
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000612 reportTryError(w, r, err, "Code too large.", "")
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000613 return
614 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000615 request := TryRequest{}
616 if err := json.Unmarshal(buf.Bytes(), &request); err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000617 reportTryError(w, r, err, "Coulnd't decode JSON.", "")
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000618 return
619 }
620 if hasPreProcessor(request.Code) {
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000621 err := fmt.Errorf("Found preprocessor macro in code.")
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000622 reportTryError(w, r, err, "Preprocessor macros aren't allowed.", "")
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000623 return
624 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000625 hash, err := expandCode(LineNumbers(request.Code))
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000626 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000627 reportTryError(w, r, err, "Failed to write the code to compile.", hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000628 return
629 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000630 writeToDatabase(hash, request.Code, request.Name)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000631 message, err := doCmd(fmt.Sprintf(RESULT_COMPILE, hash, hash), true)
632 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000633 message = cleanCompileOutput(message, hash)
634 reportTryError(w, r, err, message, hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000635 return
636 }
637 linkMessage, err := doCmd(fmt.Sprintf(LINK, hash, hash), true)
638 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000639 linkMessage = cleanCompileOutput(linkMessage, hash)
640 reportTryError(w, r, err, linkMessage, hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000641 return
642 }
643 message += linkMessage
644 cmd := hash + " --out " + hash + ".png"
645 if *useChroot {
646 cmd = "schroot -c webtry --directory=/inout -- /inout/" + cmd
647 } else {
648 abs, err := filepath.Abs("../../../inout")
649 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000650 reportTryError(w, r, err, "Failed to find executable directory.", hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000651 return
652 }
653 cmd = abs + "/" + cmd
654 }
655
656 execMessage, err := doCmd(cmd, false)
657 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000658 reportTryError(w, r, err, "Failed to run the code:\n"+execMessage, hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000659 return
660 }
661 png, err := ioutil.ReadFile("../../../inout/" + hash + ".png")
662 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000663 reportTryError(w, r, err, "Failed to open the generated PNG.", hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000664 return
665 }
666
667 m := response{
668 Message: message,
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000669 StdOut: execMessage,
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000670 Img: base64.StdEncoding.EncodeToString([]byte(png)),
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000671 Hash: hash,
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000672 }
673 resp, err := json.Marshal(m)
674 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000675 reportTryError(w, r, err, "Failed to serialize a response.", hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000676 return
677 }
678 w.Write(resp)
679 }
680}
681
682func main() {
683 flag.Parse()
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000684 http.HandleFunc("/i/", imageHandler)
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000685 http.HandleFunc("/w/", workspaceHandler)
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000686 http.HandleFunc("/recent/", recentHandler)
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000687 http.HandleFunc("/iframe/", iframeHandler)
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000688 http.HandleFunc("/json/", tryInfoHandler)
fmalita@google.com950306c2014-05-01 15:14:56 +0000689
690 // Resources are served directly
691 // TODO add support for caching/etags/gzip
692 http.Handle("/res/", http.FileServer(http.Dir("./")))
693
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000694 // TODO Break out /c/ as it's own handler.
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000695 http.HandleFunc("/", mainHandler)
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000696 log.Fatal(http.ListenAndServe(*port, nil))
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000697}