api.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  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.
  4. // +build !appengine
  5. // +build go1.7
  6. package internal
  7. import (
  8. "bytes"
  9. "errors"
  10. "fmt"
  11. "io/ioutil"
  12. "log"
  13. "net"
  14. "net/http"
  15. "net/url"
  16. "os"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "sync/atomic"
  22. "time"
  23. "github.com/golang/protobuf/proto"
  24. netcontext "golang.org/x/net/context"
  25. basepb "google.golang.org/appengine/internal/base"
  26. logpb "google.golang.org/appengine/internal/log"
  27. remotepb "google.golang.org/appengine/internal/remote_api"
  28. )
  29. const (
  30. apiPath = "/rpc_http"
  31. defaultTicketSuffix = "/default.20150612t184001.0"
  32. )
  33. var (
  34. // Incoming headers.
  35. ticketHeader = http.CanonicalHeaderKey("X-AppEngine-API-Ticket")
  36. dapperHeader = http.CanonicalHeaderKey("X-Google-DapperTraceInfo")
  37. traceHeader = http.CanonicalHeaderKey("X-Cloud-Trace-Context")
  38. curNamespaceHeader = http.CanonicalHeaderKey("X-AppEngine-Current-Namespace")
  39. userIPHeader = http.CanonicalHeaderKey("X-AppEngine-User-IP")
  40. remoteAddrHeader = http.CanonicalHeaderKey("X-AppEngine-Remote-Addr")
  41. // Outgoing headers.
  42. apiEndpointHeader = http.CanonicalHeaderKey("X-Google-RPC-Service-Endpoint")
  43. apiEndpointHeaderValue = []string{"app-engine-apis"}
  44. apiMethodHeader = http.CanonicalHeaderKey("X-Google-RPC-Service-Method")
  45. apiMethodHeaderValue = []string{"/VMRemoteAPI.CallRemoteAPI"}
  46. apiDeadlineHeader = http.CanonicalHeaderKey("X-Google-RPC-Service-Deadline")
  47. apiContentType = http.CanonicalHeaderKey("Content-Type")
  48. apiContentTypeValue = []string{"application/octet-stream"}
  49. logFlushHeader = http.CanonicalHeaderKey("X-AppEngine-Log-Flush-Count")
  50. apiHTTPClient = &http.Client{
  51. Transport: &http.Transport{
  52. Proxy: http.ProxyFromEnvironment,
  53. Dial: limitDial,
  54. },
  55. }
  56. defaultTicketOnce sync.Once
  57. defaultTicket string
  58. backgroundContextOnce sync.Once
  59. backgroundContext netcontext.Context
  60. )
  61. func apiURL() *url.URL {
  62. host, port := "appengine.googleapis.internal", "10001"
  63. if h := os.Getenv("API_HOST"); h != "" {
  64. host = h
  65. }
  66. if p := os.Getenv("API_PORT"); p != "" {
  67. port = p
  68. }
  69. return &url.URL{
  70. Scheme: "http",
  71. Host: host + ":" + port,
  72. Path: apiPath,
  73. }
  74. }
  75. func handleHTTP(w http.ResponseWriter, r *http.Request) {
  76. c := &context{
  77. req: r,
  78. outHeader: w.Header(),
  79. apiURL: apiURL(),
  80. }
  81. r = r.WithContext(withContext(r.Context(), c))
  82. c.req = r
  83. stopFlushing := make(chan int)
  84. // Patch up RemoteAddr so it looks reasonable.
  85. if addr := r.Header.Get(userIPHeader); addr != "" {
  86. r.RemoteAddr = addr
  87. } else if addr = r.Header.Get(remoteAddrHeader); addr != "" {
  88. r.RemoteAddr = addr
  89. } else {
  90. // Should not normally reach here, but pick a sensible default anyway.
  91. r.RemoteAddr = "127.0.0.1"
  92. }
  93. // The address in the headers will most likely be of these forms:
  94. // 123.123.123.123
  95. // 2001:db8::1
  96. // net/http.Request.RemoteAddr is specified to be in "IP:port" form.
  97. if _, _, err := net.SplitHostPort(r.RemoteAddr); err != nil {
  98. // Assume the remote address is only a host; add a default port.
  99. r.RemoteAddr = net.JoinHostPort(r.RemoteAddr, "80")
  100. }
  101. // Start goroutine responsible for flushing app logs.
  102. // This is done after adding c to ctx.m (and stopped before removing it)
  103. // because flushing logs requires making an API call.
  104. go c.logFlusher(stopFlushing)
  105. executeRequestSafely(c, r)
  106. c.outHeader = nil // make sure header changes aren't respected any more
  107. stopFlushing <- 1 // any logging beyond this point will be dropped
  108. // Flush any pending logs asynchronously.
  109. c.pendingLogs.Lock()
  110. flushes := c.pendingLogs.flushes
  111. if len(c.pendingLogs.lines) > 0 {
  112. flushes++
  113. }
  114. c.pendingLogs.Unlock()
  115. go c.flushLog(false)
  116. w.Header().Set(logFlushHeader, strconv.Itoa(flushes))
  117. // Avoid nil Write call if c.Write is never called.
  118. if c.outCode != 0 {
  119. w.WriteHeader(c.outCode)
  120. }
  121. if c.outBody != nil {
  122. w.Write(c.outBody)
  123. }
  124. }
  125. func executeRequestSafely(c *context, r *http.Request) {
  126. defer func() {
  127. if x := recover(); x != nil {
  128. logf(c, 4, "%s", renderPanic(x)) // 4 == critical
  129. c.outCode = 500
  130. }
  131. }()
  132. http.DefaultServeMux.ServeHTTP(c, r)
  133. }
  134. func renderPanic(x interface{}) string {
  135. buf := make([]byte, 16<<10) // 16 KB should be plenty
  136. buf = buf[:runtime.Stack(buf, false)]
  137. // Remove the first few stack frames:
  138. // this func
  139. // the recover closure in the caller
  140. // That will root the stack trace at the site of the panic.
  141. const (
  142. skipStart = "internal.renderPanic"
  143. skipFrames = 2
  144. )
  145. start := bytes.Index(buf, []byte(skipStart))
  146. p := start
  147. for i := 0; i < skipFrames*2 && p+1 < len(buf); i++ {
  148. p = bytes.IndexByte(buf[p+1:], '\n') + p + 1
  149. if p < 0 {
  150. break
  151. }
  152. }
  153. if p >= 0 {
  154. // buf[start:p+1] is the block to remove.
  155. // Copy buf[p+1:] over buf[start:] and shrink buf.
  156. copy(buf[start:], buf[p+1:])
  157. buf = buf[:len(buf)-(p+1-start)]
  158. }
  159. // Add panic heading.
  160. head := fmt.Sprintf("panic: %v\n\n", x)
  161. if len(head) > len(buf) {
  162. // Extremely unlikely to happen.
  163. return head
  164. }
  165. copy(buf[len(head):], buf)
  166. copy(buf, head)
  167. return string(buf)
  168. }
  169. // context represents the context of an in-flight HTTP request.
  170. // It implements the appengine.Context and http.ResponseWriter interfaces.
  171. type context struct {
  172. req *http.Request
  173. outCode int
  174. outHeader http.Header
  175. outBody []byte
  176. pendingLogs struct {
  177. sync.Mutex
  178. lines []*logpb.UserAppLogLine
  179. flushes int
  180. }
  181. apiURL *url.URL
  182. }
  183. var contextKey = "holds a *context"
  184. // jointContext joins two contexts in a superficial way.
  185. // It takes values and timeouts from a base context, and only values from another context.
  186. type jointContext struct {
  187. base netcontext.Context
  188. valuesOnly netcontext.Context
  189. }
  190. func (c jointContext) Deadline() (time.Time, bool) {
  191. return c.base.Deadline()
  192. }
  193. func (c jointContext) Done() <-chan struct{} {
  194. return c.base.Done()
  195. }
  196. func (c jointContext) Err() error {
  197. return c.base.Err()
  198. }
  199. func (c jointContext) Value(key interface{}) interface{} {
  200. if val := c.base.Value(key); val != nil {
  201. return val
  202. }
  203. return c.valuesOnly.Value(key)
  204. }
  205. // fromContext returns the App Engine context or nil if ctx is not
  206. // derived from an App Engine context.
  207. func fromContext(ctx netcontext.Context) *context {
  208. c, _ := ctx.Value(&contextKey).(*context)
  209. return c
  210. }
  211. func withContext(parent netcontext.Context, c *context) netcontext.Context {
  212. ctx := netcontext.WithValue(parent, &contextKey, c)
  213. if ns := c.req.Header.Get(curNamespaceHeader); ns != "" {
  214. ctx = withNamespace(ctx, ns)
  215. }
  216. return ctx
  217. }
  218. func toContext(c *context) netcontext.Context {
  219. return withContext(netcontext.Background(), c)
  220. }
  221. func IncomingHeaders(ctx netcontext.Context) http.Header {
  222. if c := fromContext(ctx); c != nil {
  223. return c.req.Header
  224. }
  225. return nil
  226. }
  227. func ReqContext(req *http.Request) netcontext.Context {
  228. return req.Context()
  229. }
  230. func WithContext(parent netcontext.Context, req *http.Request) netcontext.Context {
  231. return jointContext{
  232. base: parent,
  233. valuesOnly: req.Context(),
  234. }
  235. }
  236. // DefaultTicket returns a ticket used for background context or dev_appserver.
  237. func DefaultTicket() string {
  238. defaultTicketOnce.Do(func() {
  239. if IsDevAppServer() {
  240. defaultTicket = "testapp" + defaultTicketSuffix
  241. return
  242. }
  243. appID := partitionlessAppID()
  244. escAppID := strings.Replace(strings.Replace(appID, ":", "_", -1), ".", "_", -1)
  245. majVersion := VersionID(nil)
  246. if i := strings.Index(majVersion, "."); i > 0 {
  247. majVersion = majVersion[:i]
  248. }
  249. defaultTicket = fmt.Sprintf("%s/%s.%s.%s", escAppID, ModuleName(nil), majVersion, InstanceID())
  250. })
  251. return defaultTicket
  252. }
  253. func BackgroundContext() netcontext.Context {
  254. backgroundContextOnce.Do(func() {
  255. // Compute background security ticket.
  256. ticket := DefaultTicket()
  257. c := &context{
  258. req: &http.Request{
  259. Header: http.Header{
  260. ticketHeader: []string{ticket},
  261. },
  262. },
  263. apiURL: apiURL(),
  264. }
  265. backgroundContext = toContext(c)
  266. // TODO(dsymonds): Wire up the shutdown handler to do a final flush.
  267. go c.logFlusher(make(chan int))
  268. })
  269. return backgroundContext
  270. }
  271. // RegisterTestRequest registers the HTTP request req for testing, such that
  272. // any API calls are sent to the provided URL. It returns a closure to delete
  273. // the registration.
  274. // It should only be used by aetest package.
  275. func RegisterTestRequest(req *http.Request, apiURL *url.URL, decorate func(netcontext.Context) netcontext.Context) (*http.Request, func()) {
  276. c := &context{
  277. req: req,
  278. apiURL: apiURL,
  279. }
  280. ctx := withContext(decorate(req.Context()), c)
  281. req = req.WithContext(ctx)
  282. c.req = req
  283. return req, func() {}
  284. }
  285. var errTimeout = &CallError{
  286. Detail: "Deadline exceeded",
  287. Code: int32(remotepb.RpcError_CANCELLED),
  288. Timeout: true,
  289. }
  290. func (c *context) Header() http.Header { return c.outHeader }
  291. // Copied from $GOROOT/src/pkg/net/http/transfer.go. Some response status
  292. // codes do not permit a response body (nor response entity headers such as
  293. // Content-Length, Content-Type, etc).
  294. func bodyAllowedForStatus(status int) bool {
  295. switch {
  296. case status >= 100 && status <= 199:
  297. return false
  298. case status == 204:
  299. return false
  300. case status == 304:
  301. return false
  302. }
  303. return true
  304. }
  305. func (c *context) Write(b []byte) (int, error) {
  306. if c.outCode == 0 {
  307. c.WriteHeader(http.StatusOK)
  308. }
  309. if len(b) > 0 && !bodyAllowedForStatus(c.outCode) {
  310. return 0, http.ErrBodyNotAllowed
  311. }
  312. c.outBody = append(c.outBody, b...)
  313. return len(b), nil
  314. }
  315. func (c *context) WriteHeader(code int) {
  316. if c.outCode != 0 {
  317. logf(c, 3, "WriteHeader called multiple times on request.") // error level
  318. return
  319. }
  320. c.outCode = code
  321. }
  322. func (c *context) post(body []byte, timeout time.Duration) (b []byte, err error) {
  323. hreq := &http.Request{
  324. Method: "POST",
  325. URL: c.apiURL,
  326. Header: http.Header{
  327. apiEndpointHeader: apiEndpointHeaderValue,
  328. apiMethodHeader: apiMethodHeaderValue,
  329. apiContentType: apiContentTypeValue,
  330. apiDeadlineHeader: []string{strconv.FormatFloat(timeout.Seconds(), 'f', -1, 64)},
  331. },
  332. Body: ioutil.NopCloser(bytes.NewReader(body)),
  333. ContentLength: int64(len(body)),
  334. Host: c.apiURL.Host,
  335. }
  336. if info := c.req.Header.Get(dapperHeader); info != "" {
  337. hreq.Header.Set(dapperHeader, info)
  338. }
  339. if info := c.req.Header.Get(traceHeader); info != "" {
  340. hreq.Header.Set(traceHeader, info)
  341. }
  342. tr := apiHTTPClient.Transport.(*http.Transport)
  343. var timedOut int32 // atomic; set to 1 if timed out
  344. t := time.AfterFunc(timeout, func() {
  345. atomic.StoreInt32(&timedOut, 1)
  346. tr.CancelRequest(hreq)
  347. })
  348. defer t.Stop()
  349. defer func() {
  350. // Check if timeout was exceeded.
  351. if atomic.LoadInt32(&timedOut) != 0 {
  352. err = errTimeout
  353. }
  354. }()
  355. hresp, err := apiHTTPClient.Do(hreq)
  356. if err != nil {
  357. return nil, &CallError{
  358. Detail: fmt.Sprintf("service bridge HTTP failed: %v", err),
  359. Code: int32(remotepb.RpcError_UNKNOWN),
  360. }
  361. }
  362. defer hresp.Body.Close()
  363. hrespBody, err := ioutil.ReadAll(hresp.Body)
  364. if hresp.StatusCode != 200 {
  365. return nil, &CallError{
  366. Detail: fmt.Sprintf("service bridge returned HTTP %d (%q)", hresp.StatusCode, hrespBody),
  367. Code: int32(remotepb.RpcError_UNKNOWN),
  368. }
  369. }
  370. if err != nil {
  371. return nil, &CallError{
  372. Detail: fmt.Sprintf("service bridge response bad: %v", err),
  373. Code: int32(remotepb.RpcError_UNKNOWN),
  374. }
  375. }
  376. return hrespBody, nil
  377. }
  378. func Call(ctx netcontext.Context, service, method string, in, out proto.Message) error {
  379. if ns := NamespaceFromContext(ctx); ns != "" {
  380. if fn, ok := NamespaceMods[service]; ok {
  381. fn(in, ns)
  382. }
  383. }
  384. if f, ctx, ok := callOverrideFromContext(ctx); ok {
  385. return f(ctx, service, method, in, out)
  386. }
  387. // Handle already-done contexts quickly.
  388. select {
  389. case <-ctx.Done():
  390. return ctx.Err()
  391. default:
  392. }
  393. c := fromContext(ctx)
  394. if c == nil {
  395. // Give a good error message rather than a panic lower down.
  396. return errNotAppEngineContext
  397. }
  398. // Apply transaction modifications if we're in a transaction.
  399. if t := transactionFromContext(ctx); t != nil {
  400. if t.finished {
  401. return errors.New("transaction context has expired")
  402. }
  403. applyTransaction(in, &t.transaction)
  404. }
  405. // Default RPC timeout is 60s.
  406. timeout := 60 * time.Second
  407. if deadline, ok := ctx.Deadline(); ok {
  408. timeout = deadline.Sub(time.Now())
  409. }
  410. data, err := proto.Marshal(in)
  411. if err != nil {
  412. return err
  413. }
  414. ticket := c.req.Header.Get(ticketHeader)
  415. // Use a test ticket under test environment.
  416. if ticket == "" {
  417. if appid := ctx.Value(&appIDOverrideKey); appid != nil {
  418. ticket = appid.(string) + defaultTicketSuffix
  419. }
  420. }
  421. // Fall back to use background ticket when the request ticket is not available in Flex or dev_appserver.
  422. if ticket == "" {
  423. ticket = DefaultTicket()
  424. }
  425. req := &remotepb.Request{
  426. ServiceName: &service,
  427. Method: &method,
  428. Request: data,
  429. RequestId: &ticket,
  430. }
  431. hreqBody, err := proto.Marshal(req)
  432. if err != nil {
  433. return err
  434. }
  435. hrespBody, err := c.post(hreqBody, timeout)
  436. if err != nil {
  437. return err
  438. }
  439. res := &remotepb.Response{}
  440. if err := proto.Unmarshal(hrespBody, res); err != nil {
  441. return err
  442. }
  443. if res.RpcError != nil {
  444. ce := &CallError{
  445. Detail: res.RpcError.GetDetail(),
  446. Code: *res.RpcError.Code,
  447. }
  448. switch remotepb.RpcError_ErrorCode(ce.Code) {
  449. case remotepb.RpcError_CANCELLED, remotepb.RpcError_DEADLINE_EXCEEDED:
  450. ce.Timeout = true
  451. }
  452. return ce
  453. }
  454. if res.ApplicationError != nil {
  455. return &APIError{
  456. Service: *req.ServiceName,
  457. Detail: res.ApplicationError.GetDetail(),
  458. Code: *res.ApplicationError.Code,
  459. }
  460. }
  461. if res.Exception != nil || res.JavaException != nil {
  462. // This shouldn't happen, but let's be defensive.
  463. return &CallError{
  464. Detail: "service bridge returned exception",
  465. Code: int32(remotepb.RpcError_UNKNOWN),
  466. }
  467. }
  468. return proto.Unmarshal(res.Response, out)
  469. }
  470. func (c *context) Request() *http.Request {
  471. return c.req
  472. }
  473. func (c *context) addLogLine(ll *logpb.UserAppLogLine) {
  474. // Truncate long log lines.
  475. // TODO(dsymonds): Check if this is still necessary.
  476. const lim = 8 << 10
  477. if len(*ll.Message) > lim {
  478. suffix := fmt.Sprintf("...(length %d)", len(*ll.Message))
  479. ll.Message = proto.String((*ll.Message)[:lim-len(suffix)] + suffix)
  480. }
  481. c.pendingLogs.Lock()
  482. c.pendingLogs.lines = append(c.pendingLogs.lines, ll)
  483. c.pendingLogs.Unlock()
  484. }
  485. var logLevelName = map[int64]string{
  486. 0: "DEBUG",
  487. 1: "INFO",
  488. 2: "WARNING",
  489. 3: "ERROR",
  490. 4: "CRITICAL",
  491. }
  492. func logf(c *context, level int64, format string, args ...interface{}) {
  493. if c == nil {
  494. panic("not an App Engine context")
  495. }
  496. s := fmt.Sprintf(format, args...)
  497. s = strings.TrimRight(s, "\n") // Remove any trailing newline characters.
  498. c.addLogLine(&logpb.UserAppLogLine{
  499. TimestampUsec: proto.Int64(time.Now().UnixNano() / 1e3),
  500. Level: &level,
  501. Message: &s,
  502. })
  503. log.Print(logLevelName[level] + ": " + s)
  504. }
  505. // flushLog attempts to flush any pending logs to the appserver.
  506. // It should not be called concurrently.
  507. func (c *context) flushLog(force bool) (flushed bool) {
  508. c.pendingLogs.Lock()
  509. // Grab up to 30 MB. We can get away with up to 32 MB, but let's be cautious.
  510. n, rem := 0, 30<<20
  511. for ; n < len(c.pendingLogs.lines); n++ {
  512. ll := c.pendingLogs.lines[n]
  513. // Each log line will require about 3 bytes of overhead.
  514. nb := proto.Size(ll) + 3
  515. if nb > rem {
  516. break
  517. }
  518. rem -= nb
  519. }
  520. lines := c.pendingLogs.lines[:n]
  521. c.pendingLogs.lines = c.pendingLogs.lines[n:]
  522. c.pendingLogs.Unlock()
  523. if len(lines) == 0 && !force {
  524. // Nothing to flush.
  525. return false
  526. }
  527. rescueLogs := false
  528. defer func() {
  529. if rescueLogs {
  530. c.pendingLogs.Lock()
  531. c.pendingLogs.lines = append(lines, c.pendingLogs.lines...)
  532. c.pendingLogs.Unlock()
  533. }
  534. }()
  535. buf, err := proto.Marshal(&logpb.UserAppLogGroup{
  536. LogLine: lines,
  537. })
  538. if err != nil {
  539. log.Printf("internal.flushLog: marshaling UserAppLogGroup: %v", err)
  540. rescueLogs = true
  541. return false
  542. }
  543. req := &logpb.FlushRequest{
  544. Logs: buf,
  545. }
  546. res := &basepb.VoidProto{}
  547. c.pendingLogs.Lock()
  548. c.pendingLogs.flushes++
  549. c.pendingLogs.Unlock()
  550. if err := Call(toContext(c), "logservice", "Flush", req, res); err != nil {
  551. log.Printf("internal.flushLog: Flush RPC: %v", err)
  552. rescueLogs = true
  553. return false
  554. }
  555. return true
  556. }
  557. const (
  558. // Log flushing parameters.
  559. flushInterval = 1 * time.Second
  560. forceFlushInterval = 60 * time.Second
  561. )
  562. func (c *context) logFlusher(stop <-chan int) {
  563. lastFlush := time.Now()
  564. tick := time.NewTicker(flushInterval)
  565. for {
  566. select {
  567. case <-stop:
  568. // Request finished.
  569. tick.Stop()
  570. return
  571. case <-tick.C:
  572. force := time.Now().Sub(lastFlush) > forceFlushInterval
  573. if c.flushLog(force) {
  574. lastFlush = time.Now()
  575. }
  576. }
  577. }
  578. }
  579. func ContextForTesting(req *http.Request) netcontext.Context {
  580. return toContext(&context{req: req})
  581. }