How to use getSerialPortOutput method of gce Package

Best Syzkaller code snippet using gce.getSerialPortOutput

gcp.go

Source:gcp.go Github

copy

Full Screen

1/*2Package gcp deals with Google Cloud APIs and config file parsing.3Files included in this package:4 gcp.go: Interface for GCP manipulation.5 config.go: Parse config files into dicts.6*/7package gcp8import (9 "fmt"10 "io"11 "net/http"12 "os"13 "strconv"14 "strings"15 "thunk.org/gce-server/util/mymath"16 "cloud.google.com/go/storage"17 "golang.org/x/net/context"18 "golang.org/x/oauth2/google"19 "google.golang.org/api/compute/v1"20 "google.golang.org/api/googleapi"21 "google.golang.org/api/iterator"22)23// Service holds the API clients for Google Cloud Platform.24type Service struct {25 ctx context.Context26 cancel context.CancelFunc27 service *compute.Service28 bucket *storage.BucketHandle29}30// Quota holds the quota limits for a zone.31type Quota struct {32 Zone string33 cpuLimit int34 ipLimit int35 ssdLimit int36}37// NewService launches a new GCP service client.38// If gsBucket is not empty, launches a new GS client as well.39func NewService(gsBucket string) (*Service, error) {40 gce := Service{}41 gce.ctx, gce.cancel = context.WithCancel(context.Background())42 client, err := google.DefaultClient(gce.ctx, compute.CloudPlatformScope)43 if err != nil {44 return nil, err45 }46 s, err := compute.New(client)47 if err != nil {48 return nil, err49 }50 gce.service = s51 gsclient, err := storage.NewClient(gce.ctx)52 if err != nil {53 return nil, err54 }55 if gsBucket != "" {56 gce.bucket = gsclient.Bucket(gsBucket)57 _, err = gce.bucket.Attrs(gce.ctx)58 if err != nil {59 return nil, err60 }61 }62 return &gce, nil63}64// Close cancels the context to close the GCP service client.65func (gce *Service) Close() {66 gce.cancel()67}68// GetSerialPortOutput returns the serial port output for an instance.69// Requires the starting offset of desired output. Returns the new offset.70func (gce *Service) GetSerialPortOutput(projID string, zone string, instance string, start int64) (*compute.SerialPortOutput, error) {71 call := gce.service.Instances.GetSerialPortOutput(projID, zone, instance)72 call = call.Start(start)73 return call.Context(gce.ctx).Do()74}75// GetInstanceInfo returns the info about an instance.76func (gce *Service) GetInstanceInfo(projID string, zone string, instance string) (*compute.Instance, error) {77 return gce.service.Instances.Get(projID, zone, instance).Context(gce.ctx).Do()78}79// SetMetadata sets the metadata for an instance.80func (gce *Service) SetMetadata(projID string, zone string, instance string, metadata *compute.Metadata) error {81 _, err := gce.service.Instances.SetMetadata(projID, zone, instance, metadata).Context(gce.ctx).Do()82 return err83}84// DeleteInstance deletes an instance.85func (gce *Service) DeleteInstance(projID string, zone string, instance string) error {86 _, err := gce.service.Instances.Delete(projID, zone, instance).Context(gce.ctx).Do()87 return err88}89func (gce *Service) getRegionInfo(projID string, region string) (*compute.Region, error) {90 return gce.service.Regions.Get(projID, region).Context(gce.ctx).Do()91}92func (gce *Service) getAllRegionsInfo(projID string) ([]*compute.Region, error) {93 allRegions := []*compute.Region{}94 req := gce.service.Regions.List(projID)95 err := req.Pages(gce.ctx, func(page *compute.RegionList) error {96 allRegions = append(allRegions, page.Items...)97 return nil98 })99 return allRegions, err100}101func (gce *Service) getZoneInfo(projID string, zone string) (*compute.Zone, error) {102 return gce.service.Zones.Get(projID, zone).Context(gce.ctx).Do()103}104// GetRegionQuota picks the first available zone in a region and returns the105// quota limits on it.106// Every shard needs 2 vCPUs and SSD space of GCE_MIN_SCR_SIZE.107// SSD space is no less than 50 GB.108func (gce *Service) GetRegionQuota(projID string, region string) (*Quota, error) {109 regionInfo, err := gce.getRegionInfo(projID, region)110 if err != nil {111 return nil, err112 }113 var pickedZone string114 for _, zone := range regionInfo.Zones {115 slice := strings.Split(zone, "/")116 zone := slice[len(slice)-1]117 zoneInfo, err := gce.getZoneInfo(projID, zone)118 if err != nil {119 return nil, err120 }121 if zoneInfo.Status == "UP" {122 pickedZone = zoneInfo.Name123 break124 }125 }126 if pickedZone == "" {127 return nil, fmt.Errorf("GCE region %s has no available zones", region)128 }129 var cpuNum, ipNum, ssdNum int130 for _, quota := range regionInfo.Quotas {131 switch quota.Metric {132 case "CPUS":133 cpuNum = int(quota.Limit - quota.Usage)134 case "IN_USE_ADDRESSES":135 ipNum = int(quota.Limit - quota.Usage)136 case "SSD_TOTAL_GB":137 ssdNum = int(quota.Limit - quota.Usage)138 }139 }140 size, err := GceConfig.Get("GCE_MIN_SCR_SIZE")141 if err != nil {142 return nil, err143 }144 ssdMin, err := strconv.Atoi(size)145 if err != nil {146 ssdMin = 0147 }148 ssdLimit := ssdNum / mymath.MaxInt(50, ssdMin)149 return &Quota{150 Zone: pickedZone,151 cpuLimit: cpuNum / 2,152 ipLimit: ipNum,153 ssdLimit: ssdLimit,154 }, nil155}156// GetAllRegionsQuota returns quota limits for every available region.157func (gce *Service) GetAllRegionsQuota(projID string) ([]*Quota, error) {158 allRegions, err := gce.getAllRegionsInfo(projID)159 if err != nil {160 return []*Quota{}, err161 }162 quotas := []*Quota{}163 for _, region := range allRegions {164 if region.Status == "UP" {165 quota, err := gce.GetRegionQuota(projID, region.Name)166 if quota != nil && err == nil {167 quotas = append(quotas, quota)168 }169 }170 }171 return quotas, nil172}173// GetMaxShard return the max possible number of shards according to the quota limits174func (quota *Quota) GetMaxShard() (int, error) {175 return mymath.MinIntSlice([]int{quota.cpuLimit, quota.ipLimit, quota.ssdLimit})176}177// getFiles returns an iterator for all files with a matching path prefix on GS.178func (gce *Service) getFiles(prefix string) (*storage.ObjectIterator, error) {179 if gce.bucket == nil {180 return nil, fmt.Errorf("GS client is not initialized")181 }182 query := &storage.Query{Prefix: prefix}183 it := gce.bucket.Objects(gce.ctx, query)184 return it, nil185}186// DeleteFiles removes all files with a matching path prefix on GS.187func (gce *Service) DeleteFiles(prefix string) (int, error) {188 it, err := gce.getFiles(prefix)189 if err != nil {190 return 0, err191 }192 count := 0193 for {194 objAttrs, err := it.Next()195 if err != nil {196 if err == iterator.Done {197 break198 } else {199 return 0, err200 }201 }202 err = gce.bucket.Object(objAttrs.Name).Delete(gce.ctx)203 if err != nil {204 return 0, err205 }206 count++207 }208 return count, nil209}210// GetFileNames returns a slice of file names with a matching path prefix on GS.211func (gce *Service) GetFileNames(prefix string) ([]string, error) {212 names := []string{}213 it, err := gce.getFiles(prefix)214 if err != nil {215 return names, err216 }217 for {218 objAttrs, err := it.Next()219 if err != nil {220 if err == iterator.Done {221 break222 } else {223 return names, err224 }225 }226 names = append(names, objAttrs.Name)227 }228 return names, nil229}230// UploadFile uploads a local file or directory to GS.231func (gce *Service) UploadFile(localPath string, gsPath string) error {232 if gce.bucket == nil {233 return fmt.Errorf("GS client is not initialized")234 }235 obj := gce.bucket.Object(gsPath)236 w := obj.NewWriter(gce.ctx)237 defer w.Close()238 file, err := os.Open(localPath)239 if err != nil {240 return err241 }242 defer file.Close()243 _, err = io.Copy(w, file)244 if err != nil {245 return err246 }247 return nil248}249// NotFound returns true if err is 404 not found.250func NotFound(err error) bool {251 if err != nil {252 if e, ok := err.(*googleapi.Error); ok && e.Code == http.StatusNotFound {253 return true254 }255 }256 return false257}...

