| OLD | NEW |
| 1 package main | 1 package main |
| 2 | 2 |
| 3 import ( | 3 import ( |
| 4 "bytes" | 4 "bytes" |
| 5 "crypto/md5" | 5 "crypto/md5" |
| 6 "database/sql" | 6 "database/sql" |
| 7 "encoding/base64" | 7 "encoding/base64" |
| 8 "encoding/json" | 8 "encoding/json" |
| 9 "flag" | 9 "flag" |
| 10 "fmt" | 10 "fmt" |
| 11 _ "github.com/go-sql-driver/mysql" | 11 _ "github.com/go-sql-driver/mysql" |
| 12 _ "github.com/mattn/go-sqlite3" |
| 13 htemplate "html/template" |
| 12 "io/ioutil" | 14 "io/ioutil" |
| 13 "log" | 15 "log" |
| 14 "net/http" | 16 "net/http" |
| 15 "os" | 17 "os" |
| 16 "os/exec" | 18 "os/exec" |
| 17 "path/filepath" | 19 "path/filepath" |
| 20 "regexp" |
| 18 "strings" | 21 "strings" |
| 19 "text/template" | 22 "text/template" |
| 20 ) | 23 ) |
| 21 | 24 |
| 22 const ( | 25 const ( |
| 23 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 -D
SK_SUPPORT_OPENCL=0 -DSK_FORCE_DISTANCEFIELD_FONTS=0 -DSK_SCALAR_IS_FLOAT -DSK_C
AN_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/pa
thops -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-unu
sed-parameter -Wno-c++11-extensions -Werror -m64 -fno-rtti -Wnon-virtual-dtor -c
../../../cache/%s.cpp -o ../../../cache/%s.o` | 26 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 -D
SK_SUPPORT_OPENCL=0 -DSK_FORCE_DISTANCEFIELD_FONTS=0 -DSK_SCALAR_IS_FLOAT -DSK_C
AN_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/pa
thops -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-unu
sed-parameter -Wno-c++11-extensions -Werror -m64 -fno-rtti -Wnon-virtual-dtor -c
../../../cache/%s.cpp -o ../../../cache/%s.o` |
| 24 LINK = `c++ -m64 -lstdc++ -lm -o ../../../inout/%s -Wl,--start
-group ../../../cache/%s.o obj/experimental/webtry/webtry.main.o obj/gyp/libflag
s.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 li
bskia_ports.a libskia_sfnt.a -Wl,--end-group -lpng -lz -lgif -lpthread -lfontcon
fig -ldl -lfreetype` | 27 LINK = `c++ -m64 -lstdc++ -lm -o ../../../inout/%s -Wl,--start
-group ../../../cache/%s.o obj/experimental/webtry/webtry.main.o obj/gyp/libflag
s.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 li
bskia_ports.a libskia_sfnt.a -Wl,--end-group -lpng -lz -lgif -lpthread -lfontcon
fig -ldl -lfreetype` |
| 28 DEFAULT_SAMPLE = `SkPaint p; |
| 29 p.setColor(SK_ColorRED); |
| 30 p.setAntiAlias(true); |
| 31 p.setStyle(SkPaint::kStroke_Style); |
| 32 p.setStrokeWidth(10); |
| 33 |
| 34 canvas->drawLine(20, 20, 100, 100, p); |
| 35 ` |
| 25 ) | 36 ) |
| 26 | 37 |
| 27 var ( | 38 var ( |
| 28 // codeTemplate is the cpp code template the user's code is copied into. | 39 // codeTemplate is the cpp code template the user's code is copied into. |
| 29 codeTemplate *template.Template = nil | 40 codeTemplate *template.Template = nil |
| 30 | 41 |
| 31 // index is the main index.html page we serve. | 42 // index is the main index.html page we serve. |
| 32 » index []byte | 43 » index *htemplate.Template = nil |
| 33 | 44 |
| 34 // db is the database, nil if we don't have an SQL database to store dat
a into. | 45 // db is the database, nil if we don't have an SQL database to store dat
a into. |
| 35 db *sql.DB = nil | 46 db *sql.DB = nil |
| 47 |
| 48 // directLink is the regex that matches URLs paths that are direct links
. |
| 49 directLink = regexp.MustCompile("^c/([a-a0-9]+)$") |
| 36 ) | 50 ) |
| 37 | 51 |
| 38 // flags | 52 // flags |
| 39 var ( | 53 var ( |
| 40 useChroot = flag.Bool("use_chroot", false, "Run the compiled code in the
schroot jail.") | 54 useChroot = flag.Bool("use_chroot", false, "Run the compiled code in the
schroot jail.") |
| 41 port = flag.String("port", ":8000", "HTTP service address (e.g., ':
8000')") | 55 port = flag.String("port", ":8000", "HTTP service address (e.g., ':
8000')") |
| 42 ) | 56 ) |
| 43 | 57 |
| 44 // lineNumbers adds #line numbering to the user's code. | 58 // lineNumbers adds #line numbering to the user's code. |
| 45 func LineNumbers(c string) string { | 59 func LineNumbers(c string) string { |
| 46 lines := strings.Split(c, "\n") | 60 lines := strings.Split(c, "\n") |
| 47 ret := []string{} | 61 ret := []string{} |
| 48 for i, line := range lines { | 62 for i, line := range lines { |
| 49 ret = append(ret, fmt.Sprintf("#line %d", i+1)) | 63 ret = append(ret, fmt.Sprintf("#line %d", i+1)) |
| 50 ret = append(ret, line) | 64 ret = append(ret, line) |
| 51 } | 65 } |
| 52 return strings.Join(ret, "\n") | 66 return strings.Join(ret, "\n") |
| 53 } | 67 } |
| 54 | 68 |
| 55 func init() { | 69 func init() { |
| 70 |
| 56 // Change the current working directory to the directory of the executab
le. | 71 // Change the current working directory to the directory of the executab
le. |
| 57 var err error | 72 var err error |
| 58 cwd, err := filepath.Abs(filepath.Dir(os.Args[0])) | 73 cwd, err := filepath.Abs(filepath.Dir(os.Args[0])) |
| 59 if err != nil { | 74 if err != nil { |
| 60 log.Fatal(err) | 75 log.Fatal(err) |
| 61 } | 76 } |
| 62 os.Chdir(cwd) | 77 os.Chdir(cwd) |
| 63 | 78 |
| 64 codeTemplate, err = template.ParseFiles(filepath.Join(cwd, "templates/te
mplate.cpp")) | 79 codeTemplate, err = template.ParseFiles(filepath.Join(cwd, "templates/te
mplate.cpp")) |
| 65 if err != nil { | 80 if err != nil { |
| 66 panic(err) | 81 panic(err) |
| 67 } | 82 } |
| 68 » index, err = ioutil.ReadFile(filepath.Join(cwd, "templates/index.html")) | 83 » // Convert index.html into a template, which is expanded with the code. |
| 84 » index, err = htemplate.ParseFiles(filepath.Join(cwd, "templates/index.ht
ml")) |
| 69 if err != nil { | 85 if err != nil { |
| 70 panic(err) | 86 panic(err) |
| 71 } | 87 } |
| 72 | 88 |
| 73 // Connect to MySQL server. First, get the password from the metadata se
rver. | 89 // Connect to MySQL server. First, get the password from the metadata se
rver. |
| 74 // See https://developers.google.com/compute/docs/metadata#custom. | 90 // See https://developers.google.com/compute/docs/metadata#custom. |
| 75 req, err := http.NewRequest("GET", "http://metadata/computeMetadata/v1/i
nstance/attributes/password", nil) | 91 req, err := http.NewRequest("GET", "http://metadata/computeMetadata/v1/i
nstance/attributes/password", nil) |
| 76 if err != nil { | 92 if err != nil { |
| 77 panic(err) | 93 panic(err) |
| 78 } | 94 } |
| 79 client := http.Client{} | 95 client := http.Client{} |
| 80 req.Header.Add("X-Google-Metadata-Request", "True") | 96 req.Header.Add("X-Google-Metadata-Request", "True") |
| 81 if resp, err := client.Do(req); err == nil { | 97 if resp, err := client.Do(req); err == nil { |
| 82 password, err := ioutil.ReadAll(resp.Body) | 98 password, err := ioutil.ReadAll(resp.Body) |
| 83 if err != nil { | 99 if err != nil { |
| 84 log.Printf("ERROR: Failed to read password from metadata
server: %q\n", err) | 100 log.Printf("ERROR: Failed to read password from metadata
server: %q\n", err) |
| 85 panic(err) | 101 panic(err) |
| 86 } | 102 } |
| 87 // The IP address of the database is found here: | 103 // The IP address of the database is found here: |
| 88 // https://console.developers.google.com/project/31977622648/
sql/instances/webtry/overview | 104 // https://console.developers.google.com/project/31977622648/
sql/instances/webtry/overview |
| 89 // And 3306 is the default port for MySQL. | 105 // And 3306 is the default port for MySQL. |
| 90 db, err = sql.Open("mysql", fmt.Sprintf("webtry:%s@tcp(173.194.8
3.52:3306)/webtry", password)) | 106 db, err = sql.Open("mysql", fmt.Sprintf("webtry:%s@tcp(173.194.8
3.52:3306)/webtry", password)) |
| 91 if err != nil { | 107 if err != nil { |
| 92 log.Printf("ERROR: Failed to open connection to SQL serv
er: %q\n", err) | 108 log.Printf("ERROR: Failed to open connection to SQL serv
er: %q\n", err) |
| 93 panic(err) | 109 panic(err) |
| 94 } | 110 } |
| 95 } else { | 111 } else { |
| 112 // Fallback to sqlite for local use. |
| 113 db, err = sql.Open("sqlite3", "./webtry.db") |
| 114 if err != nil { |
| 115 log.Printf("ERROR: Failed to open: %q\n", err) |
| 116 panic(err) |
| 117 } |
| 118 sql := `CREATE TABLE webtry ( |
| 119 code TEXT DEFAULT '' NOT NULL, |
| 120 create_ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, |
| 121 hash CHAR(64) DEFAULT '' NOT NULL, |
| 122 PRIMARY KEY(hash) |
| 123 )` |
| 124 db.Exec(sql) |
| 96 log.Printf("INFO: Failed to find metadata, unable to connect to
MySQL server (Expected when running locally): %q\n", err) | 125 log.Printf("INFO: Failed to find metadata, unable to connect to
MySQL server (Expected when running locally): %q\n", err) |
| 97 } | 126 } |
| 98 } | 127 } |
| 99 | 128 |
| 100 // userCode is used in template expansion. | 129 // userCode is used in template expansion. |
| 101 type userCode struct { | 130 type userCode struct { |
| 102 UserCode string | 131 UserCode string |
| 103 } | 132 } |
| 104 | 133 |
| 105 // expandToFile expands the template and writes the result to the file. | 134 // expandToFile expands the template and writes the result to the file. |
| 106 func expandToFile(filename string, code string, t *template.Template) error { | 135 func expandToFile(filename string, code string, t *template.Template) error { |
| 107 f, err := os.Create(filename) | 136 f, err := os.Create(filename) |
| 108 if err != nil { | 137 if err != nil { |
| 109 return err | 138 return err |
| 110 } | 139 } |
| 111 defer f.Close() | 140 defer f.Close() |
| 112 » return t.Execute(f, struct{ UserCode string }{UserCode: code}) | 141 » return t.Execute(f, userCode{UserCode: code}) |
| 113 } | 142 } |
| 114 | 143 |
| 115 // expandCode expands the template into a file and calculate the MD5 hash. | 144 // expandCode expands the template into a file and calculate the MD5 hash. |
| 116 func expandCode(code string) (string, error) { | 145 func expandCode(code string) (string, error) { |
| 117 h := md5.New() | 146 h := md5.New() |
| 118 h.Write([]byte(code)) | 147 h.Write([]byte(code)) |
| 119 hash := fmt.Sprintf("%x", h.Sum(nil)) | 148 hash := fmt.Sprintf("%x", h.Sum(nil)) |
| 120 // At this point we are running in skia/experimental/webtry, making cach
e a | 149 // At this point we are running in skia/experimental/webtry, making cach
e a |
| 121 // peer directory to skia. | 150 // peer directory to skia. |
| 122 // TODO(jcgregorio) Make all relative directories into flags. | 151 // TODO(jcgregorio) Make all relative directories into flags. |
| 123 err := expandToFile(fmt.Sprintf("../../../cache/%s.cpp", hash), code, co
deTemplate) | 152 err := expandToFile(fmt.Sprintf("../../../cache/%s.cpp", hash), code, co
deTemplate) |
| 124 return hash, err | 153 return hash, err |
| 125 } | 154 } |
| 126 | 155 |
| 127 // response is serialized to JSON as a response to POSTs. | 156 // response is serialized to JSON as a response to POSTs. |
| 128 type response struct { | 157 type response struct { |
| 129 Message string `json:"message"` | 158 Message string `json:"message"` |
| 130 Img string `json:"img"` | 159 Img string `json:"img"` |
| 160 Hash string `json:"hash"` |
| 131 } | 161 } |
| 132 | 162 |
| 133 // doCmd executes the given command line string in either the out/Debug | 163 // doCmd executes the given command line string in either the out/Debug |
| 134 // directory or the inout directory. Returns the stdout, and stderr in the case | 164 // directory or the inout directory. Returns the stdout, and stderr in the case |
| 135 // of a non-zero exit code. | 165 // of a non-zero exit code. |
| 136 func doCmd(commandLine string, moveToDebug bool) (string, error) { | 166 func doCmd(commandLine string, moveToDebug bool) (string, error) { |
| 137 log.Printf("Command: %q\n", commandLine) | 167 log.Printf("Command: %q\n", commandLine) |
| 138 programAndArgs := strings.SplitN(commandLine, " ", 2) | 168 programAndArgs := strings.SplitN(commandLine, " ", 2) |
| 139 program := programAndArgs[0] | 169 program := programAndArgs[0] |
| 140 args := []string{} | 170 args := []string{} |
| (...skipping 51 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 192 return | 222 return |
| 193 } | 223 } |
| 194 if _, err := db.Exec("INSERT INTO webtry (code, hash) VALUES(?, ?)", cod
e, hash); err != nil { | 224 if _, err := db.Exec("INSERT INTO webtry (code, hash) VALUES(?, ?)", cod
e, hash); err != nil { |
| 195 log.Printf("ERROR: Failed to insert code into database: %q\n", e
rr) | 225 log.Printf("ERROR: Failed to insert code into database: %q\n", e
rr) |
| 196 } | 226 } |
| 197 } | 227 } |
| 198 | 228 |
| 199 // mainHandler handles the GET and POST of the main page. | 229 // mainHandler handles the GET and POST of the main page. |
| 200 func mainHandler(w http.ResponseWriter, r *http.Request) { | 230 func mainHandler(w http.ResponseWriter, r *http.Request) { |
| 201 if r.Method == "GET" { | 231 if r.Method == "GET" { |
| 202 » » w.Write(index) | 232 » » code := DEFAULT_SAMPLE |
| 233 » » directLink := regexp.MustCompile("^/c/([a-f0-9]+)$") |
| 234 » » match := directLink.FindStringSubmatch(r.URL.Path) |
| 235 » » if len(match) == 2 { |
| 236 » » » hash := match[1] |
| 237 » » » if db == nil { |
| 238 » » » » http.NotFound(w, r) |
| 239 » » » » return |
| 240 » » » } |
| 241 » » » // Update 'code' with the code found in the database. |
| 242 » » » if err := db.QueryRow("SELECT code FROM webtry WHERE has
h=?", hash).Scan(&code); err != nil { |
| 243 » » » » http.NotFound(w, r) |
| 244 » » » » return |
| 245 » » » } |
| 246 » » } |
| 247 » » // Expand the template. |
| 248 » » if err := index.Execute(w, userCode{UserCode: code}); err != nil
{ |
| 249 » » » log.Printf("ERROR: Failed to expand template: %q\n", err
) |
| 250 » » } |
| 203 } else if r.Method == "POST" { | 251 } else if r.Method == "POST" { |
| 204 w.Header().Set("Content-Type", "application/json") | 252 w.Header().Set("Content-Type", "application/json") |
| 205 b, err := ioutil.ReadAll(r.Body) | 253 b, err := ioutil.ReadAll(r.Body) |
| 206 if err != nil { | 254 if err != nil { |
| 207 reportError(w, r, err, "Failed to read a request body.") | 255 reportError(w, r, err, "Failed to read a request body.") |
| 208 return | 256 return |
| 209 } | 257 } |
| 210 code := string(b) | 258 code := string(b) |
| 211 hash, err := expandCode(LineNumbers(code)) | 259 hash, err := expandCode(LineNumbers(code)) |
| 212 if err != nil { | 260 if err != nil { |
| (...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 244 } | 292 } |
| 245 png, err := ioutil.ReadFile("../../../inout/" + hash + ".png") | 293 png, err := ioutil.ReadFile("../../../inout/" + hash + ".png") |
| 246 if err != nil { | 294 if err != nil { |
| 247 reportError(w, r, err, "Failed to open the generated PNG
.") | 295 reportError(w, r, err, "Failed to open the generated PNG
.") |
| 248 return | 296 return |
| 249 } | 297 } |
| 250 | 298 |
| 251 m := response{ | 299 m := response{ |
| 252 Message: message, | 300 Message: message, |
| 253 Img: base64.StdEncoding.EncodeToString([]byte(png)), | 301 Img: base64.StdEncoding.EncodeToString([]byte(png)), |
| 302 Hash: hash, |
| 254 } | 303 } |
| 255 resp, err := json.Marshal(m) | 304 resp, err := json.Marshal(m) |
| 256 if err != nil { | 305 if err != nil { |
| 257 reportError(w, r, err, "Failed to serialize a response."
) | 306 reportError(w, r, err, "Failed to serialize a response."
) |
| 258 return | 307 return |
| 259 } | 308 } |
| 260 w.Write(resp) | 309 w.Write(resp) |
| 261 } | 310 } |
| 262 } | 311 } |
| 263 | 312 |
| 264 func main() { | 313 func main() { |
| 265 flag.Parse() | 314 flag.Parse() |
| 266 | 315 |
| 267 http.HandleFunc("/", mainHandler) | 316 http.HandleFunc("/", mainHandler) |
| 268 log.Fatal(http.ListenAndServe(*port, nil)) | 317 log.Fatal(http.ListenAndServe(*port, nil)) |
| 269 } | 318 } |
| OLD | NEW |