Best Syzkaller code snippet using gce.NewContext
node.go
Source:node.go
1// Copyright 2015 The Vanadium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4package main5import (6 "bytes"7 "fmt"8 "path/filepath"9 "strings"10 "time"11 "v.io/x/lib/cmdline"12)13var cmdNode = &cmdline.Command{14 Name: "node",15 Short: "Manage GCE nodes",16 Long: "Manage GCE nodes.",17 Children: []*cmdline.Command{cmdNodeAuthorize, cmdNodeDeauthorize, cmdNodeCreate, cmdNodeDelete},18}19var cmdNodeAuthorize = &cmdline.Command{20 Runner: cmdline.RunnerFunc(runNodeAuthorize),21 Name: "authorize",22 Short: "Authorize a user to login to a GCE node",23 Long: `24Authorizes a user to login to a GCE node (possibly as other user). For25instance, this mechanism is used to give Jenkins slave nodes access to26the GCE mirror of Vanadium repositories.27`,28 ArgsName: "<userA>@<hostA> [<userB>@]<hostB>",29 ArgsLong: `30<userA>@<hostA> [<userB>@]<hostB> authorizes userA to log into GCE31node hostB from GCE node hostA as user userB. The default value for32userB is userA.33`,34}35var cmdNodeDeauthorize = &cmdline.Command{36 Runner: cmdline.RunnerFunc(runNodeDeauthorize),37 Name: "deauthorize",38 Short: "Deauthorize a user to login to a GCE node",39 Long: `40Deuthorizes a user to login to a GCE node (possibly as other41user). For instance, this mechanism is used to revoke access of give42Jenkins slave nodes to the GCE mirror of Vanadium repositories.43`,44 ArgsName: "<userA>@<hostA> [<userB>@]<hostB>",45 ArgsLong: `46<userA>@<hostA> [<userB>@]<hostB> deauthorizes userA to log into GCE47node hostB from GCE node hostA as user userB. The default value for48userB is userA.49`,50}51func parseUserAndHost(args []string) (string, string, string, string, error) {52 if got, want := len(args), 2; got != want {53 return "", "", "", "", fmt.Errorf("unexpected number of arguments: got %v, want %d", got, want)54 }55 parseFn := func(s string) (string, string, error) {56 tokens := strings.Split(s, "@")57 switch len(tokens) {58 case 1:59 return "", tokens[0], nil60 case 2:61 return tokens[0], tokens[1], nil62 default:63 return "", "", fmt.Errorf("unexpected length of %v: expected at most %d", tokens, 2)64 }65 }66 userA, hostA, err := parseFn(args[0])67 if err != nil {68 return "", "", "", "", err69 }70 if userA == "" {71 return "", "", "", "", fmt.Errorf("failed to parse user: %v", args[0])72 }73 userB, hostB, err := parseFn(args[1])74 if err != nil {75 return "", "", "", "", err76 }77 if userB == "" {78 userB = userA79 }80 return userA, hostA, userB, hostB, nil81}82// TODO(jsimsa): Add command-line flags for specifying the name of the83// SSH key file to use and whether to create one if it does not84// exist.85func runNodeAuthorize(env *cmdline.Env, args []string) error {86 userA, hostA, userB, hostB, err := parseUserAndHost(args)87 if err != nil {88 return env.UsageErrorf("%v", err)89 }90 // Copy the public SSH key for <userA> from <hostA> to the local91 // machine.92 ctx := newContext(env)93 s := ctx.NewSeq()94 tmpDir, err := s.TempDir("", "")95 if err != nil {96 return fmt.Errorf("TempDir() failed: %v", err)97 }98 defer ctx.NewSeq().RemoveAll(tmpDir)99 allNodes, err := listAll(ctx)100 if err != nil {101 return err102 }103 nodeA, err := allNodes.MatchNames(hostA)104 if err != nil {105 return err106 }107 if err := nodeA.RunCopy(ctx, []string{fmt.Sprintf(":/home/%v/.ssh/id_rsa.pub", userA)}, tmpDir); err != nil {108 return err109 }110 // Append the key to the set of authorized keys of <userB> on111 // <hostB>.112 sshKeyFile := filepath.Join(tmpDir, "id_rsa.pub")113 bytes, err := s.ReadFile(sshKeyFile)114 if err != nil {115 return fmt.Errorf("ReadFile(%v) failed: %v", sshKeyFile, err)116 }117 nodeB, err := allNodes.MatchNames(hostB)118 if err != nil {119 return err120 }121 echoCmd := []string{"echo", strings.TrimSpace(string(bytes)), ">>", fmt.Sprintf("/home/%v/.ssh/authorized_keys", userB)}122 if err := nodeB.RunCommand(ctx, userB, echoCmd); err != nil {123 return err124 }125 return nil126}127func runNodeDeauthorize(env *cmdline.Env, args []string) error {128 userA, hostA, userB, hostB, err := parseUserAndHost(args)129 if err != nil {130 return env.UsageErrorf("%v", err)131 }132 // Remove all keys for <userA>@<hostA> from the set of authorized133 // keys of <userB> on <hostB>.134 ctx := newContext(env)135 allNodes, err := listAll(ctx)136 if err != nil {137 return err138 }139 nodeB, err := allNodes.MatchNames(hostB)140 if err != nil {141 return err142 }143 authorizedKeysFile := fmt.Sprintf("/home/%v/.ssh/authorized_keys", userB)144 tmpKeysFile := authorizedKeysFile + ".tmp"145 grepCmd := []string{"grep", "-v", fmt.Sprintf("%v@%v", userA, hostA), authorizedKeysFile, ">", tmpKeysFile}146 if err := nodeB.RunCommand(ctx, userB, grepCmd); err != nil {147 return err148 }149 moveCmd := []string{"mv", tmpKeysFile, authorizedKeysFile}150 if err := nodeB.RunCommand(ctx, userB, moveCmd); err != nil {151 return err152 }153 return nil154}155var cmdNodeCreate = &cmdline.Command{156 Runner: cmdline.RunnerFunc(runNodeCreate),157 Name: "create",158 Short: "Create GCE nodes",159 Long: `160Create GCE nodes. Runs 'gcloud compute instances create'.161`,162 ArgsName: "<names>",163 ArgsLong: "<names> is a list of names identifying nodes to be created.",164}165var cmdNodeDelete = &cmdline.Command{166 Runner: cmdline.RunnerFunc(runNodeDelete),167 Name: "delete",168 Short: "Delete GCE nodes",169 Long: `170Delete GCE nodes. Runs 'gcloud compute instances delete'.171`,172 ArgsName: "<names>",173 ArgsLong: "<names> is a list of names identifying nodes to be deleted.",174}175func runNodeCreate(env *cmdline.Env, args []string) error {176 ctx := newContext(env)177 // Create the GCE node(s).178 createArgs := []string{179 "compute",180 "--project", *flagProject,181 "instances",182 "create",183 }184 createArgs = append(createArgs, args...)185 createArgs = append(createArgs,186 "--boot-disk-size", flagBootDiskSize,187 "--image", flagImage,188 "--machine-type", flagMachineType,189 "--zone", flagZone,190 "--scopes", flagScopes,191 )192 if err := ctx.NewSeq().Last("gcloud", createArgs...); err != nil {193 return err194 }195 // Create in-memory representation of node information.196 allNodes, err := listAll(ctx)197 if err != nil {198 return err199 }200 nodes, err := allNodes.MatchNames(strings.Join(args, ","))201 if err != nil {202 return err203 }204 // Wait for the SSH server on all nodes to start up.205 const numRetries = 10206 const retryPeriod = 5 * time.Second207 ready := false208 for i := 0; i < numRetries; i++ {209 if err := nodes.RunCommand(ctx, *flagUser, []string{"echo"}); err != nil {210 fmt.Fprintf(ctx.Stdout(), "attempt #%d to connect failed, will try again later\n", i+1)211 time.Sleep(retryPeriod)212 continue213 }214 ready = true215 break216 }217 if !ready {218 return fmt.Errorf("timed out waiting for nodes to start")219 }220 // Execute the setup script.221 if flagSetupScript != "" {222 if err := nodes.RunCopyAndRun(ctx, *flagUser, []string{flagSetupScript}, nil, ""); err != nil {223 return err224 }225 }226 return nil227}228func runNodeDelete(env *cmdline.Env, args []string) error {229 ctx := newContext(env)230 // Delete the GCE node(s).231 var in bytes.Buffer232 in.WriteString("Y\n") // answers the [Y/n] prompt233 deleteArgs := []string{234 "compute",235 "--project", *flagProject,236 "instances",237 "delete",238 }239 deleteArgs = append(deleteArgs, args...)240 deleteArgs = append(deleteArgs, "--zone", flagZone)241 return ctx.NewSeq().Read(&in).Last("gcloud", deleteArgs...)242}...
main.go
Source:main.go
...94 w.Header().Set("Content-Type", "application/json")95 w.Write(json)96}97func sendExternalIp(w http.ResponseWriter, r *http.Request, project string, zone string, instance string) {98 ctx := appengine.NewContext(r)99 s, err := NewComputeService(ctx, w)100 if err != nil {101 fmt.Fprint(w, err)102 return103 }104 is := compute.NewInstancesService(s)105 insList, err := is.List(project, zone).Do()106 if err != nil {107 fmt.Fprint(w, err)108 return109 }110 for _, ins := range insList.Items {111 name := ins.Name112 status := ins.Status113 if name == instance {114 if status == "RUNNING" {115 natIp := ins.NetworkInterfaces[0].AccessConfigs[0].NatIP116 if natIp != "" {117 message := fmt.Sprintf("Minecraft server is running on : %s:25565", natIp)118 writeSlackMessage(w, message)119 }120 } else {121 message := fmt.Sprintf("instance status is %s", status)122 writeSlackMessage(w, message)123 }124 }125 }126}127func startInstance(w http.ResponseWriter, r *http.Request, project string, zone string, instance string) {128 ctx := appengine.NewContext(r)129 s, err := NewComputeService(ctx, w)130 if err != nil {131 fmt.Fprint(w, err)132 return133 }134 is := compute.NewInstancesService(s)135 insList, err := is.List(project, zone).Do()136 if err != nil {137 fmt.Fprint(w, err)138 return139 }140 for _, ins := range insList.Items {141 name := ins.Name142 status := ins.Status143 if name == instance {144 if status == "RUNNING" {145 writeSlackMessage(w, "instance is already RUNNING")146 } else {147 _, err := is.Start(project, zone, instance).Do()148 if err != nil {149 fmt.Fprint(w, err)150 return151 }152 writeSlackMessage(w, "Instance is starting now... wait for minutes..")153 }154 }155 }156}157func stopInstance(w http.ResponseWriter, r *http.Request, project string, zone string, instance string) {158 ctx := appengine.NewContext(r)159 s, err := NewComputeService(ctx, w)160 if err != nil {161 fmt.Fprint(w, err)162 return163 }164 is := compute.NewInstancesService(s)165 insList, err := is.List(project, zone).Do()166 if err != nil {167 fmt.Fprint(w, err)168 return169 }170 for _, ins := range insList.Items {171 name := ins.Name172 status := ins.Status...
vjenkins.go
Source:vjenkins.go
...71 cmdNodeCreate.Flags.StringVar(&flagProject, "project", "vanadium-internal", "GCE project of the machine.")72 tool.InitializeRunFlags(&cmdVJenkins.Flags)73}74func newContext(env *cmdline.Env) *tool.Context {75 return tool.NewContextFromEnv(env)76}77// lookupIPAddress looks up the IP address for the given GCE node.78func lookupIPAddress(ctx *tool.Context, node string) (string, error) {79 var out bytes.Buffer80 if err := ctx.NewSeq().Capture(&out, ctx.Stderr()).Last("gcloud", "compute", "instances",81 "--project", flagProject,82 "list", "--zones", flagZone, "-r", node, "--format=json"); err != nil {83 return "", err84 }85 var instances []struct {86 Name string87 NetworkInterfaces []struct {88 AccessConfigs []struct {89 NatIP string...
NewContext
Using AI Code Generation
1ctx := gce.NewContext(ctx, projectID, zone, instanceName)2ctx := gce.NewContextWithCredentials(ctx, projectID, zone, instanceName, credentials)3ctx := gce.NewContextWithClient(ctx, projectID, zone, instanceName, client)4ctx := gce.NewContextWithClientAndCredentials(ctx, projectID, zone, instanceName, client, credentials)5ctx := gce.NewContextWithClientAndCredentialsFile(ctx, projectID, zone, instanceName, client, credentialsFile)6ctx := gce.NewContextWithClientAndCredentialsJSON(ctx, projectID, zone, instanceName, client, credentialsJSON)7ctx := gce.NewContextWithClientAndCredentialsJSONReader(ctx, projectID, zone, instanceName, client, credentialsJSONReader)8ctx := gce.NewContextWithClientAndCredentialsFileReader(ctx, projectID, zone, instanceName, client, credentialsFileReader)9ctx := gce.NewContextWithClientAndCredentialsFileReader(ctx, projectID, zone, instanceName, client, credentialsFileReader)10ctx := gce.NewContextWithClientAndCredentialsFileReader(ctx, projectID, zone, instanceName, client, credentialsFileReader)11ctx := gce.NewContextWithClientAndCredentialsFileReader(ctx, projectID, zone, instanceName, client, credentialsFileReader)12ctx := gce.NewContextWithClientAndCredentialsFileReader(ctx, projectID, zone, instanceName, client, credentialsFileReader)
NewContext
Using AI Code Generation
1import (2func main() {3 if !metadata.OnGCE() {4 log.Fatal("not running on GCE")5 }6 ctx := context.Background()7 creds, err := google.FindDefaultCredentials(ctx, compute.ComputeScope)8 if err != nil {9 log.Fatal(err)10 }11 computeService, err := compute.New(creds.Client(ctx))12 if err != nil {13 log.Fatal(err)14 }15 projectID, err := metadata.ProjectID()16 if err != nil {17 log.Fatal(err)18 }19 ctx, cancel := context.WithTimeout(ctx, 5*time.Second)20 defer cancel()21 inst, err := computeService.Instances.Get(projectID, "us-central1-a", "test").Context(ctx).Do()22 if err != nil {23 log.Fatal(err)24 }25 fmt.Println(inst.Name)26}27import (28func main() {29 if !metadata.OnGCE() {30 log.Fatal("not running on GCE")31 }32 ctx := context.Background()33 creds, err := google.FindDefaultCredentials(ctx, compute.ComputeScope)34 if err != nil {35 log.Fatal(err)36 }37 computeService, err := compute.New(creds.Client(ctx))38 if err != nil {39 log.Fatal(err)40 }41 projectID, err := metadata.ProjectID()42 if err != nil {43 log.Fatal(err)44 }45 ctx, cancel := context.WithTimeout(ctx, 5*time.Second)46 defer cancel()47 inst, err := computeService.Instances.Get(projectID, "
NewContext
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 computeService, err := compute.New(client)9 if err != nil {10 log.Fatal(err)11 }12 instance, err := computeService.Instances.Get(project, zone, name).Context(ctx).Do()13 if err != nil {14 log.Fatal(err)15 }16 fmt.Printf("Instance name: %v17}18import (19func main() {20 ctx := context.Background()21 client, err := google.DefaultClient(ctx, compute.ComputeScope)22 if err != nil {23 log.Fatal(err)24 }25 computeService, err := compute.New(client)26 if err != nil {27 log.Fatal(err)28 }29 instance, err := computeService.Instances.Get(project, zone, name).Context(ctx).Do()30 if err != nil {31 log.Fatal(err)32 }33 fmt.Printf("Instance name: %v34}35import (36func main() {37 ctx := context.Background()
NewContext
Using AI Code Generation
1import (2const (3func main() {4 serviceAccount := os.Getenv("GOOGLE_SERVICE_ACCOUNT")5 if serviceAccount == "" {6 fmt.Println("GOOGLE_SERVICE_ACCOUNT must be set.")7 }8 serviceAccountKey := os.Getenv("GOOGLE_SERVICE_ACCOUNT_KEY")9 if serviceAccountKey == "" {10 fmt.Println("GOOGLE_SERVICE_ACCOUNT_KEY must be set.")11 }12 transport := &oauth.Transport{13 Config: &oauth.Config{14 Scopes: []string{computeScope},15 },16 }17 service, err := compute.New(transport.Client())18 if err != nil {19 fmt.Println("Failed to create service:", err)20 }21 instances, err := service.Instances.List("sweat-sand-540", "us-central1-a").Do()22 if err != nil {23 fmt.Println("Failed to list instances:", err)24 }25 for _, instance := range instances.Items {26 fmt.Println(instance.Name)27 }28}
NewContext
Using AI Code Generation
1import "fmt"2func main() {3 gce := new(GCE)4 gce.NewContext()5 gce.NewContext()6 gce.NewContext()7}8import "fmt"9func main() {10 gce := new(GCE)11 gce.NewContext()12 gce.NewContext()13 gce.NewContext()14}15import "fmt"16func main() {17 gce := new(GCE)18 gce.NewContext()19 gce.NewContext()20 gce.NewContext()21}22import "fmt"23func main() {24 gce := new(GCE)25 gce.NewContext()26 gce.NewContext()27 gce.NewContext()28}29import "fmt"30func main() {31 gce := new(GCE)32 gce.NewContext()33 gce.NewContext()34 gce.NewContext()35}36import "fmt"37func main() {38 gce := new(GCE)39 gce.NewContext()40 gce.NewContext()41 gce.NewContext()42}43import "fmt"44func main() {45 gce := new(GCE)46 gce.NewContext()47 gce.NewContext()48 gce.NewContext()49}
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!!