How to use uploadImageToGCS method of gce Package

Best Syzkaller code snippet using gce.uploadImageToGCS

gce.go

Source:gce.go Github

copy

Full Screen

...92 if cfg.GCE_Image == "" {93 cfg.GCE_Image = env.Name94 gcsImage := filepath.Join(cfg.GCS_Path, env.Name+"-image.tar.gz")95 Logf(0, "uploading image to %v...", gcsImage)96 if err := uploadImageToGCS(env.Image, gcsImage); err != nil {97 return nil, err98 }99 Logf(0, "creating GCE image %v...", cfg.GCE_Image)100 if err := GCE.DeleteImage(cfg.GCE_Image); err != nil {101 return nil, fmt.Errorf("failed to delete GCE image: %v", err)102 }103 if err := GCE.CreateImage(cfg.GCE_Image, gcsImage); err != nil {104 return nil, fmt.Errorf("failed to create GCE image: %v", err)105 }106 }107 pool := &Pool{108 cfg: cfg,109 env: env,110 GCE: GCE,111 }112 return pool, nil113}114func (pool *Pool) Count() int {115 return pool.cfg.Count116}117func (pool *Pool) Create(workdir string, index int) (vmimpl.Instance, error) {118 name := fmt.Sprintf("%v-%v", pool.env.Name, index)119 // Create SSH key for the instance.120 gceKey := filepath.Join(workdir, "key")121 keygen := exec.Command("ssh-keygen", "-t", "rsa", "-b", "2048", "-N", "", "-C", "syzkaller", "-f", gceKey)122 if out, err := keygen.CombinedOutput(); err != nil {123 return nil, fmt.Errorf("failed to execute ssh-keygen: %v\n%s", err, out)124 }125 gceKeyPub, err := ioutil.ReadFile(gceKey + ".pub")126 if err != nil {127 return nil, fmt.Errorf("failed to read file: %v", err)128 }129 Logf(0, "deleting instance: %v", name)130 if err := pool.GCE.DeleteInstance(name, true); err != nil {131 return nil, err132 }133 Logf(0, "creating instance: %v", name)134 ip, err := pool.GCE.CreateInstance(name, pool.cfg.Machine_Type, pool.cfg.GCE_Image, string(gceKeyPub))135 if err != nil {136 return nil, err137 }138 ok := false139 defer func() {140 if !ok {141 pool.GCE.DeleteInstance(name, true)142 }143 }()144 sshKey := pool.env.SshKey145 sshUser := pool.env.SshUser146 if sshKey == "" {147 // Assuming image supports GCE ssh fanciness.148 sshKey = gceKey149 sshUser = "syzkaller"150 }151 Logf(0, "wait instance to boot: %v (%v)", name, ip)152 if err := pool.waitInstanceBoot(ip, sshKey, sshUser); err != nil {153 return nil, err154 }155 ok = true156 inst := &instance{157 env: pool.env,158 cfg: pool.cfg,159 debug: pool.env.Debug,160 GCE: pool.GCE,161 name: name,162 ip: ip,163 gceKey: gceKey,164 sshKey: sshKey,165 sshUser: sshUser,166 closed: make(chan bool),167 }168 return inst, nil169}170func (inst *instance) Close() {171 close(inst.closed)172 inst.GCE.DeleteInstance(inst.name, false)173}174func (inst *instance) Forward(port int) (string, error) {175 return fmt.Sprintf("%v:%v", inst.GCE.InternalIP, port), nil176}177func (inst *instance) Copy(hostSrc string) (string, error) {178 vmDst := "./" + filepath.Base(hostSrc)179 args := append(sshArgs(inst.debug, inst.sshKey, "-P", 22), hostSrc, inst.sshUser+"@"+inst.name+":"+vmDst)180 if _, err := runCmd(inst.debug, "scp", args...); err != nil {181 return "", err182 }183 return vmDst, nil184}185func (inst *instance) Run(timeout time.Duration, stop <-chan bool, command string) (<-chan []byte, <-chan error, error) {186 conRpipe, conWpipe, err := osutil.LongPipe()187 if err != nil {188 return nil, nil, err189 }190 conAddr := fmt.Sprintf("%v.%v.%v.syzkaller.port=1@ssh-serialport.googleapis.com",191 inst.GCE.ProjectID, inst.GCE.ZoneID, inst.name)192 conArgs := append(sshArgs(inst.debug, inst.gceKey, "-p", 9600), conAddr)193 con := exec.Command("ssh", conArgs...)194 con.Env = []string{}195 con.Stdout = conWpipe196 con.Stderr = conWpipe197 if _, err := con.StdinPipe(); err != nil { // SSH would close connection on stdin EOF198 conRpipe.Close()199 conWpipe.Close()200 return nil, nil, err201 }202 if err := con.Start(); err != nil {203 conRpipe.Close()204 conWpipe.Close()205 return nil, nil, fmt.Errorf("failed to connect to console server: %v", err)206 }207 conWpipe.Close()208 var tee io.Writer209 if inst.debug {210 tee = os.Stdout211 }212 merger := vmimpl.NewOutputMerger(tee)213 merger.Add("console", conRpipe)214 // We've started the console reading ssh command, but it has not necessary connected yet.215 // If we proceed to running the target command right away, we can miss part216 // of console output. During repro we can crash machines very quickly and217 // would miss beginning of a crash. Before ssh starts piping console output,218 // it usually prints:219 // "serialport: Connected to ... port 1 (session ID: ..., active connections: 1)"220 // So we wait for this line, or at least a minute and at least some output.221 {222 var output []byte223 timeout := time.NewTimer(time.Minute)224 connectedMsg := []byte("serialport: Connected")225 permissionDeniedMsg := []byte("Permission denied (publickey)")226 loop:227 for {228 select {229 case out := <-merger.Output:230 output = append(output, out...)231 if bytes.Contains(output, connectedMsg) {232 // Just to make sure (otherwise we still see trimmed reports).233 time.Sleep(5 * time.Second)234 break loop235 }236 if bytes.Contains(output, permissionDeniedMsg) {237 // This is a GCE bug.238 break239 }240 case <-timeout.C:241 break loop242 }243 }244 timeout.Stop()245 if len(output) == 0 || bytes.Contains(output, permissionDeniedMsg) {246 con.Process.Kill()247 merger.Wait()248 return nil, nil, fmt.Errorf("no output from console or permission denied")249 }250 }251 sshRpipe, sshWpipe, err := osutil.LongPipe()252 if err != nil {253 con.Process.Kill()254 merger.Wait()255 sshRpipe.Close()256 return nil, nil, err257 }258 if inst.env.OS == "linux" {259 if inst.sshUser != "root" {260 command = fmt.Sprintf("sudo bash -c '%v'", command)261 }262 }263 args := append(sshArgs(inst.debug, inst.sshKey, "-p", 22), inst.sshUser+"@"+inst.name, command)264 ssh := exec.Command("ssh", args...)265 ssh.Stdout = sshWpipe266 ssh.Stderr = sshWpipe267 if err := ssh.Start(); err != nil {268 con.Process.Kill()269 merger.Wait()270 sshRpipe.Close()271 sshWpipe.Close()272 return nil, nil, fmt.Errorf("failed to connect to instance: %v", err)273 }274 sshWpipe.Close()275 merger.Add("ssh", sshRpipe)276 errc := make(chan error, 1)277 signal := func(err error) {278 select {279 case errc <- err:280 default:281 }282 }283 go func() {284 select {285 case <-time.After(timeout):286 signal(vmimpl.TimeoutErr)287 case <-stop:288 signal(vmimpl.TimeoutErr)289 case <-inst.closed:290 signal(fmt.Errorf("instance closed"))291 case err := <-merger.Err:292 con.Process.Kill()293 ssh.Process.Kill()294 merger.Wait()295 con.Wait()296 if cmdErr := ssh.Wait(); cmdErr == nil {297 // If the command exited successfully, we got EOF error from merger.298 // But in this case no error has happened and the EOF is expected.299 err = nil300 } else {301 // Check if the instance was terminated due to preemption or host maintenance.302 time.Sleep(5 * time.Second) // just to avoid any GCE races303 if !inst.GCE.IsInstanceRunning(inst.name) {304 Logf(1, "%v: ssh exited but instance is not running", inst.name)305 err = vmimpl.TimeoutErr306 }307 }308 signal(err)309 return310 }311 con.Process.Kill()312 ssh.Process.Kill()313 merger.Wait()314 con.Wait()315 ssh.Wait()316 }()317 return merger.Output, errc, nil318}319func (pool *Pool) waitInstanceBoot(ip, sshKey, sshUser string) error {320 pwd := "pwd"321 if pool.env.OS == "windows" {322 pwd = "dir"323 }324 for i := 0; i < 100; i++ {325 if !vmimpl.SleepInterruptible(5 * time.Second) {326 return fmt.Errorf("shutdown in progress")327 }328 args := append(sshArgs(pool.env.Debug, sshKey, "-p", 22), sshUser+"@"+ip, pwd)329 if _, err := runCmd(pool.env.Debug, "ssh", args...); err == nil {330 return nil331 }332 }333 return fmt.Errorf("can't ssh into the instance")334}335func uploadImageToGCS(localImage, gcsImage string) error {336 GCS, err := gcs.NewClient()337 if err != nil {338 return fmt.Errorf("failed to create GCS client: %v", err)339 }340 defer GCS.Close()341 localReader, err := os.Open(localImage)342 if err != nil {343 return fmt.Errorf("failed to open image file: %v")344 }345 defer localReader.Close()346 localStat, err := localReader.Stat()347 if err != nil {348 return fmt.Errorf("failed to stat image file: %v")349 }...

Full Screen

Full Screen

uploadImageToGCS

Using AI Code Generation

copy

Full Screen

1func (gce *GCE) uploadImageToGCS() (string, error) {2 ctx := context.Background()3 client, err := storage.NewClient(ctx)4 if err != nil {5 }6 defer client.Close()7 file, err := os.Open("/home/saurabh/Desktop/2.jpg")8 if err != nil {9 }10 defer file.Close()11 ctx, cancel := context.WithTimeout(ctx, time.Second*50)12 defer cancel()13 bucket := client.Bucket("saurabh")14 obj := bucket.Object("2.jpg")15 w := obj.NewWriter(ctx)16 if _, err = io.Copy(w, file); err != nil {17 }18 if err := w.Close(); err != nil {19 }20}21func (gce *GCE) uploadImageToGCS() (string, error) {22 ctx := context.Background()23 client, err := storage.NewClient(ctx)24 if err != nil {25 }26 defer client.Close()27 file, err := os.Open("/home/saurabh/Desktop/3.jpg")28 if err != nil {29 }30 defer file.Close()31 ctx, cancel := context.WithTimeout(ctx, time.Second*50)32 defer cancel()33 bucket := client.Bucket("saurabh")34 obj := bucket.Object("3.jpg")35 w := obj.NewWriter(ctx)36 if _, err = io.Copy(w, file); err != nil {37 }38 if err := w.Close(); err != nil {39 }40}41func (gce *GCE) uploadImageToGCS() (string, error) {42 ctx := context.Background()43 client, err := storage.NewClient(ctx)44 if err != nil {45 }46 defer client.Close()47 file, err := os.Open("/home/saurabh/Desktop/4.jpg")48 if err != nil {49 }50 defer file.Close()51 ctx, cancel := context.WithTimeout(ctx, time.Second*

Full Screen

Full Screen

uploadImageToGCS

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.HandleFunc("/upload", uploadImage)4 http.ListenAndServe(":8080", nil)5}6func uploadImage(w http.ResponseWriter, r *http.Request) {7 gce := bookshelf.NewGCE()8 gce.UploadImageToGCS(w, r)9}10import (11type GCE struct {12}13func NewGCE() *GCE {14 ctx := context.Background()15 client, err := storage.NewClient(ctx, option.WithCredentialsFile("service-account.json"))16 if err != nil {17 fmt.Println(err)18 }19 return &GCE{20 }21}22func (gce *GCE) UploadImageToGCS(w http.ResponseWriter, r *http.Request) {23 ctx := context.Background()24 file, header, err := r.FormFile("image")25 if err != nil {26 fmt.Println(err)27 }28 defer file.Close()29 object := gce.Client.Bucket(gce.Bucket).Object(header.Filename)30 w := object.NewWriter(ctx)31 if _, err := io.Copy(w, file); err != nil {32 fmt.Println(err)33 }34 if err := w.Close(); err != nil {35 fmt.Println(err)36 }37 attrs, err := object.Attrs(ctx)38 if err != nil {39 fmt.Println(err)40 }41 fmt.Fprintf(w, "Image is available at %s", attrs.MediaLink)42}43{

Full Screen

Full Screen

uploadImageToGCS

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.HandleFunc("/upload", uploadHandler)4 http.HandleFunc("/delete", deleteHandler)5 http.HandleFunc("/get", getHandler)6 http.HandleFunc("/create", createHandler)7 http.HandleFunc("/deleteVM", deleteVMHandler)8 http.HandleFunc("/listVM", listVMHandler)9 http.HandleFunc("/getVM", getVMHandler)10 http.HandleFunc("/startVM", startVMHandler)11 http.HandleFunc("/stopVM", stopVMHandler)12 http.HandleFunc("/restartVM", restartVMHandler)13 http.HandleFunc("/setMetadataVM", setMetadataVMHandler)14 http.HandleFunc("/getMetadataVM", getMetadataVMHandler)15 http.HandleFunc("/deleteMetadataVM", deleteMetadataVMHandler)16 http.HandleFunc("/getSerialPortOutput", getSerialPortOutputHandler)17 http.HandleFunc("/getDisk", getDiskHandler)18 http.HandleFunc("/createDisk", createDiskHandler)19 http.HandleFunc("/deleteDisk", deleteDiskHandler)20 http.HandleFunc("/listDisk", listDiskHandler)21 http.HandleFunc("/attachDisk", attachDiskHandler)22 http.HandleFunc("/detachDisk", detachDiskHandler)23 http.HandleFunc("/getZone", getZoneHandler)24 http.HandleFunc("/createZone", createZoneHandler)25 http.HandleFunc("/deleteZone", deleteZoneHandler)26 http.HandleFunc("/listZone", listZoneHandler)27 http.HandleFunc("/getRegion", getRegionHandler)28 http.HandleFunc("/createRegion", createRegionHandler)29 http.HandleFunc("/deleteRegion", deleteRegionHandler)30 http.HandleFunc("/listRegion", listRegionHandler)31 http.HandleFunc("/createSnapshot", createSnapshotHandler)32 http.HandleFunc("/deleteSnapshot", deleteSnapshotHandler)33 http.HandleFunc("/listSnapshot", listSnapshotHandler)34 http.HandleFunc("/getSnapshot", getSnapshotHandler)35 http.HandleFunc("/setLabelsVM", setLabelsVMHandler)36 http.HandleFunc("/getLabelsVM", getLabelsVMHandler)37 http.HandleFunc("/deleteLabelsVM", deleteLabelsVMHandler)

Full Screen

Full Screen

uploadImageToGCS

Using AI Code Generation

copy

Full Screen

1func uploadImageToGCS(w http.ResponseWriter, r *http.Request) {2 gce := gce.New("project-id")3 gce.UploadImageToGCS("bucket-name", "image-name", "image-path")4}5func uploadImageToGCS(w http.ResponseWriter, r *http.Request) {6 gce := gce.New("project-id")7 gce.UploadImageToGCS("bucket-name", "image-name", "image-path")8}9func uploadImageToGCS(w http.ResponseWriter, r *http.Request) {10 gce := gce.New("project-id")11 gce.UploadImageToGCS("bucket-name", "image-name", "image-path")12}13func uploadImageToGCS(w http.ResponseWriter, r *http.Request) {14 gce := gce.New("project-id")15 gce.UploadImageToGCS("bucket-name", "image-name", "image-path")16}17func uploadImageToGCS(w http.ResponseWriter, r *http.Request) {18 gce := gce.New("project-id")19 gce.UploadImageToGCS("bucket-name", "image-name", "image-path")20}21func uploadImageToGCS(w http.ResponseWriter, r *http.Request) {22 gce := gce.New("project-id")23 gce.UploadImageToGCS("bucket-name", "image-name", "image-path")24}25func uploadImageToGCS(w http.ResponseWriter, r *http.Request) {26 gce := gce.New("project-id")

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