当前位置: 首页>>代码示例>>Golang>>正文


Golang metadata.OnGCE函数代码示例

本文整理汇总了Golang中google/golang.org/cloud/compute/metadata.OnGCE函数的典型用法代码示例。如果您正苦于以下问题:Golang OnGCE函数的具体用法?Golang OnGCE怎么用?Golang OnGCE使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了OnGCE函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: authenticatedClient

// If we're not running on GCE (e.g. dev mode on localhost) and have
// no other way to get the info, the error value is is errNoRefresh.
func (h *DeployHandler) authenticatedClient() (project string, hc *http.Client, err error) {
	project = os.Getenv("CAMLI_GCE_PROJECT")
	accountFile := os.Getenv("CAMLI_GCE_SERVICE_ACCOUNT")
	if project != "" && accountFile != "" {
		data, errr := ioutil.ReadFile(accountFile)
		err = errr
		if err != nil {
			return
		}
		jwtConf, errr := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/compute.readonly")
		err = errr
		if err != nil {
			return
		}
		hc = jwtConf.Client(context.Background())
		return
	}
	if !metadata.OnGCE() {
		err = errNoRefresh
		return
	}
	project, _ = metadata.ProjectID()
	hc, err = google.DefaultClient(oauth2.NoContext)
	return project, hc, err
}
开发者ID:preillyme,项目名称:camlistore,代码行数:27,代码来源:handler.go

示例2: init

func init() {
	if !metadata.OnGCE() {
		return
	}
	client, err := googlestorage.NewServiceClient()
	wkfs.RegisterFS("/gcs/", &gcsFS{client, err})
}
开发者ID:Jimmy99,项目名称:camlistore,代码行数:7,代码来源:gcs.go

示例3: NewAuthTokenProvider

func NewAuthTokenProvider(expectedAuthScope string) (AuthTokenProvider, error) {
	// Retry OnGCE call for 15 seconds before declaring failure.
	onGCE := false
	for start := time.Now(); time.Since(start) < 15*time.Second; time.Sleep(time.Second) {
		if metadata.OnGCE() {
			onGCE = true
			break
		}
	}
	// Only support GCE for now.
	if !onGCE {
		return nil, fmt.Errorf("authorization to GCE is currently only supported on GCE")
	}

	// Check for required auth scopes
	err := verifyAuthScope(expectedAuthScope)
	if err != nil {
		return nil, err
	}

	t := &realAuthTokenProvider{
		RWMutex: sync.RWMutex{},
	}
	go t.refreshTokenWhenExpires()
	return t, nil
}
开发者ID:ravihansa3000,项目名称:heapster,代码行数:26,代码来源:auth.go

示例4: maybeRemapCloudSQL

func maybeRemapCloudSQL(host string) (out string, err error) {
	if !strings.HasSuffix(host, cloudSQLSuffix) {
		return host, nil
	}
	inst := strings.TrimSuffix(host, cloudSQLSuffix)
	if !metadata.OnGCE() {
		return "", errors.New("CloudSQL support only available when running on Google Compute Engine.")
	}
	proj, err := metadata.ProjectID()
	if err != nil {
		return "", fmt.Errorf("Failed to lookup GCE project ID: %v", err)
	}

	admin, _ := sqladmin.New(oauth2.NewClient(context.Background(), google.ComputeTokenSource("")))
	listRes, err := admin.Instances.List(proj).Do()
	if err != nil {
		return "", fmt.Errorf("error enumerating Cloud SQL instances: %v", err)
	}
	for _, it := range listRes.Items {
		if !strings.EqualFold(it.Instance, inst) {
			continue
		}
		js, _ := json.Marshal(it)
		log.Printf("Found Cloud SQL instance %s: %s", inst, js)
		for _, ipm := range it.IpAddresses {
			return ipm.IpAddress, nil
		}
		return "", fmt.Errorf("No external IP address for Cloud SQL instances %s", inst)
	}
	var found []string
	for _, it := range listRes.Items {
		found = append(found, it.Instance)
	}
	return "", fmt.Errorf("Cloud SQL instance %q not found. Found: %q", inst, found)
}
开发者ID:camarox53,项目名称:coreos-baremetal,代码行数:35,代码来源:cloudsql.go

示例5: init

