Example #1
0
func (fi *FileInfo) CreateUrls(r *http.Request, c context.Context) {
	u := &url.URL{
		Scheme: r.URL.Scheme,
		Host:   appengine.DefaultVersionHostname(c),
		Path:   "/",
	}
	uString := u.String()
	fi.Url = uString + fi.Key
	fi.DeleteUrl = fi.Url
	fi.DeleteType = "DELETE"
	if fi.ThumbnailKey != "" {
		fi.ThumbnailUrl = uString + fi.ThumbnailKey
	}
}
//Diagnostics shows a bunch of app engine's information for the app/project
//useful for figuring out which version of an app is serving
func Diagnostics(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	out := map[string]interface{}{
		"App ID":                   appengine.AppID(c),
		"Instance ID":              appengine.InstanceID(),
		"Default Version Hostname": appengine.DefaultVersionHostname(c),
		"Version ID":               appengine.VersionID(c),
		"Datacenter":               appengine.Datacenter(c),
		"Module Name":              appengine.ModuleName(c),
		"Server Software":          appengine.ServerSoftware(),
	}

	templates.Load(w, "diagnostics", out)
	return
}
Example #3
0
// linkToPrimary sends HttpRPC to the primary to register myself as a replica.
func linkToPrimary(c context.Context, ticket ServiceLinkTicket, initiatedBy string) error {
	headers := make(map[string]string)
	headers["Content-Type"] = "application/octet-stream"
	protocol := "https"
	if appengine.IsDevAppServer() {
		headers["X-Appengine-Inbound-Appid"] = appengine.AppID(c)
		protocol = "http"
	}

	linkReq := &ServiceLinkRequest{
		Ticket:      ticket.GetTicket(),
		ReplicaUrl:  proto.String(fmt.Sprintf("%s://%s", protocol, appengine.DefaultVersionHostname(c))),
		InitiatedBy: proto.String(initiatedBy),
	}
	buf, err := proto.Marshal(linkReq)
	if err != nil {
		return err
	}
	req, err := http.NewRequest("POST", fmt.Sprintf("%s/auth_service/api/v1/internal/link_replica", ticket.GetPrimaryUrl()), bytes.NewReader(buf))
	if err != nil {
		return err
	}
	for key, value := range headers {
		req.Header.Add(key, value)
	}

	client := urlfetch.Client(c)
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		return fmt.Errorf("got status code %v; want 200", resp.StatusCode)
	}

	respBody := new(bytes.Buffer)
	respBody.ReadFrom(resp.Body)
	linkResp := &ServiceLinkResponse{}
	if err = proto.Unmarshal(respBody.Bytes(), linkResp); err != nil {
		return err
	}
	if linkResp.GetStatus() != ServiceLinkResponse_SUCCESS {
		return fmt.Errorf("Request to the primary failed with status %d", linkResp.GetStatus())
	}
	return nil
}
Example #4
0
// Status gathers a quick overview of the system state
// and dumps it in JSON format.
func Status(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		return
	}

	ctx := appengine.NewContext(r)

	m := new(runtime.MemStats)
	runtime.ReadMemStats(m)

	s := &status{
		initTime,
		appengineStatus{
			appengine.InstanceID(),
			appengine.AppID(ctx),
			appengine.Datacenter(ctx),
			appengine.DefaultVersionHostname(ctx),
			appengine.ModuleName(ctx),
			appengine.IsDevAppServer(),
		},
		runtimeStatus{
			runtime.GOMAXPROCS(0),
			runtime.GOARCH,
			runtime.GOOS,
			runtime.GOROOT(),
			runtime.NumCPU(),
			runtime.NumCgoCall(),
			runtime.Version(),
			*m,
		},
		os.Environ(),
	}

	b, err := json.Marshal(s)

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json; encoding=utf-8")
	w.Write(b)
}
Example #5
0
// Todo: When c==nil we are in a non-appengine environment.
// We still want to return at least ii.PureHostname
func GetByContext(c context.Context) *Instance {

	tstart := time.Now()

	if !ii.LastUpdated.IsZero() {

		age := tstart.Sub(ii.LastUpdated)

		if age < 200*time.Millisecond {
			aelog.Infof(c, "instance info update too recently: %v, skipping.\n", age)
			return ii
		}

		if age < 1*time.Hour {
			if len(ii.Hostname) > 2 {
				return ii
			}

		}

		aelog.Infof(c, "instance info update too old: %v, recomputing.\n", age)
	}

	ii.ModuleName = appengine.ModuleName(c)
	ii.InstanceID = appengine.InstanceID()
	ii.VersionFull = appengine.VersionID(c)

	majorMinor := strings.Split(ii.VersionFull, ".")
	if len(majorMinor) != 2 {
		panic("we need a version string of format X.Y")
	}

	ii.VersionMajor = majorMinor[0]
	ii.VersionMinor = majorMinor[1]

	var err = errors.New("dummy creation error message")

	ii.NumInstances, err = module.NumInstances(c, ii.ModuleName, ii.VersionFull)
	if err != nil {
		// this never works with version full
		// we do not log this - but try version major
		err = nil

		if !util_appengine.IsLocalEnviron() {
			ii.NumInstances, err = module.NumInstances(c, ii.ModuleName, ii.VersionMajor)

			if err != nil {
				eStr := err.Error()
				eCmp1, eCmp2, eCmp3 := "API error", "INVALID_VERSION)", "Could not find the given version"
				if strings.Contains(eStr, eCmp1) && strings.Contains(eStr, eCmp2) && strings.Contains(eStr, eCmp3) {
					aelog.Infof(c, "get num instances works only live and without autoscale; %v", err)
				} else {
					aelog.Errorf(c, "get num instances error; %v", err)
				}
			}

		}

	}

	// in auto scaling, google reports "zero" - which can not be true
	// we assume at least 1
	if ii.NumInstances == 0 {
		ii.NumInstances = 1
	}

	// http://[0-2].1.default.libertarian-islands.appspot.com/instance-info

	ii.Hostname, err = appengine.ModuleHostname(c, ii.ModuleName, ii.VersionMajor, "")
	if err != nil {
		aelog.Errorf(c, "ModuleHostname1: %v", err)
	}

	ii.PureHostname = appengine.DefaultVersionHostname(c)

	if !appengine.IsDevAppServer() {
		ii.HostnameInst0, err = appengine.ModuleHostname(c, ii.ModuleName, ii.VersionMajor, "0")
		if err != nil && (err.Error() == autoScalingErr1 || err.Error() == autoScalingErr2) {
			aelog.Infof(c, "inst 0: "+autoScalingErrMsg)
			err = nil
		}
		if err != nil {
			aelog.Errorf(c, "ModuleHostname2: %v", err)
		}

		ii.HostnameInst1, err = appengine.ModuleHostname(c, ii.ModuleName, ii.VersionMajor, "1")
		if err != nil && (err.Error() == autoScalingErr1 || err.Error() == autoScalingErr2) {
			aelog.Infof(c, "inst 1: "+autoScalingErrMsg)
			err = nil
		}
		if err != nil {
			aelog.Errorf(c, "ModuleHostname3: %v", err)
		}

		ii.HostnameMod02, err = appengine.ModuleHostname(c, "mod02", "", "")
		if err != nil {
			aelog.Infof(c, "ModuleHostname4: %v", err)
		}

	}

	ii.LastUpdated = time.Now()

	aelog.Infof(c, "collectInfo() completed, %v  - %v - %v - %v - %v, took %v",
		stringspb.Ellipsoider(ii.InstanceID, 4), ii.VersionMajor, ii.ModuleName,
		ii.Hostname, ii.PureHostname, time.Now().Sub(tstart))

	return ii
}
Example #6
0
func (g giImpl) DefaultVersionHostname() string {
	return appengine.DefaultVersionHostname(g.aeCtx)
}
Example #7
0
//
//
// requestPay is unused
func requestPay(w http.ResponseWriter, r *http.Request, m map[string]interface{}) {

	lg, b := loghttp.BuffLoggerUniversal(w, r)
	closureOverBuf := func(bUnused *bytes.Buffer) {
		loghttp.Pf(w, r, b.String())
	}
	defer closureOverBuf(b) // the argument is ignored,
	r.Header.Set("X-Custom-Header-Counter", "nocounter")

	protoc := "https://"
	if appengine.IsDevAppServer() {
		protoc = "http://"
	}

	host := appengine.DefaultVersionHostname(appengine.NewContext(r))
	if appengine.IsDevAppServer() {
		host = "not-loclhost"
	}

	confirmURL := fmt.Sprintf("%v%v%v", protoc, host, uriConfirmPayment)
	confirmURL = url.QueryEscape(confirmURL)

	addrURL := fmt.Sprintf("https://%v/api/receive?method=create&address=%v&callback=%v&customsecret=49&api_code=%v",
		coinbaseHost, walletAddress, confirmURL, apiKey)

	req, err := http.NewRequest("GET", addrURL, nil)
	lg(err)
	if err != nil {
		return
	}
	bts, inf, err := fetch.UrlGetter(r, fetch.Options{Req: req})
	bts = bytes.Replace(bts, []byte(`","`), []byte(`", "`), -1)
	if err != nil {
		lg(err)
		lg(inf.Msg)
		return
	}

	lg("response body 1:\n")
	lg("%s\n", string(bts))

	lg("response body 2:\n")
	var data1 map[string]interface{}
	err = json.Unmarshal(bts, &data1)
	lg(err)
	lg(stringspb.IndentedDumpBytes(data1))

	// Response body contains the suggested bitcoin address for payment.
	// And the minimum recommended fee percentage
	inputAddress, ok := data1["input_address"].(string)
	if !ok {
		lg("input address could not be casted to string; is type %T", data1["input_address"])
		return
	}
	feePercent, ok := data1["fee_percent"].(float64)
	if !ok {
		lg("fee percent could not be casted to float64; is type %T", data1["fee_percent"])
		return
	}

	lg("Input Adress will be %q; fee percent will be %4.2v", inputAddress, feePercent)

}