|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/base64" |
| 6 | + "encoding/json" |
| 7 | + "flag" |
| 8 | + "fmt" |
| 9 | + "io" |
| 10 | + "log" |
| 11 | + "net/http" |
| 12 | + "regexp" |
| 13 | + "strings" |
| 14 | + "time" |
| 15 | + |
| 16 | + "github.com/hashicorp/go-retryablehttp" |
| 17 | +) |
| 18 | + |
| 19 | +// Define our Janky Response Structs |
| 20 | +type JankyBuildStruct struct { |
| 21 | + Result string |
| 22 | + Url string |
| 23 | +} |
| 24 | +type JankyStatusStruct struct { |
| 25 | + Id string |
| 26 | + Green bool |
| 27 | + Completed bool |
| 28 | + StartedAt string |
| 29 | + CompletedAt string |
| 30 | + Sha string |
| 31 | + BuildableName string |
| 32 | +} |
| 33 | + |
| 34 | +const ( |
| 35 | + pollWaitTime = 10 * time.Second |
| 36 | + jankyPollTimeout = 5 * time.Hour |
| 37 | + jankyHttpRetryMax = 5 |
| 38 | + jankyUrl = "https://janky.githubapp.com" |
| 39 | +) |
| 40 | + |
| 41 | +func main() { |
| 42 | + // Parse command-line arguments |
| 43 | + job := flag.String("job", "", "Name of the Janky job") |
| 44 | + token := flag.String("token", "", "Name of the Janky token") |
| 45 | + branch := flag.String("branch", "", "Name of the Git branch") |
| 46 | + force := flag.String("force", "false", "Force a build even if one is already passed") |
| 47 | + envVars := flag.String("envVars", "", "Comma separated list of key value pairs to pass to Janky - ex: key1=value1,key2=value2,key3=value3") |
| 48 | + flag.Parse() |
| 49 | + |
| 50 | + // Validate command-line arguments |
| 51 | + if *job == "" || *token == "" || *branch == "" { |
| 52 | + log.Fatal("job, token and branch flags must be specified") |
| 53 | + } |
| 54 | + |
| 55 | + // Set up the token + request payload |
| 56 | + authToken := base64.StdEncoding.EncodeToString([]byte(":" + *token)) |
| 57 | + type buildRequestObject struct { |
| 58 | + BuildableName string `json:"buildable_name"` |
| 59 | + BranchName string `json:"branch_name"` |
| 60 | + Force string `json:"force"` |
| 61 | + EnvVars map[string]string `json:"env_vars"` |
| 62 | + } |
| 63 | + |
| 64 | + requestBody := buildRequestObject{ |
| 65 | + BuildableName: *job, |
| 66 | + BranchName: *branch, |
| 67 | + Force: *force, |
| 68 | + } |
| 69 | + |
| 70 | + // Parse the envVars flag into a map and add to the request payload |
| 71 | + fmt.Println("Environment Variables:") |
| 72 | + fmt.Println(*envVars) |
| 73 | + if *envVars != "" { |
| 74 | + envVarsMap := make(map[string]string) |
| 75 | + for _, envVar := range strings.Split(*envVars, ",") { |
| 76 | + envVarSplit := strings.Split(envVar, "=") |
| 77 | + envVarsMap[envVarSplit[0]] = envVarSplit[1] |
| 78 | + } |
| 79 | + requestBody.EnvVars = envVarsMap |
| 80 | + } |
| 81 | + |
| 82 | + payloadBytes, err := json.Marshal(requestBody) |
| 83 | + if err != nil { |
| 84 | + log.Fatal("Failed to marshal the JSON payload!\n" + err.Error()) |
| 85 | + } |
| 86 | + |
| 87 | + // Send build request to Janky |
| 88 | + buildRequest, err := http.NewRequest("POST", jankyUrl+"/api/builds", bytes.NewBuffer(payloadBytes)) |
| 89 | + if err != nil { |
| 90 | + log.Fatal("Failed to create build request!\n" + err.Error()) |
| 91 | + } |
| 92 | + buildRequest.Header.Set("Content-Type", "application/json") |
| 93 | + buildRequest.Header.Set("Authorization", "Basic "+authToken) |
| 94 | + retryClient := retryablehttp.NewClient() //nolint:all |
| 95 | + retryClient.RetryMax = jankyHttpRetryMax |
| 96 | + retryClient.Logger = nil // disable debug logging |
| 97 | + client := retryClient.StandardClient() // uses *http.Client |
| 98 | + resp, err := client.Do(buildRequest) |
| 99 | + if err != nil { |
| 100 | + log.Fatal("Failed to send build request!\n" + err.Error()) |
| 101 | + } |
| 102 | + defer resp.Body.Close() |
| 103 | + body, err := io.ReadAll(resp.Body) |
| 104 | + if err != nil { |
| 105 | + log.Fatal("Error reading build response!\n" + err.Error()) |
| 106 | + } |
| 107 | + |
| 108 | + // Check if the build was triggered successfully |
| 109 | + if resp.StatusCode == 404 { |
| 110 | + log.Fatal("Failed to trigger build! Either " + *job + " is not the name of a Janky job or " + *branch + " is not a branch for the repository that job belongs to.") |
| 111 | + } |
| 112 | + if resp.StatusCode != 201 { |
| 113 | + log.Fatal("Failed to trigger build! Got exception: " + string(body)) |
| 114 | + } |
| 115 | + |
| 116 | + // Parse the build request response |
| 117 | + var buildResponse JankyBuildStruct |
| 118 | + json.Unmarshal(body, &buildResponse) |
| 119 | + log.Println("Succesfully triggered janky!\n" + buildResponse.Result) |
| 120 | + |
| 121 | + // Parse the request response for the buildId |
| 122 | + r, err := regexp.Compile("/[0-9]+/") |
| 123 | + if err != nil { |
| 124 | + log.Fatal("Failed to trigger build!\n" + err.Error()) |
| 125 | + } |
| 126 | + buildId := strings.Trim(r.FindString(buildResponse.Result), "/") |
| 127 | + |
| 128 | + // Setup our second HTTP client for reuse in during status polling |
| 129 | + jankyStatusUrl := jankyUrl + "/api/" + buildId + "/status" |
| 130 | + statusRequest, err := http.NewRequest("GET", jankyStatusUrl, nil) |
| 131 | + if err != nil { |
| 132 | + log.Fatal("Failed to create status request!\n" + err.Error()) |
| 133 | + } |
| 134 | + statusRequest.Header.Set("Content-Type", "application/json") |
| 135 | + statusRequest.Header.Set("Authorization", "Basic "+authToken) |
| 136 | + retryClient2 := retryablehttp.NewClient() //nolint:all |
| 137 | + retryClient2.RetryMax = jankyHttpRetryMax |
| 138 | + retryClient2.Logger = nil // disable debug logging |
| 139 | + client2 := retryClient2.StandardClient() // uses *http.Client |
| 140 | + |
| 141 | + // Wait for a completed status from Janky or break the loop after a certain amount of time |
| 142 | + timeout := time.NewTimer(jankyPollTimeout) |
| 143 | + poll := time.NewTicker(pollWaitTime) |
| 144 | + |
| 145 | +jobLoop: |
| 146 | + for { |
| 147 | + select { |
| 148 | + case <-timeout.C: |
| 149 | + log.Fatal("Failed to poll for build status after " + jankyPollTimeout.String() + "hours") |
| 150 | + case <-poll.C: |
| 151 | + // Send build status request to Janky |
| 152 | + statusResponse, err := client2.Do(statusRequest) |
| 153 | + if err != nil { |
| 154 | + log.Fatal("Failed to send status request!\n" + err.Error()) |
| 155 | + } |
| 156 | + defer statusResponse.Body.Close() |
| 157 | + statusBody, err := io.ReadAll(statusResponse.Body) |
| 158 | + if err != nil { |
| 159 | + log.Fatal("Error reading status response!\n" + err.Error()) |
| 160 | + } |
| 161 | + |
| 162 | + // Parse the status response for a green completed build |
| 163 | + var jankyStatusResponse JankyStatusStruct |
| 164 | + json.Unmarshal(statusBody, &jankyStatusResponse) |
| 165 | + //fmt.Println("Janky Status Response:") |
| 166 | + //fmt.Println(string(statusBody)) |
| 167 | + if jankyStatusResponse.Completed && jankyStatusResponse.Green { |
| 168 | + log.Println("Janky build Succeeded!") |
| 169 | + break jobLoop |
| 170 | + } |
| 171 | + if jankyStatusResponse.Completed && !jankyStatusResponse.Green { |
| 172 | + log.Fatal("Build failed, see Janky for more info: " + buildResponse.Url) |
| 173 | + } |
| 174 | + |
| 175 | + // wait for a bit and try again |
| 176 | + log.Println("Build still in progress, will poll for status again in [" + pollWaitTime.String() + "]") |
| 177 | + continue |
| 178 | + } |
| 179 | + } |
| 180 | +} |
0 commit comments