blob: f909b0637d3a30d64f2dbd12fa154a339d9ae591 [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.org6d036c22014-04-09 18:59:44 +0000238}
239
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000240// Titlebar is used in titlebar template expansion.
241type Titlebar struct {
242 GitHash string
243 GitInfo string
244}
245
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000246// userCode is used in template expansion.
247type userCode struct {
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000248 Code string
249 Hash string
250 Titlebar Titlebar
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000251}
252
253// expandToFile expands the template and writes the result to the file.
254func expandToFile(filename string, code string, t *template.Template) error {
255 f, err := os.Create(filename)
256 if err != nil {
257 return err
258 }
259 defer f.Close()
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000260 return t.Execute(f, userCode{Code: code, Titlebar: Titlebar{GitHash: gitHash, GitInfo: gitInfo}})
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000261}
262
263// expandCode expands the template into a file and calculate the MD5 hash.
264func expandCode(code string) (string, error) {
265 h := md5.New()
266 h.Write([]byte(code))
267 hash := fmt.Sprintf("%x", h.Sum(nil))
268 // At this point we are running in skia/experimental/webtry, making cache a
269 // peer directory to skia.
270 // TODO(jcgregorio) Make all relative directories into flags.
271 err := expandToFile(fmt.Sprintf("../../../cache/%s.cpp", hash), code, codeTemplate)
272 return hash, err
273}
274
275// response is serialized to JSON as a response to POSTs.
276type response struct {
277 Message string `json:"message"`
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000278 StdOut string `json:"stdout"`
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000279 Img string `json:"img"`
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000280 Hash string `json:"hash"`
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000281}
282
283// doCmd executes the given command line string in either the out/Debug
commit-bot@chromium.org15b29812014-04-28 14:56:32 +0000284// directory or the inout directory. Returns the stdout and stderr.
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000285func doCmd(commandLine string, moveToDebug bool) (string, error) {
286 log.Printf("Command: %q\n", commandLine)
287 programAndArgs := strings.SplitN(commandLine, " ", 2)
288 program := programAndArgs[0]
289 args := []string{}
290 if len(programAndArgs) > 1 {
291 args = strings.Split(programAndArgs[1], " ")
292 }
293 cmd := exec.Command(program, args...)
294 abs, err := filepath.Abs("../../out/Debug")
295 if err != nil {
296 return "", fmt.Errorf("Failed to find absolute path to Debug directory.")
297 }
298 if moveToDebug {
299 cmd.Dir = abs
300 } else if !*useChroot { // Don't set cmd.Dir when using chroot.
301 abs, err := filepath.Abs("../../../inout")
302 if err != nil {
303 return "", fmt.Errorf("Failed to find absolute path to inout directory.")
304 }
305 cmd.Dir = abs
306 }
307 log.Printf("Run in directory: %q\n", cmd.Dir)
commit-bot@chromium.org15b29812014-04-28 14:56:32 +0000308 message, err := cmd.CombinedOutput()
309 log.Printf("StdOut + StdErr: %s\n", string(message))
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000310 if err != nil {
311 log.Printf("Exit status: %s\n", err.Error())
commit-bot@chromium.org15b29812014-04-28 14:56:32 +0000312 return string(message), fmt.Errorf("Failed to run command.")
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000313 }
commit-bot@chromium.org15b29812014-04-28 14:56:32 +0000314 return string(message), nil
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000315}
316
317// reportError formats an HTTP error response and also logs the detailed error message.
318func reportError(w http.ResponseWriter, r *http.Request, err error, message string) {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000319 log.Printf("Error: %s\n%s", message, err.Error())
320 http.Error(w, message, 500)
321}
322
323// reportTryError formats an HTTP error response in JSON and also logs the detailed error message.
324func reportTryError(w http.ResponseWriter, r *http.Request, err error, message, hash string) {
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000325 m := response{
326 Message: message,
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000327 Hash: hash,
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000328 }
329 log.Printf("Error: %s\n%s", message, err.Error())
330 resp, err := json.Marshal(m)
331 if err != nil {
332 http.Error(w, "Failed to serialize a response", 500)
333 return
334 }
335 w.Write(resp)
336}
337
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000338func writeToDatabase(hash string, code string, workspaceName string) {
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000339 if db == nil {
340 return
341 }
342 if _, err := db.Exec("INSERT INTO webtry (code, hash) VALUES(?, ?)", code, hash); err != nil {
343 log.Printf("ERROR: Failed to insert code into database: %q\n", err)
344 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000345 if workspaceName != "" {
346 if _, err := db.Exec("INSERT INTO workspacetry (name, hash) VALUES(?, ?)", workspaceName, hash); err != nil {
347 log.Printf("ERROR: Failed to insert into workspacetry table: %q\n", err)
348 }
349 }
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000350}
351
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000352// imageHandler serves up the PNG of a specific try.
353func imageHandler(w http.ResponseWriter, r *http.Request) {
354 log.Printf("Image Handler: %q\n", r.URL.Path)
355 if r.Method != "GET" {
356 http.NotFound(w, r)
357 return
358 }
359 match := imageLink.FindStringSubmatch(r.URL.Path)
360 if len(match) != 2 {
361 http.NotFound(w, r)
362 return
363 }
364 filename := match[1]
365 http.ServeFile(w, r, fmt.Sprintf("../../../inout/%s", filename))
366}
367
368type Try struct {
commit-bot@chromium.orgc3b738a2014-04-21 17:36:44 +0000369 Hash string `json:"hash"`
370 CreateTS string `json:"create_ts"`
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000371}
372
373type Recent struct {
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000374 Tries []Try
375 Titlebar Titlebar
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000376}
377
378// recentHandler shows the last 20 tries.
379func recentHandler(w http.ResponseWriter, r *http.Request) {
380 log.Printf("Recent Handler: %q\n", r.URL.Path)
381
382 var err error
383 rows, err := db.Query("SELECT create_ts, hash FROM webtry ORDER BY create_ts DESC LIMIT 20")
384 if err != nil {
385 http.NotFound(w, r)
386 return
387 }
388 recent := []Try{}
389 for rows.Next() {
390 var hash string
391 var create_ts time.Time
392 if err := rows.Scan(&create_ts, &hash); err != nil {
393 log.Printf("Error: failed to fetch from database: %q", err)
394 continue
395 }
396 recent = append(recent, Try{Hash: hash, CreateTS: create_ts.Format("2006-02-01")})
397 }
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000398 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 +0000399 log.Printf("ERROR: Failed to expand template: %q\n", err)
400 }
401}
402
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000403type Workspace struct {
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000404 Name string
405 Code string
406 Hash string
407 Tries []Try
408 Titlebar Titlebar
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000409}
410
411// newWorkspace generates a new random workspace name and stores it in the database.
412func newWorkspace() (string, error) {
413 for i := 0; i < 10; i++ {
414 adj := workspaceNameAdj[rand.Intn(len(workspaceNameAdj))]
415 noun := workspaceNameNoun[rand.Intn(len(workspaceNameNoun))]
416 suffix := rand.Intn(1000)
417 name := fmt.Sprintf("%s-%s-%d", adj, noun, suffix)
418 if _, err := db.Exec("INSERT INTO workspace (name) VALUES(?)", name); err == nil {
419 return name, nil
420 } else {
421 log.Printf("ERROR: Failed to insert workspace into database: %q\n", err)
422 }
423 }
424 return "", fmt.Errorf("Failed to create a new workspace")
425}
426
427// getCode returns the code for a given hash, or the empty string if not found.
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000428func getCode(hash string) (string, error) {
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000429 code := ""
430 if err := db.QueryRow("SELECT code FROM webtry WHERE hash=?", hash).Scan(&code); err != nil {
431 log.Printf("ERROR: Code for hash is missing: %q\n", err)
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000432 return code, err
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000433 }
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000434 return code, nil
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000435}
436
437func workspaceHandler(w http.ResponseWriter, r *http.Request) {
438 log.Printf("Workspace Handler: %q\n", r.URL.Path)
439 if r.Method == "GET" {
440 tries := []Try{}
441 match := workspaceLink.FindStringSubmatch(r.URL.Path)
442 name := ""
443 if len(match) == 2 {
444 name = match[1]
commit-bot@chromium.orgc3b738a2014-04-21 17:36:44 +0000445 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 +0000446 if err != nil {
447 reportError(w, r, err, "Failed to select.")
448 return
449 }
450 for rows.Next() {
451 var hash string
452 var create_ts time.Time
453 if err := rows.Scan(&create_ts, &hash); err != nil {
454 log.Printf("Error: failed to fetch from database: %q", err)
455 continue
456 }
457 tries = append(tries, Try{Hash: hash, CreateTS: create_ts.Format("2006-02-01")})
458 }
459 }
460 var code string
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000461 var hash string
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000462 if len(tries) == 0 {
463 code = DEFAULT_SAMPLE
464 } else {
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000465 hash = tries[len(tries)-1].Hash
466 code, _ = getCode(hash)
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000467 }
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000468 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 +0000469 log.Printf("ERROR: Failed to expand template: %q\n", err)
470 }
471 } else if r.Method == "POST" {
472 name, err := newWorkspace()
473 if err != nil {
474 http.Error(w, "Failed to create a new workspace.", 500)
475 return
476 }
477 http.Redirect(w, r, "/w/"+name, 302)
478 }
479}
480
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000481// hasPreProcessor returns true if any line in the code begins with a # char.
482func hasPreProcessor(code string) bool {
483 lines := strings.Split(code, "\n")
484 for _, s := range lines {
485 if strings.HasPrefix(strings.TrimSpace(s), "#") {
486 return true
487 }
488 }
489 return false
490}
491
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000492type TryRequest struct {
493 Code string `json:"code"`
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000494 Name string `json:"name"` // Optional name of the workspace the code is in.
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000495}
496
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000497// iframeHandler handles the GET and POST of the main page.
498func iframeHandler(w http.ResponseWriter, r *http.Request) {
499 log.Printf("IFrame Handler: %q\n", r.URL.Path)
500 if r.Method != "GET" {
501 http.NotFound(w, r)
502 return
503 }
504 match := iframeLink.FindStringSubmatch(r.URL.Path)
505 if len(match) != 2 {
506 http.NotFound(w, r)
507 return
508 }
509 hash := match[1]
510 if db == nil {
511 http.NotFound(w, r)
512 return
513 }
514 var code string
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000515 code, err := getCode(hash)
516 if err != nil {
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000517 http.NotFound(w, r)
518 return
519 }
520 // Expand the template.
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000521 if err := iframeTemplate.Execute(w, userCode{Code: code, Hash: hash}); err != nil {
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000522 log.Printf("ERROR: Failed to expand template: %q\n", err)
523 }
524}
525
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000526type TryInfo struct {
527 Hash string `json:"hash"`
528 Code string `json:"code"`
529}
530
531// tryInfoHandler returns information about a specific try.
532func tryInfoHandler(w http.ResponseWriter, r *http.Request) {
533 log.Printf("Try Info Handler: %q\n", r.URL.Path)
534 if r.Method != "GET" {
535 http.NotFound(w, r)
536 return
537 }
538 match := tryInfoLink.FindStringSubmatch(r.URL.Path)
539 if len(match) != 2 {
540 http.NotFound(w, r)
541 return
542 }
543 hash := match[1]
544 code, err := getCode(hash)
545 if err != nil {
546 http.NotFound(w, r)
547 return
548 }
549 m := TryInfo{
550 Hash: hash,
551 Code: code,
552 }
553 resp, err := json.Marshal(m)
554 if err != nil {
555 reportError(w, r, err, "Failed to serialize a response.")
556 return
557 }
558 w.Header().Set("Content-Type", "application/json")
559 w.Write(resp)
560}
561
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000562func cleanCompileOutput(s, hash string) string {
563 old := "../../../cache/" + hash + ".cpp:"
564 log.Printf("INFO: replacing %q\n", old)
565 return strings.Replace(s, old, "usercode.cpp:", -1)
566}
567
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000568// mainHandler handles the GET and POST of the main page.
569func mainHandler(w http.ResponseWriter, r *http.Request) {
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000570 log.Printf("Main Handler: %q\n", r.URL.Path)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000571 if r.Method == "GET" {
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000572 code := DEFAULT_SAMPLE
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000573 match := directLink.FindStringSubmatch(r.URL.Path)
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000574 var hash string
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000575 if len(match) == 2 && r.URL.Path != "/" {
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000576 hash = match[1]
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000577 if db == nil {
578 http.NotFound(w, r)
579 return
580 }
581 // Update 'code' with the code found in the database.
582 if err := db.QueryRow("SELECT code FROM webtry WHERE hash=?", hash).Scan(&code); err != nil {
583 http.NotFound(w, r)
584 return
585 }
586 }
587 // Expand the template.
commit-bot@chromium.org472f8302014-04-28 15:33:31 +0000588 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 +0000589 log.Printf("ERROR: Failed to expand template: %q\n", err)
590 }
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000591 } else if r.Method == "POST" {
592 w.Header().Set("Content-Type", "application/json")
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000593 buf := bytes.NewBuffer(make([]byte, 0, MAX_TRY_SIZE))
594 n, err := buf.ReadFrom(r.Body)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000595 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000596 reportTryError(w, r, err, "Failed to read a request body.", "")
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000597 return
598 }
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000599 if n == MAX_TRY_SIZE {
600 err := fmt.Errorf("Code length equal to, or exceeded, %d", MAX_TRY_SIZE)
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000601 reportTryError(w, r, err, "Code too large.", "")
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000602 return
603 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000604 request := TryRequest{}
605 if err := json.Unmarshal(buf.Bytes(), &request); err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000606 reportTryError(w, r, err, "Coulnd't decode JSON.", "")
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000607 return
608 }
609 if hasPreProcessor(request.Code) {
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000610 err := fmt.Errorf("Found preprocessor macro in code.")
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000611 reportTryError(w, r, err, "Preprocessor macros aren't allowed.", "")
commit-bot@chromium.org4bd8fdc2014-04-15 00:43:51 +0000612 return
613 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000614 hash, err := expandCode(LineNumbers(request.Code))
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000615 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000616 reportTryError(w, r, err, "Failed to write the code to compile.", hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000617 return
618 }
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000619 writeToDatabase(hash, request.Code, request.Name)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000620 message, err := doCmd(fmt.Sprintf(RESULT_COMPILE, hash, hash), true)
621 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000622 message = cleanCompileOutput(message, hash)
623 reportTryError(w, r, err, message, hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000624 return
625 }
626 linkMessage, err := doCmd(fmt.Sprintf(LINK, hash, hash), true)
627 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000628 linkMessage = cleanCompileOutput(linkMessage, hash)
629 reportTryError(w, r, err, linkMessage, hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000630 return
631 }
632 message += linkMessage
633 cmd := hash + " --out " + hash + ".png"
634 if *useChroot {
635 cmd = "schroot -c webtry --directory=/inout -- /inout/" + cmd
636 } else {
637 abs, err := filepath.Abs("../../../inout")
638 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000639 reportTryError(w, r, err, "Failed to find executable directory.", hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000640 return
641 }
642 cmd = abs + "/" + cmd
643 }
644
645 execMessage, err := doCmd(cmd, false)
646 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000647 reportTryError(w, r, err, "Failed to run the code:\n"+execMessage, hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000648 return
649 }
650 png, err := ioutil.ReadFile("../../../inout/" + hash + ".png")
651 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000652 reportTryError(w, r, err, "Failed to open the generated PNG.", hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000653 return
654 }
655
656 m := response{
657 Message: message,
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000658 StdOut: execMessage,
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000659 Img: base64.StdEncoding.EncodeToString([]byte(png)),
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000660 Hash: hash,
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000661 }
662 resp, err := json.Marshal(m)
663 if err != nil {
commit-bot@chromium.org90041922014-04-22 21:13:45 +0000664 reportTryError(w, r, err, "Failed to serialize a response.", hash)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000665 return
666 }
667 w.Write(resp)
668 }
669}
670
671func main() {
672 flag.Parse()
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000673 http.HandleFunc("/i/", imageHandler)
commit-bot@chromium.orgd04e1dd2014-04-19 13:55:50 +0000674 http.HandleFunc("/w/", workspaceHandler)
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000675 http.HandleFunc("/recent/", recentHandler)
commit-bot@chromium.org2dceeda2014-04-19 14:50:23 +0000676 http.HandleFunc("/iframe/", iframeHandler)
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000677 http.HandleFunc("/json/", tryInfoHandler)
fmalita@google.com950306c2014-05-01 15:14:56 +0000678
679 // Resources are served directly
680 // TODO add support for caching/etags/gzip
681 http.Handle("/res/", http.FileServer(http.Dir("./")))
682
commit-bot@chromium.org35ffc442014-04-22 19:32:06 +0000683 // TODO Break out /c/ as it's own handler.
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000684 http.HandleFunc("/", mainHandler)
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000685 log.Fatal(http.ListenAndServe(*port, nil))
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000686}