func init() {
	if !metadata.OnGCE() {
		return
	}
	hc, err := google.DefaultClient(oauth2.NoContext)
	if err != nil {
		registerBrokenFS(fmt.Errorf("could not get http client for context: %v", err))
		return
	}
	projID, err := metadata.ProjectID()
	if projID == "" || err != nil {
		registerBrokenFS(fmt.Errorf("could not get GCE project ID: %v", err))
		return
	}
	ctx := cloud.NewContext(projID, hc)
	sc, err := storage.NewClient(ctx)
	if err != nil {
		registerBrokenFS(fmt.Errorf("could not get cloud storage client: %v", err))
		return
	}
	wkfs.RegisterFS("/gcs/", &gcsFS{
		ctx: ctx,
		sc:  sc,
	})
}
开发者ID:cgag,项目名称:coreos-baremetal,代码行数:25,代码来源:gcs.go

示例6: GetGceIp

// Gets the IP of the specified GCE instance.
func GetGceIp(hostname string) (string, error) {
	if hostname == "localhost" {
		return "127.0.0.1", nil
	}

	args := []string{"compute"}
	args = append(args, getProjectFlag()...)
	args = append(args, "instances", "describe")
	args = append(args, getZoneFlag()...)
	args = append(args, hostname)
	out, err := exec.Command("gcloud", args...).CombinedOutput()
	if err != nil {
		return "", fmt.Errorf("failed to get instance information for %q with error %v and output %s", hostname, err, string(out))
	}

	// Use the internal IP within GCE and the external one outside.
	var matches []string
	if metadata.OnGCE() {
		matches = gceInternalIpRegexp.FindStringSubmatch(string(out))
	} else {
		matches = gceExternalIpRegexp.FindStringSubmatch(string(out))
	}
	if len(matches) == 0 {
		return "", fmt.Errorf("failed to find IP from output %q", string(out))
	}
	return matches[1], nil
}
开发者ID:normanjoyner,项目名称:cadvisor,代码行数:28,代码来源:gce.go

示例7: new

// Returns an implementation of a Google Cloud Logging (GCL) sink.
func new() (sink_api.ExternalSink, error) {
	// TODO: Retry OnGCE call for ~15 seconds before declaring failure.
	time.Sleep(3 * time.Second)
	// Only support GCE for now.
	if !metadata.OnGCE() {
		return nil, fmt.Errorf("The Google Cloud Logging (GCL) sink failed to start: this process must be running on Google Compute Engine (GCE)")
	}

	// Detect project ID
	projectId, err := metadata.ProjectID()
	if err != nil {
		return nil, err
	}
	glog.Infof("Project ID for GCL sink is: %q\r\n", projectId)

	// Check for required auth scopes
	err = gce.VerifyAuthScope(GCLAuthScope)
	if err != nil {
		return nil, err
	}

	impl := &gclSink{
		projectId:  projectId,
		httpClient: &http.Client{},
	}

	// Get an initial token.
	err = impl.refreshToken()
	if err != nil {
		return nil, err
	}

	return impl, nil
}
开发者ID:naxhh,项目名称:heapster,代码行数:35,代码来源:driver.go

示例8: detectGCE

func detectGCE() {
	if !metadata.OnGCE() {
		return
	}
	v, _ := metadata.InstanceAttributeValue("camlistore-config-dir")
	isGCE = v != ""
}
开发者ID:camarox53,项目名称:coreos-baremetal,代码行数:7,代码来源:env.go

示例9: Token

func (cs computeSource) Token() (*oauth2.Token, error) {
	if !metadata.OnGCE() {
		return nil, errors.New("oauth2/google: can't get a token from the metadata service; not running on GCE")
	}
	acct := cs.account
	if acct == "" {
		acct = "default"
	}
	tokenJSON, err := metadata.Get("instance/service-accounts/" + acct + "/token")
	if err != nil {
		return nil, err
	}
	var res struct {
		AccessToken  string `json:"access_token"`
		ExpiresInSec int    `json:"expires_in"`
		TokenType    string `json:"token_type"`
	}
	err = json.NewDecoder(strings.NewReader(tokenJSON)).Decode(&res)
	if err != nil {
		return nil, fmt.Errorf("oauth2/google: invalid token JSON from metadata: %v", err)
	}
	if res.ExpiresInSec == 0 || res.AccessToken == "" {
		return nil, fmt.Errorf("oauth2/google: incomplete token received from metadata")
	}
	return &oauth2.Token{
		AccessToken: res.AccessToken,
		TokenType:   res.TokenType,
		Expiry:      time.Now().Add(time.Duration(res.ExpiresInSec) * time.Second),
	}, nil
}
开发者ID:Kr1sso,项目名称:oauth2,代码行数:30,代码来源:google.go

示例10: metadataValue

