blob: 008ea82929597925e497fee22ee4d75ce003e569 [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"
16 "net/http"
17 "os"
18 "os/exec"
19 "path/filepath"
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +000020 "regexp"
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000021 "strings"
22 "text/template"
commit-bot@chromium.org06aca012014-04-14 20:12:08 +000023 "time"
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000024)
25
26const (
27 RESULT_COMPILE = `c++ -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 -Wno-c++11-extensions -Werror -m64 -fno-rtti -Wnon-virtual-dtor -c ../../../cache/%s.cpp -o ../../../cache/%s.o`
commit-bot@chromium.orgd6cab4a2014-04-09 21:35:18 +000028 LINK = `c++ -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`
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +000029 DEFAULT_SAMPLE = `SkPaint p;
30p.setColor(SK_ColorRED);
31p.setAntiAlias(true);
32p.setStyle(SkPaint::kStroke_Style);
33p.setStrokeWidth(10);
34
35canvas->drawLine(20, 20, 100, 100, p);
36`
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000037)
38
39var (
40 // codeTemplate is the cpp code template the user's code is copied into.
41 codeTemplate *template.Template = nil
42
commit-bot@chromium.org06aca012014-04-14 20:12:08 +000043 // indexTemplate is the main index.html page we serve.
44 indexTemplate *htemplate.Template = nil
45
46 // recentTemplate is a list of recent images.
47 recentTemplate *htemplate.Template = nil
commit-bot@chromium.org282333f2014-04-14 14:54:07 +000048
49 // db is the database, nil if we don't have an SQL database to store data into.
50 db *sql.DB = nil
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +000051
52 // directLink is the regex that matches URLs paths that are direct links.
commit-bot@chromium.org06aca012014-04-14 20:12:08 +000053 directLink = regexp.MustCompile("^/c/([a-f0-9]+)$")
54
55 // imageLink is the regex that matches URLs paths that are direct links to PNGs.
56 imageLink = regexp.MustCompile("^/i/([a-f0-9]+.png)$")
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000057)
58
59// flags
60var (
61 useChroot = flag.Bool("use_chroot", false, "Run the compiled code in the schroot jail.")
commit-bot@chromium.org282333f2014-04-14 14:54:07 +000062 port = flag.String("port", ":8000", "HTTP service address (e.g., ':8000')")
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000063)
64
65// lineNumbers adds #line numbering to the user's code.
66func LineNumbers(c string) string {
67 lines := strings.Split(c, "\n")
68 ret := []string{}
69 for i, line := range lines {
70 ret = append(ret, fmt.Sprintf("#line %d", i+1))
71 ret = append(ret, line)
72 }
73 return strings.Join(ret, "\n")
74}
75
76func init() {
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +000077
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000078 // Change the current working directory to the directory of the executable.
79 var err error
80 cwd, err := filepath.Abs(filepath.Dir(os.Args[0]))
81 if err != nil {
82 log.Fatal(err)
83 }
84 os.Chdir(cwd)
85
86 codeTemplate, err = template.ParseFiles(filepath.Join(cwd, "templates/template.cpp"))
87 if err != nil {
88 panic(err)
89 }
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +000090 // Convert index.html into a template, which is expanded with the code.
commit-bot@chromium.org06aca012014-04-14 20:12:08 +000091 indexTemplate, err = htemplate.ParseFiles(filepath.Join(cwd, "templates/index.html"))
92 if err != nil {
93 panic(err)
94 }
95
96 recentTemplate, err = htemplate.ParseFiles(filepath.Join(cwd, "templates/recent.html"))
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +000097 if err != nil {
98 panic(err)
99 }
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000100
101 // Connect to MySQL server. First, get the password from the metadata server.
102 // See https://developers.google.com/compute/docs/metadata#custom.
103 req, err := http.NewRequest("GET", "http://metadata/computeMetadata/v1/instance/attributes/password", nil)
104 if err != nil {
105 panic(err)
106 }
107 client := http.Client{}
108 req.Header.Add("X-Google-Metadata-Request", "True")
109 if resp, err := client.Do(req); err == nil {
110 password, err := ioutil.ReadAll(resp.Body)
111 if err != nil {
112 log.Printf("ERROR: Failed to read password from metadata server: %q\n", err)
113 panic(err)
114 }
115 // The IP address of the database is found here:
116 // https://console.developers.google.com/project/31977622648/sql/instances/webtry/overview
117 // And 3306 is the default port for MySQL.
118 db, err = sql.Open("mysql", fmt.Sprintf("webtry:%s@tcp(173.194.83.52:3306)/webtry", password))
119 if err != nil {
120 log.Printf("ERROR: Failed to open connection to SQL server: %q\n", err)
121 panic(err)
122 }
123 } else {
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000124 // Fallback to sqlite for local use.
125 db, err = sql.Open("sqlite3", "./webtry.db")
126 if err != nil {
127 log.Printf("ERROR: Failed to open: %q\n", err)
128 panic(err)
129 }
130 sql := `CREATE TABLE webtry (
131 code TEXT DEFAULT '' NOT NULL,
132 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
133 hash CHAR(64) DEFAULT '' NOT NULL,
134 PRIMARY KEY(hash)
135 )`
136 db.Exec(sql)
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000137 log.Printf("INFO: Failed to find metadata, unable to connect to MySQL server (Expected when running locally): %q\n", err)
138 }
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000139}
140
141// userCode is used in template expansion.
142type userCode struct {
143 UserCode string
144}
145
146// expandToFile expands the template and writes the result to the file.
147func expandToFile(filename string, code string, t *template.Template) error {
148 f, err := os.Create(filename)
149 if err != nil {
150 return err
151 }
152 defer f.Close()
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000153 return t.Execute(f, userCode{UserCode: code})
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000154}
155
156// expandCode expands the template into a file and calculate the MD5 hash.
157func expandCode(code string) (string, error) {
158 h := md5.New()
159 h.Write([]byte(code))
160 hash := fmt.Sprintf("%x", h.Sum(nil))
161 // At this point we are running in skia/experimental/webtry, making cache a
162 // peer directory to skia.
163 // TODO(jcgregorio) Make all relative directories into flags.
164 err := expandToFile(fmt.Sprintf("../../../cache/%s.cpp", hash), code, codeTemplate)
165 return hash, err
166}
167
168// response is serialized to JSON as a response to POSTs.
169type response struct {
170 Message string `json:"message"`
171 Img string `json:"img"`
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000172 Hash string `json:"hash"`
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000173}
174
175// doCmd executes the given command line string in either the out/Debug
176// directory or the inout directory. Returns the stdout, and stderr in the case
177// of a non-zero exit code.
178func doCmd(commandLine string, moveToDebug bool) (string, error) {
179 log.Printf("Command: %q\n", commandLine)
180 programAndArgs := strings.SplitN(commandLine, " ", 2)
181 program := programAndArgs[0]
182 args := []string{}
183 if len(programAndArgs) > 1 {
184 args = strings.Split(programAndArgs[1], " ")
185 }
186 cmd := exec.Command(program, args...)
187 abs, err := filepath.Abs("../../out/Debug")
188 if err != nil {
189 return "", fmt.Errorf("Failed to find absolute path to Debug directory.")
190 }
191 if moveToDebug {
192 cmd.Dir = abs
193 } else if !*useChroot { // Don't set cmd.Dir when using chroot.
194 abs, err := filepath.Abs("../../../inout")
195 if err != nil {
196 return "", fmt.Errorf("Failed to find absolute path to inout directory.")
197 }
198 cmd.Dir = abs
199 }
200 log.Printf("Run in directory: %q\n", cmd.Dir)
201 var stdOut bytes.Buffer
202 cmd.Stdout = &stdOut
203 var stdErr bytes.Buffer
204 cmd.Stderr = &stdErr
205 cmd.Start()
206 err = cmd.Wait()
207 message := stdOut.String()
208 log.Printf("StdOut: %s\n", message)
209 if err != nil {
210 log.Printf("Exit status: %s\n", err.Error())
211 log.Printf("StdErr: %s\n", stdErr.String())
212 message += stdErr.String()
213 return message, fmt.Errorf("Failed to run command.")
214 }
215 return message, nil
216}
217
218// reportError formats an HTTP error response and also logs the detailed error message.
219func reportError(w http.ResponseWriter, r *http.Request, err error, message string) {
220 m := response{
221 Message: message,
222 }
223 log.Printf("Error: %s\n%s", message, err.Error())
224 resp, err := json.Marshal(m)
225 if err != nil {
226 http.Error(w, "Failed to serialize a response", 500)
227 return
228 }
229 w.Write(resp)
230}
231
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000232func writeToDatabase(hash string, code string) {
233 if db == nil {
234 return
235 }
236 if _, err := db.Exec("INSERT INTO webtry (code, hash) VALUES(?, ?)", code, hash); err != nil {
237 log.Printf("ERROR: Failed to insert code into database: %q\n", err)
238 }
239}
240
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000241func cssHandler(w http.ResponseWriter, r *http.Request) {
242 http.ServeFile(w, r, "css/webtry.css")
243}
244
245// imageHandler serves up the PNG of a specific try.
246func imageHandler(w http.ResponseWriter, r *http.Request) {
247 log.Printf("Image Handler: %q\n", r.URL.Path)
248 if r.Method != "GET" {
249 http.NotFound(w, r)
250 return
251 }
252 match := imageLink.FindStringSubmatch(r.URL.Path)
253 if len(match) != 2 {
254 http.NotFound(w, r)
255 return
256 }
257 filename := match[1]
258 http.ServeFile(w, r, fmt.Sprintf("../../../inout/%s", filename))
259}
260
261type Try struct {
262 Hash string
263 CreateTS string
264}
265
266type Recent struct {
267 Tries []Try
268}
269
270// recentHandler shows the last 20 tries.
271func recentHandler(w http.ResponseWriter, r *http.Request) {
272 log.Printf("Recent Handler: %q\n", r.URL.Path)
273
274 var err error
275 rows, err := db.Query("SELECT create_ts, hash FROM webtry ORDER BY create_ts DESC LIMIT 20")
276 if err != nil {
277 http.NotFound(w, r)
278 return
279 }
280 recent := []Try{}
281 for rows.Next() {
282 var hash string
283 var create_ts time.Time
284 if err := rows.Scan(&create_ts, &hash); err != nil {
285 log.Printf("Error: failed to fetch from database: %q", err)
286 continue
287 }
288 recent = append(recent, Try{Hash: hash, CreateTS: create_ts.Format("2006-02-01")})
289 }
290 if err := recentTemplate.Execute(w, Recent{Tries: recent}); err != nil {
291 log.Printf("ERROR: Failed to expand template: %q\n", err)
292 }
293}
294
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000295// mainHandler handles the GET and POST of the main page.
296func mainHandler(w http.ResponseWriter, r *http.Request) {
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000297 log.Printf("Main Handler: %q\n", r.URL.Path)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000298 if r.Method == "GET" {
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000299 code := DEFAULT_SAMPLE
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000300 match := directLink.FindStringSubmatch(r.URL.Path)
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000301 if len(match) == 2 && r.URL.Path != "/" {
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000302 hash := match[1]
303 if db == nil {
304 http.NotFound(w, r)
305 return
306 }
307 // Update 'code' with the code found in the database.
308 if err := db.QueryRow("SELECT code FROM webtry WHERE hash=?", hash).Scan(&code); err != nil {
309 http.NotFound(w, r)
310 return
311 }
312 }
313 // Expand the template.
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000314 if err := indexTemplate.Execute(w, userCode{UserCode: code}); err != nil {
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000315 log.Printf("ERROR: Failed to expand template: %q\n", err)
316 }
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000317 } else if r.Method == "POST" {
318 w.Header().Set("Content-Type", "application/json")
319 b, err := ioutil.ReadAll(r.Body)
320 if err != nil {
321 reportError(w, r, err, "Failed to read a request body.")
322 return
323 }
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000324 code := string(b)
325 hash, err := expandCode(LineNumbers(code))
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000326 if err != nil {
327 reportError(w, r, err, "Failed to write the code to compile.")
328 return
329 }
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000330 writeToDatabase(hash, code)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000331 message, err := doCmd(fmt.Sprintf(RESULT_COMPILE, hash, hash), true)
332 if err != nil {
333 reportError(w, r, err, "Failed to compile the code:\n"+message)
334 return
335 }
336 linkMessage, err := doCmd(fmt.Sprintf(LINK, hash, hash), true)
337 if err != nil {
338 reportError(w, r, err, "Failed to link the code:\n"+linkMessage)
339 return
340 }
341 message += linkMessage
342 cmd := hash + " --out " + hash + ".png"
343 if *useChroot {
344 cmd = "schroot -c webtry --directory=/inout -- /inout/" + cmd
345 } else {
346 abs, err := filepath.Abs("../../../inout")
347 if err != nil {
348 reportError(w, r, err, "Failed to find executable directory.")
349 return
350 }
351 cmd = abs + "/" + cmd
352 }
353
354 execMessage, err := doCmd(cmd, false)
355 if err != nil {
356 reportError(w, r, err, "Failed to run the code:\n"+execMessage)
357 return
358 }
359 png, err := ioutil.ReadFile("../../../inout/" + hash + ".png")
360 if err != nil {
361 reportError(w, r, err, "Failed to open the generated PNG.")
362 return
363 }
364
365 m := response{
366 Message: message,
367 Img: base64.StdEncoding.EncodeToString([]byte(png)),
commit-bot@chromium.orgc81d1c42014-04-14 18:53:10 +0000368 Hash: hash,
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000369 }
370 resp, err := json.Marshal(m)
371 if err != nil {
372 reportError(w, r, err, "Failed to serialize a response.")
373 return
374 }
375 w.Write(resp)
376 }
377}
378
379func main() {
380 flag.Parse()
commit-bot@chromium.org06aca012014-04-14 20:12:08 +0000381 http.HandleFunc("/i/", imageHandler)
382 http.HandleFunc("/recent/", recentHandler)
383 http.HandleFunc("/css/", cssHandler)
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000384 http.HandleFunc("/", mainHandler)
commit-bot@chromium.org282333f2014-04-14 14:54:07 +0000385 log.Fatal(http.ListenAndServe(*port, nil))
commit-bot@chromium.org6d036c22014-04-09 18:59:44 +0000386}