client.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. // Copyright 2013 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. package remote_api
  5. // This file provides the client for connecting remotely to a user's production
  6. // application.
  7. import (
  8. "bytes"
  9. "fmt"
  10. "io/ioutil"
  11. "log"
  12. "math/rand"
  13. "net/http"
  14. "net/url"
  15. "regexp"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "github.com/golang/protobuf/proto"
  20. "golang.org/x/net/context"
  21. "google.golang.org/appengine/internal"
  22. pb "google.golang.org/appengine/internal/remote_api"
  23. )
  24. // NewRemoteContext returns a context that gives access to the production
  25. // APIs for the application at the given host. All communication will be
  26. // performed over SSL unless the host is localhost.
  27. func NewRemoteContext(host string, client *http.Client) (context.Context, error) {
  28. // Add an appcfg header to outgoing requests.
  29. t := client.Transport
  30. if t == nil {
  31. t = http.DefaultTransport
  32. }
  33. client.Transport = &headerAddingRoundTripper{t}
  34. url := url.URL{
  35. Scheme: "https",
  36. Host: host,
  37. Path: "/_ah/remote_api",
  38. }
  39. if host == "localhost" || strings.HasPrefix(host, "localhost:") {
  40. url.Scheme = "http"
  41. }
  42. u := url.String()
  43. appID, err := getAppID(client, u)
  44. if err != nil {
  45. return nil, fmt.Errorf("unable to contact server: %v", err)
  46. }
  47. rc := &remoteContext{
  48. client: client,
  49. url: u,
  50. }
  51. ctx := internal.WithCallOverride(context.Background(), rc.call)
  52. ctx = internal.WithLogOverride(ctx, rc.logf)
  53. ctx = internal.WithAppIDOverride(ctx, appID)
  54. return ctx, nil
  55. }
  56. type remoteContext struct {
  57. client *http.Client
  58. url string
  59. }
  60. var logLevels = map[int64]string{
  61. 0: "DEBUG",
  62. 1: "INFO",
  63. 2: "WARNING",
  64. 3: "ERROR",
  65. 4: "CRITICAL",
  66. }
  67. func (c *remoteContext) logf(level int64, format string, args ...interface{}) {
  68. log.Printf(logLevels[level]+": "+format, args...)
  69. }
  70. func (c *remoteContext) call(ctx context.Context, service, method string, in, out proto.Message) error {
  71. req, err := proto.Marshal(in)
  72. if err != nil {
  73. return fmt.Errorf("error marshalling request: %v", err)
  74. }
  75. remReq := &pb.Request{
  76. ServiceName: proto.String(service),
  77. Method: proto.String(method),
  78. Request: req,
  79. // NOTE(djd): RequestId is unused in the server.
  80. }
  81. req, err = proto.Marshal(remReq)
  82. if err != nil {
  83. return fmt.Errorf("proto.Marshal: %v", err)
  84. }
  85. // TODO(djd): Respect ctx.Deadline()?
  86. resp, err := c.client.Post(c.url, "application/octet-stream", bytes.NewReader(req))
  87. if err != nil {
  88. return fmt.Errorf("error sending request: %v", err)
  89. }
  90. defer resp.Body.Close()
  91. body, err := ioutil.ReadAll(resp.Body)
  92. if resp.StatusCode != http.StatusOK {
  93. return fmt.Errorf("bad response %d; body: %q", resp.StatusCode, body)
  94. }
  95. if err != nil {
  96. return fmt.Errorf("failed reading response: %v", err)
  97. }
  98. remResp := &pb.Response{}
  99. if err := proto.Unmarshal(body, remResp); err != nil {
  100. return fmt.Errorf("error unmarshalling response: %v", err)
  101. }
  102. if ae := remResp.GetApplicationError(); ae != nil {
  103. return &internal.APIError{
  104. Code: ae.GetCode(),
  105. Detail: ae.GetDetail(),
  106. Service: service,
  107. }
  108. }
  109. if remResp.Response == nil {
  110. return fmt.Errorf("unexpected response: %s", proto.MarshalTextString(remResp))
  111. }
  112. return proto.Unmarshal(remResp.Response, out)
  113. }
  114. // This is a forgiving regexp designed to parse the app ID from YAML.
  115. var appIDRE = regexp.MustCompile(`app_id["']?\s*:\s*['"]?([-a-z0-9.:~]+)`)
  116. func getAppID(client *http.Client, url string) (string, error) {
  117. // Generate a pseudo-random token for handshaking.
  118. token := strconv.Itoa(rand.New(rand.NewSource(time.Now().UnixNano())).Int())
  119. resp, err := client.Get(fmt.Sprintf("%s?rtok=%s", url, token))
  120. if err != nil {
  121. return "", err
  122. }
  123. defer resp.Body.Close()
  124. body, err := ioutil.ReadAll(resp.Body)
  125. if resp.StatusCode != http.StatusOK {
  126. return "", fmt.Errorf("bad response %d; body: %q", resp.StatusCode, body)
  127. }
  128. if err != nil {
  129. return "", fmt.Errorf("failed reading response: %v", err)
  130. }
  131. // Check the token is present in response.
  132. if !bytes.Contains(body, []byte(token)) {
  133. return "", fmt.Errorf("token not found: want %q; body %q", token, body)
  134. }
  135. match := appIDRE.FindSubmatch(body)
  136. if match == nil {
  137. return "", fmt.Errorf("app ID not found: body %q", body)
  138. }
  139. return string(match[1]), nil
  140. }
  141. type headerAddingRoundTripper struct {
  142. Wrapped http.RoundTripper
  143. }
  144. func (t *headerAddingRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
  145. r.Header.Set("X-Appcfg-Api-Version", "1")
  146. return t.Wrapped.RoundTrip(r)
  147. }