Skip to content

Instantly share code, notes, and snippets.

@chloeruka
Last active April 12, 2019 01:40
Show Gist options
  • Save chloeruka/caeda8fea963c3363fdb10a2252d15c4 to your computer and use it in GitHub Desktop.
Save chloeruka/caeda8fea963c3363fdb10a2252d15c4 to your computer and use it in GitHub Desktop.
Query buildkite for all agent metadata
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
"github.com/buildkite/cli/graphql"
)
var (
apiToken = os.Getenv("BUILDKITE_API_TOKEN")
orgSlug = os.Getenv("BUILDKITE_ORG_SLUG")
)
func main() {
client, err := graphql.NewClient(apiToken)
if err != nil {
log.Fatalf("Could not get Buildkite GraphQL client: %s\n", err)
}
agents, err := getAllAgentMetadata(client)
if err != nil {
log.Fatalf("Could not get agent metadata: %s\n", err)
}
log.Printf("Found %d agents\n", len(agents))
for _, agent := range agents {
log.Printf("%s - metadata: %+v", agent.Name, agent.Metadata)
}
}
func getAllAgentMetadata(client *graphql.Client) ([]agent, error) {
var cursor string
var agentMetadata []agent
page := 1
for {
log.Printf("Getting page %d", page)
resp, err := client.Do(`
query AllAgentMetadata($slug: ID!, $cursor: String) {
organization(slug: $slug){
slug
agents(first: 500 after: $cursor) {
edges {
cursor
node {
id
name
metaData
}
}
pageInfo {
hasNextPage
}
}
}
}`,
map[string]interface{}{
`slug`: orgSlug,
`cursor`: cursor,
})
if err != nil {
return []agent{}, err
}
var parsed struct {
Data struct {
Organization struct {
AgentPage agentPage `json:"agents"`
} `json:"organization"`
} `json:"data"`
}
if err = resp.DecodeInto(&parsed); err != nil {
return []agent{}, fmt.Errorf("Failed to parse GraphQL response: %v", err)
}
agents := parsed.Data.Organization.AgentPage.Agents
agentMetadata = append(agentMetadata, agents...)
if parsed.Data.Organization.AgentPage.HasNextPage == false {
break
}
cursor = parsed.Data.Organization.AgentPage.LastCursor
page++
}
return agentMetadata, nil
}
type agent struct {
UUID string `json:"id"`
Name string `json:"name"`
Metadata []string `json:"metadata"`
}
type agentPage struct {
Agents []agent
HasNextPage bool
LastCursor string
}
func (a *agentPage) UnmarshalJSON(j []byte) error {
var parsed struct {
Edges []struct {
Cursor string `json:"cursor"`
Node agent `json:"node"`
} `json:"edges"`
PageInfo struct {
HasNextPage bool `json:"hasNextPage"`
} `json:"pageInfo"`
}
err := json.Unmarshal(j, &parsed)
if err != nil {
return err
}
a.HasNextPage = parsed.PageInfo.HasNextPage
a.LastCursor = parsed.Edges[len(parsed.Edges)-1].Cursor
agents := []agent{}
for _, edge := range parsed.Edges {
agents = append(agents, edge.Node)
}
a.Agents = agents
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment