Best Syzkaller code snippet using gce.Close
gce.go
Source:gce.go
...52 gceKey string // per-instance private ssh key associated with the instance53 sshKey string // ssh key54 sshUser string55 closed chan bool56 consolew io.WriteCloser57}58func ctor(env *vmimpl.Env) (vmimpl.Pool, error) {59 if env.Name == "" {60 return nil, fmt.Errorf("config param name is empty (required for GCE)")61 }62 cfg := &Config{63 Count: 1,64 Preemptible: true,65 }66 if err := config.LoadData(env.Config, cfg); err != nil {67 return nil, fmt.Errorf("failed to parse gce vm config: %v", err)68 }69 if cfg.Count < 1 || cfg.Count > 1000 {70 return nil, fmt.Errorf("invalid config param count: %v, want [1, 1000]", cfg.Count)71 }72 if env.Debug && cfg.Count > 1 {73 log.Logf(0, "limiting number of VMs from %v to 1 in debug mode", cfg.Count)74 cfg.Count = 175 }76 if cfg.MachineType == "" {77 return nil, fmt.Errorf("machine_type parameter is empty")78 }79 if cfg.GCEImage == "" && cfg.GCSPath == "" {80 return nil, fmt.Errorf("gcs_path parameter is empty")81 }82 if cfg.GCEImage == "" && env.Image == "" {83 return nil, fmt.Errorf("config param image is empty (required for GCE)")84 }85 if cfg.GCEImage != "" && env.Image != "" {86 return nil, fmt.Errorf("both image and gce_image are specified")87 }88 GCE, err := gce.NewContext()89 if err != nil {90 return nil, fmt.Errorf("failed to init gce: %v", err)91 }92 log.Logf(0, "GCE initialized: running on %v, internal IP %v, project %v, zone %v, net %v/%v",93 GCE.Instance, GCE.InternalIP, GCE.ProjectID, GCE.ZoneID, GCE.Network, GCE.Subnetwork)94 if cfg.GCEImage == "" {95 cfg.GCEImage = env.Name96 gcsImage := filepath.Join(cfg.GCSPath, env.Name+"-image.tar.gz")97 log.Logf(0, "uploading image %v to %v...", env.Image, gcsImage)98 if err := uploadImageToGCS(env.Image, gcsImage); err != nil {99 return nil, err100 }101 log.Logf(0, "creating GCE image %v...", cfg.GCEImage)102 if err := GCE.DeleteImage(cfg.GCEImage); err != nil {103 return nil, fmt.Errorf("failed to delete GCE image: %v", err)104 }105 if err := GCE.CreateImage(cfg.GCEImage, gcsImage); err != nil {106 return nil, fmt.Errorf("failed to create GCE image: %v", err)107 }108 }109 pool := &Pool{110 cfg: cfg,111 env: env,112 GCE: GCE,113 }114 return pool, nil115}116func (pool *Pool) Count() int {117 return pool.cfg.Count118}119func (pool *Pool) Create(workdir string, index int) (vmimpl.Instance, error) {120 name := fmt.Sprintf("%v-%v", pool.env.Name, index)121 // Create SSH key for the instance.122 gceKey := filepath.Join(workdir, "key")123 keygen := osutil.Command("ssh-keygen", "-t", "rsa", "-b", "2048", "-N", "", "-C", "syzkaller", "-f", gceKey)124 if out, err := keygen.CombinedOutput(); err != nil {125 return nil, fmt.Errorf("failed to execute ssh-keygen: %v\n%s", err, out)126 }127 gceKeyPub, err := ioutil.ReadFile(gceKey + ".pub")128 if err != nil {129 return nil, fmt.Errorf("failed to read file: %v", err)130 }131 log.Logf(0, "deleting instance: %v", name)132 if err := pool.GCE.DeleteInstance(name, true); err != nil {133 return nil, err134 }135 log.Logf(0, "creating instance: %v", name)136 ip, err := pool.GCE.CreateInstance(name, pool.cfg.MachineType, pool.cfg.GCEImage,137 string(gceKeyPub), pool.cfg.Preemptible)138 if err != nil {139 return nil, err140 }141 ok := false142 defer func() {143 if !ok {144 pool.GCE.DeleteInstance(name, true)145 }146 }()147 sshKey := pool.env.SSHKey148 sshUser := pool.env.SSHUser149 if sshKey == "" {150 // Assuming image supports GCE ssh fanciness.151 sshKey = gceKey152 sshUser = "syzkaller"153 }154 log.Logf(0, "wait instance to boot: %v (%v)", name, ip)155 if err := vmimpl.WaitForSSH(pool.env.Debug, 5*time.Minute, ip,156 sshKey, sshUser, pool.env.OS, 22, nil); err != nil {157 output, outputErr := pool.getSerialPortOutput(name, gceKey)158 if outputErr != nil {159 output = []byte(fmt.Sprintf("failed to get boot output: %v", outputErr))160 }161 return nil, vmimpl.MakeBootError(err, output)162 }163 ok = true164 inst := &instance{165 env: pool.env,166 cfg: pool.cfg,167 debug: pool.env.Debug,168 GCE: pool.GCE,169 name: name,170 ip: ip,171 gceKey: gceKey,172 sshKey: sshKey,173 sshUser: sshUser,174 closed: make(chan bool),175 }176 return inst, nil177}178func (inst *instance) Close() {179 close(inst.closed)180 inst.GCE.DeleteInstance(inst.name, false)181 if inst.consolew != nil {182 inst.consolew.Close()183 }184}185func (inst *instance) Forward(port int) (string, error) {186 return fmt.Sprintf("%v:%v", inst.GCE.InternalIP, port), nil187}188func (inst *instance) Copy(hostSrc string) (string, error) {189 vmDst := "./" + filepath.Base(hostSrc)190 args := append(vmimpl.SCPArgs(inst.debug, inst.sshKey, 22), hostSrc, inst.sshUser+"@"+inst.ip+":"+vmDst)191 if err := runCmd(inst.debug, "scp", args...); err != nil {192 return "", err193 }194 return vmDst, nil195}196func (inst *instance) Run(timeout time.Duration, stop <-chan bool, command string) (197 <-chan []byte, <-chan error, error) {198 conRpipe, conWpipe, err := osutil.LongPipe()199 if err != nil {200 return nil, nil, err201 }202 conAddr := fmt.Sprintf("%v.%v.%v.syzkaller.port=1@ssh-serialport.googleapis.com",203 inst.GCE.ProjectID, inst.GCE.ZoneID, inst.name)204 conArgs := append(vmimpl.SSHArgs(inst.debug, inst.gceKey, 9600), conAddr)205 con := osutil.Command("ssh", conArgs...)206 con.Env = []string{}207 con.Stdout = conWpipe208 con.Stderr = conWpipe209 conw, err := con.StdinPipe()210 if err != nil {211 conRpipe.Close()212 conWpipe.Close()213 return nil, nil, err214 }215 if inst.consolew != nil {216 inst.consolew.Close()217 }218 inst.consolew = conw219 if err := con.Start(); err != nil {220 conRpipe.Close()221 conWpipe.Close()222 return nil, nil, fmt.Errorf("failed to connect to console server: %v", err)223 }224 conWpipe.Close()225 var tee io.Writer226 if inst.debug {227 tee = os.Stdout228 }229 merger := vmimpl.NewOutputMerger(tee)230 var decoder func(data []byte) (int, int, []byte)231 if inst.env.OS == "windows" {232 decoder = kd.Decode233 }234 merger.AddDecoder("console", conRpipe, decoder)235 if err := waitForConsoleConnect(merger); err != nil {236 con.Process.Kill()237 merger.Wait()238 return nil, nil, err239 }240 sshRpipe, sshWpipe, err := osutil.LongPipe()241 if err != nil {242 con.Process.Kill()243 merger.Wait()244 sshRpipe.Close()245 return nil, nil, err246 }247 if inst.env.OS == "linux" {248 if inst.sshUser != "root" {249 command = fmt.Sprintf("sudo bash -c '%v'", command)250 }251 }252 args := append(vmimpl.SSHArgs(inst.debug, inst.sshKey, 22), inst.sshUser+"@"+inst.ip, command)253 ssh := osutil.Command("ssh", args...)254 ssh.Stdout = sshWpipe255 ssh.Stderr = sshWpipe256 if err := ssh.Start(); err != nil {257 con.Process.Kill()258 merger.Wait()259 sshRpipe.Close()260 sshWpipe.Close()261 return nil, nil, fmt.Errorf("failed to connect to instance: %v", err)262 }263 sshWpipe.Close()264 merger.Add("ssh", sshRpipe)265 errc := make(chan error, 1)266 signal := func(err error) {267 select {268 case errc <- err:269 default:270 }271 }272 go func() {273 select {274 case <-time.After(timeout):275 signal(vmimpl.ErrTimeout)276 case <-stop:277 signal(vmimpl.ErrTimeout)278 case <-inst.closed:279 signal(fmt.Errorf("instance closed"))280 case err := <-merger.Err:281 con.Process.Kill()282 ssh.Process.Kill()283 merger.Wait()284 con.Wait()285 if cmdErr := ssh.Wait(); cmdErr == nil {286 // If the command exited successfully, we got EOF error from merger.287 // But in this case no error has happened and the EOF is expected.288 err = nil289 } else if merr, ok := err.(vmimpl.MergerError); ok && merr.R == conRpipe {290 // Console connection must never fail. If it does, it's either291 // instance preemption or a GCE bug. In either case, not a kernel bug.292 log.Logf(1, "%v: gce console connection failed with %v", inst.name, merr.Err)293 err = vmimpl.ErrTimeout294 } else {295 // Check if the instance was terminated due to preemption or host maintenance.296 time.Sleep(5 * time.Second) // just to avoid any GCE races297 if !inst.GCE.IsInstanceRunning(inst.name) {298 log.Logf(1, "%v: ssh exited but instance is not running", inst.name)299 err = vmimpl.ErrTimeout300 }301 }302 signal(err)303 return304 }305 con.Process.Kill()306 ssh.Process.Kill()307 merger.Wait()308 con.Wait()309 ssh.Wait()310 }()311 return merger.Output, errc, nil312}313func waitForConsoleConnect(merger *vmimpl.OutputMerger) error {314 // We've started the console reading ssh command, but it has not necessary connected yet.315 // If we proceed to running the target command right away, we can miss part316 // of console output. During repro we can crash machines very quickly and317 // would miss beginning of a crash. Before ssh starts piping console output,318 // it usually prints:319 // "serialport: Connected to ... port 1 (session ID: ..., active connections: 1)"320 // So we wait for this line, or at least a minute and at least some output.321 timeout := time.NewTimer(time.Minute)322 defer timeout.Stop()323 connectedMsg := []byte("serialport: Connected")324 permissionDeniedMsg := []byte("Permission denied (publickey)")325 var output []byte326 for {327 select {328 case out := <-merger.Output:329 output = append(output, out...)330 if bytes.Contains(output, connectedMsg) {331 // Just to make sure (otherwise we still see trimmed reports).332 time.Sleep(5 * time.Second)333 return nil334 }335 if bytes.Contains(output, permissionDeniedMsg) {336 // This is a GCE bug.337 return fmt.Errorf("broken console: %s", permissionDeniedMsg)338 }339 case <-timeout.C:340 if len(output) == 0 {341 return fmt.Errorf("broken console: no output")342 }343 return nil344 }345 }346}347func (inst *instance) Diagnose() ([]byte, bool) {348 if inst.env.OS == "openbsd" {349 return nil, vmimpl.DiagnoseOpenBSD(inst.consolew)350 }351 return nil, false352}353func (pool *Pool) getSerialPortOutput(name, gceKey string) ([]byte, error) {354 conRpipe, conWpipe, err := osutil.LongPipe()355 if err != nil {356 return nil, err357 }358 defer conRpipe.Close()359 defer conWpipe.Close()360 conAddr := fmt.Sprintf("%v.%v.%v.syzkaller.port=1.replay-lines=10000@ssh-serialport.googleapis.com",361 pool.GCE.ProjectID, pool.GCE.ZoneID, name)362 conArgs := append(vmimpl.SSHArgs(pool.env.Debug, gceKey, 9600), conAddr)363 con := osutil.Command("ssh", conArgs...)364 con.Env = []string{}365 con.Stdout = conWpipe366 con.Stderr = conWpipe367 if _, err := con.StdinPipe(); err != nil { // SSH would close connection on stdin EOF368 return nil, err369 }370 if err := con.Start(); err != nil {371 return nil, fmt.Errorf("failed to connect to console server: %v", err)372 }373 conWpipe.Close()374 done := make(chan bool)375 go func() {376 timeout := time.NewTimer(time.Minute)377 defer timeout.Stop()378 select {379 case <-done:380 case <-timeout.C:381 }382 con.Process.Kill()383 }()384 var output []byte385 buf := make([]byte, 64<<10)386 for {387 n, err := conRpipe.Read(buf)388 if err != nil || n == 0 {389 break390 }391 output = append(output, buf[:n]...)392 }393 close(done)394 con.Wait()395 return output, nil396}397func uploadImageToGCS(localImage, gcsImage string) error {398 GCS, err := gcs.NewClient()399 if err != nil {400 return fmt.Errorf("failed to create GCS client: %v", err)401 }402 defer GCS.Close()403 localReader, err := os.Open(localImage)404 if err != nil {405 return fmt.Errorf("failed to open image file: %v", err)406 }407 defer localReader.Close()408 localStat, err := localReader.Stat()409 if err != nil {410 return fmt.Errorf("failed to stat image file: %v", err)411 }412 gcsWriter, err := GCS.FileWriter(gcsImage)413 if err != nil {414 return fmt.Errorf("failed to upload image: %v", err)415 }416 defer gcsWriter.Close()417 gzipWriter := gzip.NewWriter(gcsWriter)418 tarWriter := tar.NewWriter(gzipWriter)419 tarHeader := &tar.Header{420 Name: "disk.raw",421 Typeflag: tar.TypeReg,422 Mode: 0640,423 Size: localStat.Size(),424 ModTime: time.Now(),425 Uname: "syzkaller",426 Gname: "syzkaller",427 }428 setGNUFormat(tarHeader)429 if err := tarWriter.WriteHeader(tarHeader); err != nil {430 return fmt.Errorf("failed to write image tar header: %v", err)431 }432 if _, err := io.Copy(tarWriter, localReader); err != nil {433 return fmt.Errorf("failed to write image file: %v", err)434 }435 if err := tarWriter.Close(); err != nil {436 return fmt.Errorf("failed to write image file: %v", err)437 }438 if err := gzipWriter.Close(); err != nil {439 return fmt.Errorf("failed to write image file: %v", err)440 }441 if err := gcsWriter.Close(); err != nil {442 return fmt.Errorf("failed to write image file: %v", err)443 }444 return nil445}446func runCmd(debug bool, bin string, args ...string) error {447 if debug {448 log.Logf(0, "running command: %v %#v", bin, args)449 }450 output, err := osutil.RunCmd(time.Minute, "", bin, args...)451 if debug {452 log.Logf(0, "result: %v\n%s", err, output)453 }454 return err455}...
Close
Using AI Code Generation
1import (2func main() {3 f, err := os.Open("test.txt")4 if err != nil {5 fmt.Println(err)6 }7 defer f.Close()8}
Close
Using AI Code Generation
1import (2func main() {3 file, err := os.Open("test.txt")4 if err != nil {5 fmt.Println(err)6 }7 defer file.Close()8}
Close
Using AI Code Generation
1import (2func main() {3 file, err = os.Open("test.txt")4 if err != nil {5 fmt.Println("Error in opening file")6 }7 defer file.Close()8 fmt.Println("File opened successfully")9}
Close
Using AI Code Generation
1import (2func main() {3 file, err := os.Create("test.txt")4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println("File created successfully")8 err = file.Close()9 if err != nil {10 fmt.Println(err)11 }12 fmt.Println("File closed successfully")13}
Close
Using AI Code Generation
1import (2type gce struct {3}4func (gce gce) Area() int {5}6func (gce gce) Perimeter() int {7 return 2 * (gce.width + gce.height)8}9func (gce gce) Close() {10}11func main() {12 r := gce{5, 3}13 fmt.Println(r.Area())14 fmt.Println(r.Perimeter())15 r.Close()16 fmt.Println(r.Area())17 fmt.Println(r.Perimeter())18}19import (20type gce struct {21}22func (gce gce) Area() int {23}24func (gce gce) Perimeter() int {25 return 2 * (gce.width + gce.height)26}27func (gce gce) Close() {28}29func main() {30 r := gce{5, 3}31 fmt.Println(r.Area())32 fmt.Println(r.Perimeter())33 r.Close()34 fmt.Println(r.Area())35 fmt.Println(r.Perimeter())36}37import (38type gce struct {39}40func (gce gce) Area() int {41}42func (gce gce) Perimeter() int {43 return 2 * (gce.width + gce.height)44}45func (gce gce) Close() {46}47func main() {48 r := gce{5, 3}49 fmt.Println(r.Area())50 fmt.Println(r.Perimeter())51 r.Close()52 fmt.Println(r.Area())53 fmt.Println(r.Perimeter())54}55import (
Close
Using AI Code Generation
1import (2func main() {3 c := gce.New(5, 3)4 defer c.Close()5 fmt.Println(c.Area())6}
Close
Using AI Code Generation
1import (2func main() {3 loop := s2.LoopFromPoints([]s2.Point{4 s2.PointFromLatLng(s2.LatLngFromDegrees(0, 0)),5 s2.PointFromLatLng(s2.LatLngFromDegrees(0, 10)),6 s2.PointFromLatLng(s2.LatLngFromDegrees(10, 10)),7 s2.PointFromLatLng(s2.LatLngFromDegrees(10, 0)),8 })9 cap := s2.CapFromCenterAngle(loop.Center(), s1.Angle(0))10 cell := s2.CellFromCap(cap)11 covering := []s2.CellID{cell.ID()}12 regionCovering := s2.RegionCoveringFromCellIDs(covering)13 gce := s2.GeoCoveringFromRegionCovering(regionCovering)14 gceFromLoop := s2.GeoCoveringFromLoop(loop)15 gceFromCell := s2.GeoCoveringFromCell(cell)16 gceFromCovering := s2.GeoCoveringFromCellIDs(covering)17 gceFromRegionCovering := s2.GeoCoveringFromRegionCovering(regionCovering)18 gceFromGCE := s2.GeoCoveringFromGeoCovering(gce)19 gceFromGCEFromLoop := s2.GeoCoveringFromGeoCovering(gceFromLoop)20 gceFromGCEFromCell := s2.GeoCoveringFromGeoCovering(gceFromCell)21 gceFromGCEFromCovering := s2.GeoCoveringFromGeoCovering(gceFromCovering)
Close
Using AI Code Generation
1import (2type gce struct {3}4func main() {5 obj := gce{1, 2}6 fmt.Println(obj)7 obj.Close()8}9func (obj gce) Close() {10 fmt.Println("closing object")11}
Close
Using AI Code Generation
1import (2func main() {3 a.Set(10, 20)4 a.Close()5 fmt.Println(a.Get())6}
Close
Using AI Code Generation
1import (2func main() {3 defer z01.PrintRune('\n')4 gce.Close()5}6type GCE struct{}7func (gce GCE) Close() {8 fmt.Println("Close")9}10import (11func main() {12 defer z01.PrintRune('\n')13 gce.Close()14}15type GCE struct{}16func (gce GCE) Close() {17 fmt.Println("Close")18}19import (20func main() {21 defer z01.PrintRune('\n')22 gce.Close()23}24type GCE struct{}25func (gce GCE) Close() {26 fmt.Println("Close")27}28import (29func main() {30 defer z01.PrintRune('\n')31 gce.Close()32}33type GCE struct{}34func (gce GCE) Close() {35 fmt.Println("Close")36}37import (38func main() {39 defer z01.PrintRune('\n')40 gce.Close()41}42type GCE struct{}43func (gce GCE) Close() {44 fmt.Println("Close")45}46import (47func main() {48 defer z01.PrintRune('\n')49 gce.Close()50}51type GCE struct{}52func (gce GCE) Close() {53 fmt.Println("Close")54}55import (
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!