1 // Copyright 2011 Google Inc. All rights reserved.
2 // Use of this source code is governed by the Apache 2.0
3 // license that can be found in the LICENSE file.
26 "github.com/golang/protobuf/proto"
27 netcontext "golang.org/x/net/context"
29 basepb "google.golang.org/appengine/internal/base"
30 logpb "google.golang.org/appengine/internal/log"
31 remotepb "google.golang.org/appengine/internal/remote_api"
36 defaultTicketSuffix = "/default.20150612t184001.0"
41 ticketHeader = http.CanonicalHeaderKey("X-AppEngine-API-Ticket")
42 dapperHeader = http.CanonicalHeaderKey("X-Google-DapperTraceInfo")
43 traceHeader = http.CanonicalHeaderKey("X-Cloud-Trace-Context")
44 curNamespaceHeader = http.CanonicalHeaderKey("X-AppEngine-Current-Namespace")
45 userIPHeader = http.CanonicalHeaderKey("X-AppEngine-User-IP")
46 remoteAddrHeader = http.CanonicalHeaderKey("X-AppEngine-Remote-Addr")
47 devRequestIdHeader = http.CanonicalHeaderKey("X-Appengine-Dev-Request-Id")
50 apiEndpointHeader = http.CanonicalHeaderKey("X-Google-RPC-Service-Endpoint")
51 apiEndpointHeaderValue = []string{"app-engine-apis"}
52 apiMethodHeader = http.CanonicalHeaderKey("X-Google-RPC-Service-Method")
53 apiMethodHeaderValue = []string{"/VMRemoteAPI.CallRemoteAPI"}
54 apiDeadlineHeader = http.CanonicalHeaderKey("X-Google-RPC-Service-Deadline")
55 apiContentType = http.CanonicalHeaderKey("Content-Type")
56 apiContentTypeValue = []string{"application/octet-stream"}
57 logFlushHeader = http.CanonicalHeaderKey("X-AppEngine-Log-Flush-Count")
59 apiHTTPClient = &http.Client{
60 Transport: &http.Transport{
61 Proxy: http.ProxyFromEnvironment,
66 defaultTicketOnce sync.Once
68 backgroundContextOnce sync.Once
69 backgroundContext netcontext.Context
72 func apiURL() *url.URL {
73 host, port := "appengine.googleapis.internal", "10001"
74 if h := os.Getenv("API_HOST"); h != "" {
77 if p := os.Getenv("API_PORT"); p != "" {
82 Host: host + ":" + port,
87 func handleHTTP(w http.ResponseWriter, r *http.Request) {
90 outHeader: w.Header(),
93 r = r.WithContext(withContext(r.Context(), c))
96 stopFlushing := make(chan int)
98 // Patch up RemoteAddr so it looks reasonable.
99 if addr := r.Header.Get(userIPHeader); addr != "" {
101 } else if addr = r.Header.Get(remoteAddrHeader); addr != "" {
104 // Should not normally reach here, but pick a sensible default anyway.
105 r.RemoteAddr = "127.0.0.1"
107 // The address in the headers will most likely be of these forms:
110 // net/http.Request.RemoteAddr is specified to be in "IP:port" form.
111 if _, _, err := net.SplitHostPort(r.RemoteAddr); err != nil {
112 // Assume the remote address is only a host; add a default port.
113 r.RemoteAddr = net.JoinHostPort(r.RemoteAddr, "80")
116 // Start goroutine responsible for flushing app logs.
117 // This is done after adding c to ctx.m (and stopped before removing it)
118 // because flushing logs requires making an API call.
119 go c.logFlusher(stopFlushing)
121 executeRequestSafely(c, r)
122 c.outHeader = nil // make sure header changes aren't respected any more
124 stopFlushing <- 1 // any logging beyond this point will be dropped
126 // Flush any pending logs asynchronously.
128 flushes := c.pendingLogs.flushes
129 if len(c.pendingLogs.lines) > 0 {
132 c.pendingLogs.Unlock()
133 flushed := make(chan struct{})
136 // Force a log flush, because with very short requests we
137 // may not ever flush logs.
140 w.Header().Set(logFlushHeader, strconv.Itoa(flushes))
142 // Avoid nil Write call if c.Write is never called.
144 w.WriteHeader(c.outCode)
146 if c.outBody != nil {
149 // Wait for the last flush to complete before returning,
150 // otherwise the security ticket will not be valid.
154 func executeRequestSafely(c *context, r *http.Request) {
156 if x := recover(); x != nil {
157 logf(c, 4, "%s", renderPanic(x)) // 4 == critical
162 http.DefaultServeMux.ServeHTTP(c, r)
165 func renderPanic(x interface{}) string {
166 buf := make([]byte, 16<<10) // 16 KB should be plenty
167 buf = buf[:runtime.Stack(buf, false)]
169 // Remove the first few stack frames:
171 // the recover closure in the caller
172 // That will root the stack trace at the site of the panic.
174 skipStart = "internal.renderPanic"
177 start := bytes.Index(buf, []byte(skipStart))
179 for i := 0; i < skipFrames*2 && p+1 < len(buf); i++ {
180 p = bytes.IndexByte(buf[p+1:], '\n') + p + 1
186 // buf[start:p+1] is the block to remove.
187 // Copy buf[p+1:] over buf[start:] and shrink buf.
188 copy(buf[start:], buf[p+1:])
189 buf = buf[:len(buf)-(p+1-start)]
192 // Add panic heading.
193 head := fmt.Sprintf("panic: %v\n\n", x)
194 if len(head) > len(buf) {
195 // Extremely unlikely to happen.
198 copy(buf[len(head):], buf)
204 // context represents the context of an in-flight HTTP request.
205 // It implements the appengine.Context and http.ResponseWriter interfaces.
206 type context struct {
210 outHeader http.Header
215 lines []*logpb.UserAppLogLine
222 var contextKey = "holds a *context"
224 // jointContext joins two contexts in a superficial way.
225 // It takes values and timeouts from a base context, and only values from another context.
226 type jointContext struct {
227 base netcontext.Context
228 valuesOnly netcontext.Context
231 func (c jointContext) Deadline() (time.Time, bool) {
232 return c.base.Deadline()
235 func (c jointContext) Done() <-chan struct{} {
239 func (c jointContext) Err() error {
243 func (c jointContext) Value(key interface{}) interface{} {
244 if val := c.base.Value(key); val != nil {
247 return c.valuesOnly.Value(key)
250 // fromContext returns the App Engine context or nil if ctx is not
251 // derived from an App Engine context.
252 func fromContext(ctx netcontext.Context) *context {
253 c, _ := ctx.Value(&contextKey).(*context)
257 func withContext(parent netcontext.Context, c *context) netcontext.Context {
258 ctx := netcontext.WithValue(parent, &contextKey, c)
259 if ns := c.req.Header.Get(curNamespaceHeader); ns != "" {
260 ctx = withNamespace(ctx, ns)
265 func toContext(c *context) netcontext.Context {
266 return withContext(netcontext.Background(), c)
269 func IncomingHeaders(ctx netcontext.Context) http.Header {
270 if c := fromContext(ctx); c != nil {
276 func ReqContext(req *http.Request) netcontext.Context {
280 func WithContext(parent netcontext.Context, req *http.Request) netcontext.Context {
283 valuesOnly: req.Context(),
287 // DefaultTicket returns a ticket used for background context or dev_appserver.
288 func DefaultTicket() string {
289 defaultTicketOnce.Do(func() {
290 if IsDevAppServer() {
291 defaultTicket = "testapp" + defaultTicketSuffix
294 appID := partitionlessAppID()
295 escAppID := strings.Replace(strings.Replace(appID, ":", "_", -1), ".", "_", -1)
296 majVersion := VersionID(nil)
297 if i := strings.Index(majVersion, "."); i > 0 {
298 majVersion = majVersion[:i]
300 defaultTicket = fmt.Sprintf("%s/%s.%s.%s", escAppID, ModuleName(nil), majVersion, InstanceID())
305 func BackgroundContext() netcontext.Context {
306 backgroundContextOnce.Do(func() {
307 // Compute background security ticket.
308 ticket := DefaultTicket()
313 ticketHeader: []string{ticket},
318 backgroundContext = toContext(c)
320 // TODO(dsymonds): Wire up the shutdown handler to do a final flush.
321 go c.logFlusher(make(chan int))
324 return backgroundContext
327 // RegisterTestRequest registers the HTTP request req for testing, such that
328 // any API calls are sent to the provided URL. It returns a closure to delete
330 // It should only be used by aetest package.
331 func RegisterTestRequest(req *http.Request, apiURL *url.URL, decorate func(netcontext.Context) netcontext.Context) (*http.Request, func()) {
336 ctx := withContext(decorate(req.Context()), c)
337 req = req.WithContext(ctx)
339 return req, func() {}
342 var errTimeout = &CallError{
343 Detail: "Deadline exceeded",
344 Code: int32(remotepb.RpcError_CANCELLED),
348 func (c *context) Header() http.Header { return c.outHeader }
350 // Copied from $GOROOT/src/pkg/net/http/transfer.go. Some response status
351 // codes do not permit a response body (nor response entity headers such as
352 // Content-Length, Content-Type, etc).
353 func bodyAllowedForStatus(status int) bool {
355 case status >= 100 && status <= 199:
365 func (c *context) Write(b []byte) (int, error) {
367 c.WriteHeader(http.StatusOK)
369 if len(b) > 0 && !bodyAllowedForStatus(c.outCode) {
370 return 0, http.ErrBodyNotAllowed
372 c.outBody = append(c.outBody, b...)
376 func (c *context) WriteHeader(code int) {
378 logf(c, 3, "WriteHeader called multiple times on request.") // error level
384 func (c *context) post(body []byte, timeout time.Duration) (b []byte, err error) {
385 hreq := &http.Request{
389 apiEndpointHeader: apiEndpointHeaderValue,
390 apiMethodHeader: apiMethodHeaderValue,
391 apiContentType: apiContentTypeValue,
392 apiDeadlineHeader: []string{strconv.FormatFloat(timeout.Seconds(), 'f', -1, 64)},
394 Body: ioutil.NopCloser(bytes.NewReader(body)),
395 ContentLength: int64(len(body)),
398 if info := c.req.Header.Get(dapperHeader); info != "" {
399 hreq.Header.Set(dapperHeader, info)
401 if info := c.req.Header.Get(traceHeader); info != "" {
402 hreq.Header.Set(traceHeader, info)
405 tr := apiHTTPClient.Transport.(*http.Transport)
407 var timedOut int32 // atomic; set to 1 if timed out
408 t := time.AfterFunc(timeout, func() {
409 atomic.StoreInt32(&timedOut, 1)
410 tr.CancelRequest(hreq)
414 // Check if timeout was exceeded.
415 if atomic.LoadInt32(&timedOut) != 0 {
420 hresp, err := apiHTTPClient.Do(hreq)
422 return nil, &CallError{
423 Detail: fmt.Sprintf("service bridge HTTP failed: %v", err),
424 Code: int32(remotepb.RpcError_UNKNOWN),
427 defer hresp.Body.Close()
428 hrespBody, err := ioutil.ReadAll(hresp.Body)
429 if hresp.StatusCode != 200 {
430 return nil, &CallError{
431 Detail: fmt.Sprintf("service bridge returned HTTP %d (%q)", hresp.StatusCode, hrespBody),
432 Code: int32(remotepb.RpcError_UNKNOWN),
436 return nil, &CallError{
437 Detail: fmt.Sprintf("service bridge response bad: %v", err),
438 Code: int32(remotepb.RpcError_UNKNOWN),
441 return hrespBody, nil
444 func Call(ctx netcontext.Context, service, method string, in, out proto.Message) error {
445 if ns := NamespaceFromContext(ctx); ns != "" {
446 if fn, ok := NamespaceMods[service]; ok {
451 if f, ctx, ok := callOverrideFromContext(ctx); ok {
452 return f(ctx, service, method, in, out)
455 // Handle already-done contexts quickly.
462 c := fromContext(ctx)
464 // Give a good error message rather than a panic lower down.
465 return errNotAppEngineContext
468 // Apply transaction modifications if we're in a transaction.
469 if t := transactionFromContext(ctx); t != nil {
471 return errors.New("transaction context has expired")
473 applyTransaction(in, &t.transaction)
476 // Default RPC timeout is 60s.
477 timeout := 60 * time.Second
478 if deadline, ok := ctx.Deadline(); ok {
479 timeout = deadline.Sub(time.Now())
482 data, err := proto.Marshal(in)
487 ticket := c.req.Header.Get(ticketHeader)
488 // Use a test ticket under test environment.
490 if appid := ctx.Value(&appIDOverrideKey); appid != nil {
491 ticket = appid.(string) + defaultTicketSuffix
494 // Fall back to use background ticket when the request ticket is not available in Flex or dev_appserver.
496 ticket = DefaultTicket()
498 if dri := c.req.Header.Get(devRequestIdHeader); IsDevAppServer() && dri != "" {
501 req := &remotepb.Request{
502 ServiceName: &service,
507 hreqBody, err := proto.Marshal(req)
512 hrespBody, err := c.post(hreqBody, timeout)
517 res := &remotepb.Response{}
518 if err := proto.Unmarshal(hrespBody, res); err != nil {
521 if res.RpcError != nil {
523 Detail: res.RpcError.GetDetail(),
524 Code: *res.RpcError.Code,
526 switch remotepb.RpcError_ErrorCode(ce.Code) {
527 case remotepb.RpcError_CANCELLED, remotepb.RpcError_DEADLINE_EXCEEDED:
532 if res.ApplicationError != nil {
534 Service: *req.ServiceName,
535 Detail: res.ApplicationError.GetDetail(),
536 Code: *res.ApplicationError.Code,
539 if res.Exception != nil || res.JavaException != nil {
540 // This shouldn't happen, but let's be defensive.
542 Detail: "service bridge returned exception",
543 Code: int32(remotepb.RpcError_UNKNOWN),
546 return proto.Unmarshal(res.Response, out)
549 func (c *context) Request() *http.Request {
553 func (c *context) addLogLine(ll *logpb.UserAppLogLine) {
554 // Truncate long log lines.
555 // TODO(dsymonds): Check if this is still necessary.
557 if len(*ll.Message) > lim {
558 suffix := fmt.Sprintf("...(length %d)", len(*ll.Message))
559 ll.Message = proto.String((*ll.Message)[:lim-len(suffix)] + suffix)
563 c.pendingLogs.lines = append(c.pendingLogs.lines, ll)
564 c.pendingLogs.Unlock()
567 var logLevelName = map[int64]string{
575 func logf(c *context, level int64, format string, args ...interface{}) {
577 panic("not an App Engine context")
579 s := fmt.Sprintf(format, args...)
580 s = strings.TrimRight(s, "\n") // Remove any trailing newline characters.
581 c.addLogLine(&logpb.UserAppLogLine{
582 TimestampUsec: proto.Int64(time.Now().UnixNano() / 1e3),
586 // Only duplicate log to stderr if not running on App Engine second generation
588 log.Print(logLevelName[level] + ": " + s)
592 // flushLog attempts to flush any pending logs to the appserver.
593 // It should not be called concurrently.
594 func (c *context) flushLog(force bool) (flushed bool) {
596 // Grab up to 30 MB. We can get away with up to 32 MB, but let's be cautious.
598 for ; n < len(c.pendingLogs.lines); n++ {
599 ll := c.pendingLogs.lines[n]
600 // Each log line will require about 3 bytes of overhead.
601 nb := proto.Size(ll) + 3
607 lines := c.pendingLogs.lines[:n]
608 c.pendingLogs.lines = c.pendingLogs.lines[n:]
609 c.pendingLogs.Unlock()
611 if len(lines) == 0 && !force {
620 c.pendingLogs.lines = append(lines, c.pendingLogs.lines...)
621 c.pendingLogs.Unlock()
625 buf, err := proto.Marshal(&logpb.UserAppLogGroup{
629 log.Printf("internal.flushLog: marshaling UserAppLogGroup: %v", err)
634 req := &logpb.FlushRequest{
637 res := &basepb.VoidProto{}
639 c.pendingLogs.flushes++
640 c.pendingLogs.Unlock()
641 if err := Call(toContext(c), "logservice", "Flush", req, res); err != nil {
642 log.Printf("internal.flushLog: Flush RPC: %v", err)
650 // Log flushing parameters.
651 flushInterval = 1 * time.Second
652 forceFlushInterval = 60 * time.Second
655 func (c *context) logFlusher(stop <-chan int) {
656 lastFlush := time.Now()
657 tick := time.NewTicker(flushInterval)
665 force := time.Now().Sub(lastFlush) > forceFlushInterval
666 if c.flushLog(force) {
667 lastFlush = time.Now()
673 func ContextForTesting(req *http.Request) netcontext.Context {
674 return toContext(&context{req: req})