Full Screen

Full Screen

driver.go

Source:driver.go Github

copy

Full Screen

1package googlecompute2import (3 "crypto/rsa"4 "time"5)6// Driver is the interface that has to be implemented to communicate7// with GCE. The Driver interface exists mostly to allow a mock implementation8// to be used to test the steps.9type Driver interface {10 // CreateImage creates an image from the given disk in Google Compute11 // Engine.12 CreateImage(name, description, family, zone, disk string) (<-chan *Image, <-chan error)13 // DeleteImage deletes the image with the given name.14 DeleteImage(name string) <-chan error15 // DeleteInstance deletes the given instance, keeping the boot disk.16 DeleteInstance(zone, name string) (<-chan error, error)17 // DeleteDisk deletes the disk with the given name.18 DeleteDisk(zone, name string) (<-chan error, error)19 // GetImage gets an image; tries the default and public projects. If20 // fromFamily is true, name designates an image family instead of a21 // particular image.22 GetImage(name string, fromFamily bool) (*Image, error)23 // GetImageFromProject gets an image from a specific project. If fromFamily24 // is true, name designates an image family instead of a particular image.25 GetImageFromProject(project, name string, fromFamily bool) (*Image, error)26 // GetInstanceMetadata gets a metadata variable for the instance, name.27 GetInstanceMetadata(zone, name, key string) (string, error)28 // GetInternalIP gets the GCE-internal IP address for the instance.29 GetInternalIP(zone, name string) (string, error)30 // GetNatIP gets the NAT IP address for the instance.31 GetNatIP(zone, name string) (string, error)32 // GetSerialPortOutput gets the Serial Port contents for the instance.33 GetSerialPortOutput(zone, name string) (string, error)34 // ImageExists returns true if the specified image exists. If an error35 // occurs calling the API, this method returns false.36 ImageExists(name string) bool37 // RunInstance takes the given config and launches an instance.38 RunInstance(*InstanceConfig) (<-chan error, error)39 // WaitForInstance waits for an instance to reach the given state.40 WaitForInstance(state, zone, name string) <-chan error41 // CreateOrResetWindowsPassword creates or resets the password for a user on an Windows instance.42 CreateOrResetWindowsPassword(zone, name string, config *WindowsPasswordConfig) (<-chan error, error)43}44type InstanceConfig struct {45 Address string46 Description string47 DiskSizeGb int6448 DiskType string49 Image *Image50 MachineType string51 Metadata map[string]string52 Name string53 Network string54 NetworkProjectId string55 OmitExternalIP bool56 OnHostMaintenance string57 Preemptible bool58 Region string59 Scopes []string60 Subnetwork string61 Tags []string62 Zone string63}64// WindowsPasswordConfig is the data structue that GCE needs to encrypt the created65// windows password.66type WindowsPasswordConfig struct {67 key *rsa.PrivateKey68 password string69 UserName string `json:"userName"`70 Modulus string `json:"modulus"`71 Exponent string `json:"exponent"`72 Email string `json:"email"`73 ExpireOn time.Time `json:"expireOn"`74}75type windowsPasswordResponse struct {76 UserName string `json:"userName"`77 PasswordFound bool `json:"passwordFound"`78 EncryptedPassword string `json:"encryptedPassword"`79 Modulus string `json:"modulus"`80 Exponent string `json:"exponent"`81 ErrorMessage string `json:"errorMessage"`82}...

