Best Syzkaller code snippet using gce.runCmd
syz-gce.go
Source:syz-gce.go
...266}267// Poll executes 'git pull' on syzkaller and all depenent packages.268// Returns syzkaller HEAD hash.269func (a *SyzkallerAction) Poll() (string, error) {270 if _, err := runCmd("", "go", "get", "-u", "-d", "github.com/google/syzkaller/syz-manager"); err != nil {271 return "", err272 }273 return gitRevision("gopath/src/github.com/google/syzkaller")274}275func (a *SyzkallerAction) Build() error {276 if _, err := runCmd("gopath/src/github.com/google/syzkaller", "make"); err != nil {277 return err278 }279 return nil280}281type DashboardAction struct {282 Dash *dashboard.Dashboard283}284func (a *DashboardAction) Name() string {285 return "dashboard"286}287func (a *DashboardAction) Poll() (hash string, err error) {288 patchesHash, err = a.Dash.PollPatches()289 return patchesHash, err290}291func (a *DashboardAction) Build() (err error) {292 patches, err = a.Dash.GetPatches()293 return294}295type LocalBuildAction struct {296 Dir string297 Repo string298 Branch string299 Compiler string300 UserspaceDir string301 ImagePath string302 ImageName string303}304func (a *LocalBuildAction) Name() string {305 return "kernel"306}307func (a *LocalBuildAction) Poll() (string, error) {308 dir := filepath.Join(a.Dir, "linux")309 runCmd(dir, "git", "reset", "--hard")310 if _, err := runCmd(dir, "git", "pull"); err != nil {311 if err := os.RemoveAll(dir); err != nil {312 return "", fmt.Errorf("failed to remove repo dir: %v", err)313 }314 if err := os.MkdirAll(dir, 0700); err != nil {315 return "", fmt.Errorf("failed to create repo dir: %v", err)316 }317 if _, err := runCmd("", "git", "clone", a.Repo, dir); err != nil {318 return "", err319 }320 if _, err := runCmd(dir, "git", "pull"); err != nil {321 return "", err322 }323 }324 if a.Branch != "" {325 if _, err := runCmd(dir, "git", "checkout", a.Branch); err != nil {326 return "", err327 }328 }329 rev, err := gitRevision(dir)330 if err != nil {331 return "", err332 }333 if patchesHash != "" {334 rev += "/" + patchesHash335 }336 return rev, nil337}338func (a *LocalBuildAction) Build() error {339 dir := filepath.Join(a.Dir, "linux")340 hash, err := gitRevision(dir)341 if err != nil {342 return err343 }344 for _, p := range patches {345 if err := a.apply(p); err != nil {346 return err347 }348 }349 Logf(0, "building kernel on %v...", hash)350 if err := buildKernel(dir, a.Compiler); err != nil {351 return fmt.Errorf("build failed: %v", err)352 }353 scriptFile := filepath.Join(a.Dir, "create-gce-image.sh")354 if err := ioutil.WriteFile(scriptFile, []byte(createImageScript), 0700); err != nil {355 return fmt.Errorf("failed to write script file: %v", err)356 }357 Logf(0, "building image...")358 vmlinux := filepath.Join(dir, "vmlinux")359 bzImage := filepath.Join(dir, "arch/x86/boot/bzImage")360 if _, err := runCmd(a.Dir, scriptFile, a.UserspaceDir, bzImage, vmlinux, hash); err != nil {361 return fmt.Errorf("image build failed: %v", err)362 }363 os.Remove(filepath.Join(a.Dir, "disk.raw"))364 os.Remove(filepath.Join(a.Dir, "image.tar.gz"))365 os.MkdirAll("image/obj", 0700)366 if err := ioutil.WriteFile("image/tag", []byte(hash), 0600); err != nil {367 return fmt.Errorf("failed to write tag file: %v", err)368 }369 if err := os.Rename(filepath.Join(a.Dir, "key"), "image/key"); err != nil {370 return fmt.Errorf("failed to rename key file: %v", err)371 }372 if err := os.Rename(vmlinux, "image/obj/vmlinux"); err != nil {373 return fmt.Errorf("failed to rename vmlinux file: %v", err)374 }375 if err := createImage(filepath.Join(a.Dir, "disk.tar.gz"), a.ImagePath, a.ImageName); err != nil {376 return err377 }378 return nil379}380func (a *LocalBuildAction) apply(p dashboard.Patch) error {381 // Do --dry-run first to not mess with partially consistent state.382 cmd := exec.Command("patch", "-p1", "--force", "--ignore-whitespace", "--dry-run")383 cmd.Dir = filepath.Join(a.Dir, "linux")384 cmd.Stdin = bytes.NewReader(p.Diff)385 if output, err := cmd.CombinedOutput(); err != nil {386 // If it reverses clean, then it's already applied (seems to be the easiest way to detect it).387 cmd = exec.Command("patch", "-p1", "--force", "--ignore-whitespace", "--reverse", "--dry-run")388 cmd.Dir = filepath.Join(a.Dir, "linux")389 cmd.Stdin = bytes.NewReader(p.Diff)390 if _, err := cmd.CombinedOutput(); err == nil {391 Logf(0, "patch already present: %v", p.Title)392 return nil393 }394 Logf(0, "patch failed: %v\n%s", p.Title, output)395 return nil396 }397 // Now apply for real.398 cmd = exec.Command("patch", "-p1", "--force", "--ignore-whitespace")399 cmd.Dir = filepath.Join(a.Dir, "linux")400 cmd.Stdin = bytes.NewReader(p.Diff)401 if output, err := cmd.CombinedOutput(); err != nil {402 return fmt.Errorf("patch '%v' failed after dry run:\n%s", p.Title, output)403 }404 Logf(0, "patch applied: %v", p.Title)405 return nil406}407type GCSImageAction struct {408 ImageArchive string409 ImagePath string410 ImageName string411 handle *storage.ObjectHandle412}413func (a *GCSImageAction) Name() string {414 return "GCS image"415}416func (a *GCSImageAction) Poll() (string, error) {417 pos := strings.IndexByte(a.ImageArchive, '/')418 if pos == -1 {419 return "", fmt.Errorf("invalid GCS file name: %v", a.ImageArchive)420 }421 bkt := storageClient.Bucket(a.ImageArchive[:pos])422 f := bkt.Object(a.ImageArchive[pos+1:])423 attrs, err := f.Attrs(ctx)424 if err != nil {425 return "", fmt.Errorf("failed to read %v attributes: %v", a.ImageArchive, err)426 }427 if !attrs.Deleted.IsZero() {428 return "", fmt.Errorf("file %v is deleted", a.ImageArchive)429 }430 a.handle = f.If(storage.Conditions{431 GenerationMatch: attrs.Generation,432 MetagenerationMatch: attrs.MetaGeneration,433 })434 return attrs.Updated.Format(time.RFC1123Z), nil435}436func (a *GCSImageAction) Build() error {437 Logf(0, "downloading image archive...")438 if err := os.RemoveAll("image"); err != nil {439 return fmt.Errorf("failed to remove image dir: %v", err)440 }441 if err := downloadAndExtract(a.handle, "image"); err != nil {442 return fmt.Errorf("failed to download and extract %v: %v", a.ImageArchive, err)443 }444 if err := createImage("image/disk.tar.gz", a.ImagePath, a.ImageName); err != nil {445 return err446 }447 return nil448}449func readConfig(filename string) *Config {450 if filename == "" {451 Fatalf("supply config in -config flag")452 }453 data, err := ioutil.ReadFile(filename)454 if err != nil {455 Fatalf("failed to read config file: %v", err)456 }457 cfg := new(Config)458 if err := json.Unmarshal(data, cfg); err != nil {459 Fatalf("failed to parse config file: %v", err)460 }461 return cfg462}463func writeManagerConfig(cfg *Config, httpPort int, file string) error {464 tag, err := ioutil.ReadFile("image/tag")465 if err != nil {466 return fmt.Errorf("failed to read tag file: %v", err)467 }468 if len(tag) != 0 && tag[len(tag)-1] == '\n' {469 tag = tag[:len(tag)-1]470 }471 managerCfg := &config.Config{472 Name: cfg.Name,473 Hub_Addr: cfg.Hub_Addr,474 Hub_Key: cfg.Hub_Key,475 Dashboard_Addr: cfg.Dashboard_Addr,476 Dashboard_Key: cfg.Dashboard_Key,477 Http: fmt.Sprintf(":%v", httpPort),478 Rpc: ":0",479 Workdir: "workdir",480 Vmlinux: "image/obj/vmlinux",481 Tag: string(tag),482 Syzkaller: "gopath/src/github.com/google/syzkaller",483 Type: "gce",484 Machine_Type: cfg.Machine_Type,485 Count: cfg.Machine_Count,486 Image: cfg.Image_Name,487 Sandbox: cfg.Sandbox,488 Procs: cfg.Procs,489 Enable_Syscalls: cfg.Enable_Syscalls,490 Disable_Syscalls: cfg.Disable_Syscalls,491 Cover: true,492 }493 if _, err := os.Stat("image/key"); err == nil {494 managerCfg.Sshkey = "image/key"495 }496 data, err := json.MarshalIndent(managerCfg, "", "\t")497 if err != nil {498 return err499 }500 if err := ioutil.WriteFile(file, data, 0600); err != nil {501 return err502 }503 return nil504}505func chooseUnusedPort() (int, error) {506 ln, err := net.Listen("tcp4", ":")507 if err != nil {508 return 0, err509 }510 port := ln.Addr().(*net.TCPAddr).Port511 ln.Close()512 return port, nil513}514func downloadAndExtract(f *storage.ObjectHandle, dir string) error {515 r, err := f.NewReader(ctx)516 if err != nil {517 return err518 }519 defer r.Close()520 gz, err := gzip.NewReader(r)521 if err != nil {522 return err523 }524 files := make(map[string]bool)525 ar := tar.NewReader(gz)526 for {527 hdr, err := ar.Next()528 if err == io.EOF {529 break530 }531 if err != nil {532 return err533 }534 Logf(0, "extracting file: %v (%v bytes)", hdr.Name, hdr.Size)535 if len(hdr.Name) == 0 || hdr.Name[len(hdr.Name)-1] == '/' {536 continue537 }538 files[filepath.Clean(hdr.Name)] = true539 base, file := filepath.Split(hdr.Name)540 if err := os.MkdirAll(filepath.Join(dir, base), 0700); err != nil {541 return err542 }543 dst, err := os.OpenFile(filepath.Join(dir, base, file), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)544 if err != nil {545 return err546 }547 _, err = io.Copy(dst, ar)548 dst.Close()549 if err != nil {550 return err551 }552 }553 for _, need := range []string{"disk.tar.gz", "tag", "obj/vmlinux"} {554 if !files[need] {555 return fmt.Errorf("archive misses required file '%v'", need)556 }557 }558 return nil559}560func createImage(localFile, gcsFile, imageName string) error {561 Logf(0, "uploading image...")562 if err := uploadFile(localFile, gcsFile); err != nil {563 return fmt.Errorf("failed to upload image: %v", err)564 }565 Logf(0, "creating gce image...")566 if err := GCE.DeleteImage(imageName); err != nil {567 return fmt.Errorf("failed to delete GCE image: %v", err)568 }569 if err := GCE.CreateImage(imageName, gcsFile); err != nil {570 return fmt.Errorf("failed to create GCE image: %v", err)571 }572 return nil573}574func uploadFile(localFile, gcsFile string) error {575 local, err := os.Open(localFile)576 if err != nil {577 return err578 }579 defer local.Close()580 pos := strings.IndexByte(gcsFile, '/')581 if pos == -1 {582 return fmt.Errorf("invalid GCS file name: %v", gcsFile)583 }584 bkt := storageClient.Bucket(gcsFile[:pos])585 f := bkt.Object(gcsFile[pos+1:])586 w := f.NewWriter(ctx)587 defer w.Close()588 io.Copy(w, local)589 return nil590}591func gitRevision(dir string) (string, error) {592 output, err := runCmd(dir, "git", "log", "--pretty=format:'%H'", "-n", "1")593 if err != nil {594 return "", err595 }596 if len(output) != 0 && output[len(output)-1] == '\n' {597 output = output[:len(output)-1]598 }599 if len(output) != 0 && output[0] == '\'' && output[len(output)-1] == '\'' {600 output = output[1 : len(output)-1]601 }602 if len(output) != 40 {603 return "", fmt.Errorf("unexpected git log output, want commit hash: %q", output)604 }605 return string(output), nil606}607func buildKernel(dir, ccompiler string) error {608 os.Remove(filepath.Join(dir, ".config"))609 if _, err := runCmd(dir, "make", "defconfig"); err != nil {610 return err611 }612 if _, err := runCmd(dir, "make", "kvmconfig"); err != nil {613 return err614 }615 configFile := filepath.Join(dir, "syz.config")616 if err := ioutil.WriteFile(configFile, []byte(syzconfig), 0600); err != nil {617 return fmt.Errorf("failed to write config file: %v", err)618 }619 if _, err := runCmd(dir, "scripts/kconfig/merge_config.sh", "-n", ".config", configFile); err != nil {620 return err621 }622 if _, err := runCmd(dir, "make", "olddefconfig"); err != nil {623 return err624 }625 if _, err := runCmd(dir, "make", "-j", strconv.Itoa(runtime.NumCPU()*2), "CC="+ccompiler); err != nil {626 return err627 }628 return nil629}630func runCmd(dir, bin string, args ...string) ([]byte, error) {631 cmd := exec.Command(bin, args...)632 cmd.Dir = dir633 output, err := cmd.CombinedOutput()634 if err != nil {635 return nil, fmt.Errorf("failed to run %v %+v: %v\n%s", bin, args, err, output)636 }637 return output, nil638}639func abs(wd, path string) string {640 if !filepath.IsAbs(path) {641 path = filepath.Join(wd, path)642 }643 return path644}...
nodes_util.go
Source:nodes_util.go
1/*2Copyright 2014 The Kubernetes Authors.3Licensed under the Apache License, Version 2.0 (the "License");4you may not use this file except in compliance with the License.5You may obtain a copy of the License at6 http://www.apache.org/licenses/LICENSE-2.07Unless required by applicable law or agreed to in writing, software8distributed under the License is distributed on an "AS IS" BASIS,9WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10See the License for the specific language governing permissions and11limitations under the License.12*/13package framework14import (15 "fmt"16 "path"17 "strings"18 "time"19 "k8s.io/kubernetes/pkg/api"20 clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"21 "k8s.io/kubernetes/pkg/fields"22 "k8s.io/kubernetes/pkg/util/wait"23)24// The following upgrade functions are passed into the framework below and used25// to do the actual upgrades.26var MasterUpgrade = func(v string) error {27 switch TestContext.Provider {28 case "gce":29 return masterUpgradeGCE(v)30 case "gke":31 return masterUpgradeGKE(v)32 default:33 return fmt.Errorf("MasterUpgrade() is not implemented for provider %s", TestContext.Provider)34 }35}36func masterUpgradeGCE(rawV string) error {37 v := "v" + rawV38 _, _, err := RunCmd(path.Join(TestContext.RepoRoot, "cluster/gce/upgrade.sh"), "-M", v)39 return err40}41func masterUpgradeGKE(v string) error {42 Logf("Upgrading master to %q", v)43 _, _, err := RunCmd("gcloud", "container",44 "clusters",45 fmt.Sprintf("--project=%s", TestContext.CloudConfig.ProjectID),46 fmt.Sprintf("--zone=%s", TestContext.CloudConfig.Zone),47 "upgrade",48 TestContext.CloudConfig.Cluster,49 "--master",50 fmt.Sprintf("--cluster-version=%s", v),51 "--quiet")52 return err53}54var NodeUpgrade = func(f *Framework, v string, img string) error {55 // Perform the upgrade.56 var err error57 switch TestContext.Provider {58 case "gce":59 // TODO(maisem): add GCE support for upgrading to different images.60 err = nodeUpgradeGCE(v)61 case "gke":62 err = nodeUpgradeGKE(v, img)63 default:64 err = fmt.Errorf("NodeUpgrade() is not implemented for provider %s", TestContext.Provider)65 }66 if err != nil {67 return err68 }69 // Wait for it to complete and validate nodes are healthy.70 //71 // TODO(ihmccreery) We shouldn't have to wait for nodes to be ready in72 // GKE; the operation shouldn't return until they all are.73 Logf("Waiting up to %v for all nodes to be ready after the upgrade", RestartNodeReadyAgainTimeout)74 if _, err := CheckNodesReady(f.ClientSet, RestartNodeReadyAgainTimeout, TestContext.CloudConfig.NumNodes); err != nil {75 return err76 }77 return nil78}79func nodeUpgradeGCE(rawV string) error {80 v := "v" + rawV81 _, _, err := RunCmd(path.Join(TestContext.RepoRoot, "cluster/gce/upgrade.sh"), "-N", v)82 return err83}84func cleanupNodeUpgradeGCE(tmplBefore string) {85 Logf("Cleaning up any unused node templates")86 tmplAfter, err := MigTemplate()87 if err != nil {88 Logf("Could not get node template post-upgrade; may have leaked template %s", tmplBefore)89 return90 }91 if tmplBefore == tmplAfter {92 // The node upgrade failed so there's no need to delete93 // anything.94 Logf("Node template %s is still in use; not cleaning up", tmplBefore)95 return96 }97 Logf("Deleting node template %s", tmplBefore)98 if _, _, err := retryCmd("gcloud", "compute", "instance-templates",99 fmt.Sprintf("--project=%s", TestContext.CloudConfig.ProjectID),100 "delete",101 tmplBefore); err != nil {102 Logf("gcloud compute instance-templates delete %s call failed with err: %v", tmplBefore, err)103 Logf("May have leaked instance template %q", tmplBefore)104 }105}106func nodeUpgradeGKE(v string, img string) error {107 Logf("Upgrading nodes to version %q and image %q", v, img)108 args := []string{109 "container",110 "clusters",111 fmt.Sprintf("--project=%s", TestContext.CloudConfig.ProjectID),112 fmt.Sprintf("--zone=%s", TestContext.CloudConfig.Zone),113 "upgrade",114 TestContext.CloudConfig.Cluster,115 fmt.Sprintf("--cluster-version=%s", v),116 "--quiet",117 }118 if len(img) > 0 {119 args = append(args, fmt.Sprintf("--image-type=%s", img))120 }121 _, _, err := RunCmd("gcloud", args...)122 return err123}124// CheckNodesReady waits up to nt for expect nodes accessed by c to be ready,125// returning an error if this doesn't happen in time. It returns the names of126// nodes it finds.127func CheckNodesReady(c clientset.Interface, nt time.Duration, expect int) ([]string, error) {128 // First, keep getting all of the nodes until we get the number we expect.129 var nodeList *api.NodeList130 var errLast error131 start := time.Now()132 found := wait.Poll(Poll, nt, func() (bool, error) {133 // A rolling-update (GCE/GKE implementation of restart) can complete before the apiserver134 // knows about all of the nodes. Thus, we retry the list nodes call135 // until we get the expected number of nodes.136 nodeList, errLast = c.Core().Nodes().List(api.ListOptions{137 FieldSelector: fields.Set{"spec.unschedulable": "false"}.AsSelector()})138 if errLast != nil {139 return false, nil140 }141 if len(nodeList.Items) != expect {142 errLast = fmt.Errorf("expected to find %d nodes but found only %d (%v elapsed)",143 expect, len(nodeList.Items), time.Since(start))144 Logf("%v", errLast)145 return false, nil146 }147 return true, nil148 }) == nil149 nodeNames := make([]string, len(nodeList.Items))150 for i, n := range nodeList.Items {151 nodeNames[i] = n.ObjectMeta.Name152 }153 if !found {154 return nodeNames, fmt.Errorf("couldn't find %d nodes within %v; last error: %v",155 expect, nt, errLast)156 }157 Logf("Successfully found %d nodes", expect)158 // Next, ensure in parallel that all the nodes are ready. We subtract the159 // time we spent waiting above.160 timeout := nt - time.Since(start)161 result := make(chan bool, len(nodeList.Items))162 for _, n := range nodeNames {163 n := n164 go func() { result <- WaitForNodeToBeReady(c, n, timeout) }()165 }166 failed := false167 // TODO(mbforbes): Change to `for range` syntax once we support only Go168 // >= 1.4.169 for i := range nodeList.Items {170 _ = i171 if !<-result {172 failed = true173 }174 }175 if failed {176 return nodeNames, fmt.Errorf("at least one node failed to be ready")177 }178 return nodeNames, nil179}180// MigTemplate (GCE-only) returns the name of the MIG template that the181// nodes of the cluster use.182func MigTemplate() (string, error) {183 var errLast error184 var templ string185 key := "instanceTemplate"186 if wait.Poll(Poll, SingleCallTimeout, func() (bool, error) {187 // TODO(mikedanese): make this hit the compute API directly instead of188 // shelling out to gcloud.189 // An `instance-groups managed describe` call outputs what we want to stdout.190 output, _, err := retryCmd("gcloud", "compute", "instance-groups", "managed",191 fmt.Sprintf("--project=%s", TestContext.CloudConfig.ProjectID),192 "describe",193 fmt.Sprintf("--zone=%s", TestContext.CloudConfig.Zone),194 TestContext.CloudConfig.NodeInstanceGroup)195 if err != nil {196 errLast = fmt.Errorf("gcloud compute instance-groups managed describe call failed with err: %v", err)197 return false, nil198 }199 // The 'describe' call probably succeeded; parse the output and try to200 // find the line that looks like "instanceTemplate: url/to/<templ>" and201 // return <templ>.202 if val := ParseKVLines(output, key); len(val) > 0 {203 url := strings.Split(val, "/")204 templ = url[len(url)-1]205 Logf("MIG group %s using template: %s", TestContext.CloudConfig.NodeInstanceGroup, templ)206 return true, nil207 }208 errLast = fmt.Errorf("couldn't find %s in output to get MIG template. Output: %s", key, output)209 return false, nil210 }) != nil {211 return "", fmt.Errorf("MigTemplate() failed with last error: %v", errLast)212 }213 return templ, nil214}...
gce.go
Source:gce.go
...16var Cmd = &cobra.Command{17 Use: "gce",18}19func init() {20 Cmd.AddCommand(runCmd)21}22var runCmd = &cobra.Command{23 Use: "run",24 RunE: func(cmd *cobra.Command, args []string) error {25 ctx, cancel := context.WithCancel(context.Background())26 ctx = util.SignalContext(ctx, time.Second*5, syscall.SIGINT, syscall.SIGTERM)27 defer cancel()28 conf := config.DefaultConfig()29 // Check that this is a GCE VM environment.30 // If not, fail.31 meta, merr := gce.LoadMetadata()32 if merr != nil {33 return fmt.Errorf("can't find GCE metadata. This command requires a GCE environment")34 }35 var err error36 conf, err = gce.WithMetadataConfig(conf, meta)...
runCmd
Using AI Code Generation
1import (2type gce struct {3}4func (g gce) runCmd(cmd string) {5 fmt.Println("Running command on GCE instance")6}7type aws struct {8}9func (a aws) runCmd(cmd string) {10 fmt.Println("Running command on AWS instance")11}12type azure struct {13}14func (a azure) runCmd(cmd string) {15 fmt.Println("Running command on Azure instance")16}17func main() {18 g := gce{name: "gce1", ip: "
runCmd
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 client, err := google.DefaultClient(ctx, compute.ComputeScope)5 if err != nil {6 log.Fatal(err)7 }8 service, err := compute.New(client)9 if err != nil {10 log.Fatal(err)11 }12 g := gce{service, project, zone, instance}13 output, err := g.runCmd(cmd)14 if err != nil {15 log.Fatal(err)16 }17 fmt.Println(output)18}19import (20type gce struct {21}22func (g gce) runCmd(cmd string) (string, error) {23 Do()24 if err != nil {25 }26 if op.Contents == "" {27 return "", fmt.Errorf("no output from instance")28 }29 Do()30 if err != nil {31 }32 for {33 Do()34 if err != nil {35 }36 if op.Status == "DONE" {37 }38 }39 Do()40 if err != nil {41 }42 if op.Contents == "" {43 return "", fmt.Errorf("no output from instance")44 }
runCmd
Using AI Code Generation
1import (2type GCE struct {3}4func (gce *GCE) runCmd(command string, args ...string) {5 gce.cmd = exec.Command(command, args...)6 err := gce.cmd.Run()7 if err != nil {8 log.Fatal(err)9 }10}11func main() {12 gce := &GCE{13 }14 gce.runCmd("gcloud", "compute", "instances", "create", gce.Instance, "--image", gce.Image, "--zone", gce.Zone, "--project", gce.ProjectID)15 fmt.Println("done")16}17import (18type GCE struct {19}20func (gce *GCE) runCmd(command string, args ...string) {21 gce.cmd = exec.Command(command, args...)22 err := gce.cmd.Run()23 if err != nil {24 log.Fatal(err)25 }26}27func main() {28 gce := &GCE{29 }30 gce.runCmd("gcloud", "compute", "instances", "create", gce.Instance, "--image", gce.Image, "--zone", gce.Zone, "--project", gce.ProjectID)31 fmt.Println("done")32}
runCmd
Using AI Code Generation
1func main() {2 gce.runCmd("ls")3}4func (gce gce) runCmd(cmd string) {5}6func main() {7 gce.runCmd("ls")8}9./2.go:13: gce.runCmd undefined (type gce has no field or method runCmd)10import (11func main() {12 err := ioutil.WriteFile(file, []byte(data), 0644)13 if err != nil {14 fmt.Println("Error writing file")15 }16}17import (18func main() {19 cmd := exec.Command("ls")20 err := cmd.Run()21 if err != nil {22 fmt.Println("Error running command")23 }24}25import (
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!!