// metadataValue returns the GCE metadata instance value for the given key.
// If the metadata is not defined, the returned string is empty.
//
// If not running on GCE, it falls back to using environment variables
// for local development.
func metadataValue(key string) string {

	// The common case (on GCE, but not in Kubernetes):
	if metadata.OnGCE() && !inKube {
		v, err := metadata.InstanceAttributeValue(key)
		if _, notDefined := err.(metadata.NotDefinedError); notDefined {
			return ""
		}
		if err != nil {
			log.Fatalf("metadata.InstanceAttributeValue(%q): %v", key, err)
		}
		return v
	}

	// Else allow use of environment variables to fake
	// metadata keys, for Kubernetes pods or local testing.
	envKey := "META_" + strings.Replace(key, "-", "_", -1)
	v := os.Getenv(envKey)
	// Respect curl-style '@' prefix to mean the rest is a filename.
	if strings.HasPrefix(v, "@") {
		slurp, err := ioutil.ReadFile(v[1:])
		if err != nil {
			log.Fatalf("Error reading file for GCEMETA_%v: %v", key, err)
		}
		return string(slurp)
	}
	if v == "" {
		log.Printf("Warning: not running on GCE, and no %v environment variable defined", envKey)
	}
	return v
}
开发者ID:way-2-go,项目名称:build,代码行数:36,代码来源:buildlet.go

示例11: newInstance

func newInstance() *Instance {
	var i = new(Instance)

	if !metadata.OnGCE() {
		i.Error = "Not running on GCE"
		return i
	}

	a := &assigner{}
	i.Id = a.assign(metadata.InstanceID)
	i.Zone = a.assign(metadata.Zone)
	i.Name = a.assign(metadata.InstanceName)
	i.Hostname = a.assign(metadata.Hostname)
	i.Project = a.assign(metadata.ProjectID)
	i.InternalIP = a.assign(metadata.InternalIP)
	i.ExternalIP = a.assign(metadata.ExternalIP)

	// read current POD and Namespace
	i.POD = os.Getenv("MY_POD_NAME")
	i.Namespace = os.Getenv("MY_POD_NAMESPACE")

	if a.err != nil {
		i.Error = a.err.Error()
	}
	return i
}
开发者ID:markTward,项目名称:gceme,代码行数:26,代码来源:main.go

示例12: newClient

// newClient creates http.Client with a jwt service account when
// jsonFile flag is specified, otherwise by obtaining the GCE service
// account's access token.
func newClient(jsonFile string) (*http.Client, error) {
	if jsonFile != "" {
		jsonKey, err := ioutil.ReadFile(jsonFile)
		if err != nil {
			return nil, err
		}
		conf, err := google.JWTConfigFromJSON(jsonKey, pubsub.ScopePubSub)
		if err != nil {
			return nil, err
		}
		return conf.Client(oauth2.NoContext), nil
	}
	if metadata.OnGCE() {
		c := &http.Client{
			Transport: &oauth2.Transport{
				Source: google.ComputeTokenSource(""),
			},
		}
		if *projID == "" {
			projectID, err := metadata.ProjectID()
			if err != nil {
				return nil, fmt.Errorf("ProjectID failed, %v", err)
			}
			*projID = projectID
		}
		return c, nil
	}
	return nil, errors.New("Could not create an authenticated client.")
}
开发者ID:Celluliodio,项目名称:flannel,代码行数:32,代码来源:main.go

示例13: EnsureOnGCE

func EnsureOnGCE() error {
	for start := time.Now(); time.Since(start) < waitForGCETimeout; time.Sleep(waitForGCEInterval) {
		glog.Infof("Waiting for GCE metadata to be available")
		if metadata.OnGCE() {
			return nil
		}
	}
	return fmt.Errorf("not running on GCE")
}
开发者ID:titilambert,项目名称:heapster,代码行数:9,代码来源:gce.go

示例14: checkInProduction

func checkInProduction() bool {
	if !metadata.OnGCE() {
		return false
	}
	proj, _ := metadata.ProjectID()
	inst, _ := metadata.InstanceName()
	log.Printf("Running on GCE: %v / %v", proj, inst)
	return proj == "camlistore-website" && inst == "camweb"
}
开发者ID:stevearm,项目名称:camlistore,代码行数:9,代码来源:camweb.go

示例15: newLoggerConfig

func newLoggerConfig() *loggerConfig {
	c := &loggerConfig{
		gceAccount: "default",
		logsID:     "monitoring_proxy",
	}
	if metadata.OnGCE() {
		c.preloadFromGCEMetadata()
	}
	return c
}
开发者ID:keelerh,项目名称:chrome_infra,代码行数:10,代码来源:logging.go


注:本文中的google/golang.org/cloud/compute/metadata.OnGCE函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。