github.com/go-chef/chef@v0.30.1/testapi/sandbox.go (about) 1 package testapi 2 3 import ( 4 "bytes" 5 "crypto/md5" 6 "crypto/rand" 7 "fmt" 8 "os" 9 ) 10 11 // random_data makes random byte slice for building junk sandbox data 12 func random_data(size int) (b []byte) { 13 b = make([]byte, size) 14 rand.Read(b) 15 return 16 } 17 18 // sandbox exercise the chef api 19 func Sandbox() { 20 client := Client(nil) 21 22 // create junk files and sums 23 files := make(map[string][]byte) 24 sums := make([]string, 10) 25 for i := 0; i < 10; i++ { 26 data := random_data(128) 27 hashstr := fmt.Sprintf("%x", md5.Sum(data)) 28 files[hashstr] = data 29 sums[i] = hashstr 30 } 31 32 // TODO: Find a sandbox delete method 33 34 // post the new sums and get a new sandbox id 35 postResp, err := client.Sandboxes.Post(sums) 36 if err != nil { 37 fmt.Fprintf(os.Stderr, "Issue making request: %+v\n", err) 38 } 39 fmt.Printf("Create sandboxes %+v\n", postResp) 40 41 // Let's upload the files that postRep thinks we should upload 42 for hash, item := range postResp.Checksums { 43 if item.Upload == true { 44 if hash == "" { 45 continue 46 } 47 // If you were writing this in your own tool you could just use the FH and let the Reader interface suck out the content instead of doing the convert. 48 fmt.Printf("\nUploading: %s ---> %v\n\n", hash, item) 49 req, err := client.NewRequest("PUT", item.Url, bytes.NewReader(files[hash])) 50 // TODO: headers = { "content-type" => "application/x-binary", "content-md5" => checksum64, "accept" => "application/json" } 51 if err != nil { 52 fmt.Fprintln(os.Stderr, "Issue this shouldn't happen:", err) 53 } 54 55 // post the files 56 upload := func() error { 57 _, err = client.Do(req, nil) 58 return err 59 } 60 61 // with exp backoff 62 err = upload() 63 fmt.Fprintln(os.Stderr, "Issue posting files to the sandbox: ", err) 64 // TODO: backoff of 4xx and 5xx doesn't make sense 65 // err = backoff.Retry(upload, backoff.NewExponentialBackOff()) 66 // if err != nil { 67 // fmt.Fprintln(os.Stderr, "Issue posting files to the sandbox: ", err) 68 // } 69 } 70 } 71 72 // Now lets tell the server we have uploaded all the things. 73 sandbox, err := client.Sandboxes.Put(postResp.ID) 74 if err != nil { 75 fmt.Fprintln(os.Stderr, "Issue commiting sandbox: ", err) 76 } 77 fmt.Printf("Resulting sandbox %+v\n", sandbox) 78 }