Full Screen

Full Screen

getSerialPortOutput

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 instName, err := metadata.InstanceName()4 if err != nil {5 log.Fatalf("Could not get instance name: %v", err)6 }7 g := gce.NewGCE()8 output, err := g.GetSerialPortOutput(instName, 1)9 if err != nil {10 log.Fatalf("Could not get serial port output: %v", err)11 }12 fmt.Println(output)13}

Full Screen

Full Screen

getSerialPortOutput

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var (4 projectId = flag.String("project-id", "", "The Google Cloud Platform project id.")5 zone = flag.String("zone", "", "The Google Cloud Platform zone.")6 instance = flag.String("instance", "", "The Google Compute Engine instance name.")7 flag.Parse()8 client := newHTTPClient()9 computeService, err := compute.New(client)10 if err != nil {11 log.Fatalf("Cannot create compute service: %v", err)12 }13 gce := &gce{14 }15 output, err := gce.getSerialPortOutput()16 if err != nil {17 log.Fatalf("Cannot get serial port output: %v", err)18 }19 fmt.Println(output)20}21func newHTTPClient() *http.Client {22 jsonKeyPath := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS")23 jsonKey, err := ioutil.ReadFile(jsonKeyPath)24 if err != nil {25 log.Fatalf("Cannot read JSON key file: %v", err)26 }27 config, err := google.JWTConfigFromJSON(jsonKey, compute.ComputeScope)28 if err != nil {29 log.Fatalf("Cannot create JWT config: %v", err)30 }31 return config.Client(oauth2.NoContext)32}33type gce struct {34}35func (

Full Screen

Full Screen

getSerialPortOutput

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 g := gce.New()4 fmt.Println(g.GetSerialPortOutput("instance_name", "zone"))5}6import (7type GCE struct {8}9func New() *GCE {10 client := getClient()11 service, _ := compute.New(client)12 return &GCE{service}13}14func (g *GCE) GetSerialPortOutput(instance, zone string) string {15 output, _ := g.service.Instances.GetSerialPortOutput("project_id", zone, instance).Do()16}17func getClient() *http.Client {18 client, _ := google.DefaultClient(oauth2.NoContext, compute.ComputeScope)19}

Full Screen

Full Screen

getSerialPortOutput

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 gce := gce.GCE{}4 gce.Init()5 serialPortOutput, err := gce.GetSerialPortOutput("test", "test")6 if err != nil {7 fmt.Println("Error in GetSerialPortOutput")8 }9 fmt.Println(serialPortOutput)10}11import (12type GCE struct {13}14func (gce *GCE) Init() {15 jsonKey, err := ioutil.ReadFile("service-account.json")16 if err != nil {17 fmt.Println("Error in reading json file")18 os.Exit(1)19 }20 conf, err := google.JWTConfigFromJSON(jsonKey, compute.ComputeScope)21 if err != nil {22 fmt.Println("Error in creating JWTConfig")23 os.Exit(1)24 }25 client := conf.Client(oauth2.NoContext)26 computeService, err := compute.New(client)27 if err != nil {28 fmt.Println("Error in creating compute service")29 os.Exit(1)30 }31}32func (gce *GCE) GetSerialPortOutput(project, instance string) (string, error) {33 serialPortOutput, err := gce.computeService.Instances.GetSerialPortOutput(project, "us-central1-a", instance).Do()34 if err != nil {35 fmt.Println("Error in getting serial port output")36 }37}38import (

Full Screen

Full Screen

getSerialPortOutput

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 output, err := metadata.GetSerialPortOutput(1)4 if err != nil {5 }6 fmt.Println(output)7}8import (9func main() {10 outputs, err := metadata.GetSerialPortOutput(-1)11 if err != nil {12 }13 for i, output := range outputs {14 fmt.Printf("Serial Port %d Output: %s", i, output)15 }16}17import (18func main() {19 output, err := metadata.GetSerialPortOutput(0)20 if err != nil {21 }22 fmt.Println(output)23}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful