Skip to content

Instantly share code, notes, and snippets.

@jhinrichsen
Created April 12, 2018 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhinrichsen/980fa75f97cbd15577fe7af5c9ae9c93 to your computer and use it in GitHub Desktop.
Save jhinrichsen/980fa75f97cbd15577fe7af5c9ae9c93 to your computer and use it in GitHub Desktop.
Schedule Sonatype Nexus tasks that rebuild npm metadata via REST
// Schedule Nexus tasks that rebuild npm metadata via REST
// Logging on stderr, run response as JSON on stdout
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
)
var (
server = flag.String("server", "localhost", "Nexus server IP")
port = flag.Int("port", 8081, "Nexus server port")
contextRoot = flag.String("contextRoot", "/nexus", "Nexus context root")
username = flag.String("username", "admin",
"Nexus user w/ appropriate rights")
password = flag.String("password", "admin123", "Nexus password")
name = flag.String("name", "Rebuild hosted npm-hosted metadata",
"Nexus schedule name")
)
type SchedulesResponse struct {
Data []Schedule
}
type Schedule struct {
ID string // is int in reality
Enabled bool
Name string
ResourceURI string
Status string
Type string
TypeName string
}
func main() {
flag.Parse()
url := fmt.Sprintf("http://%s:%d%s/service/local/schedules",
*server, *port, *contextRoot)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Add("Accept", "application/json")
req.SetBasicAuth(*username, *password)
client := &http.Client{}
log.Printf("Fetching %s\n", url)
res, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
if res.StatusCode != http.StatusOK {
log.Fatalf("Expected status code %d but got %d",
http.StatusOK, res.StatusCode)
}
defer res.Body.Close()
ss := &SchedulesResponse{}
buf, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
log.Printf("Schedules: %v\n", string(buf))
if err := json.Unmarshal(buf, ss); err != nil {
log.Fatal(err)
}
log.Printf("%+v\n", ss)
for _, s := range ss.Data {
if s.Name == *name {
log.Printf("Run schedule «%s»\n", s.Name)
u := "http://%s:%d%s/service/local/schedule_run/%s"
url := fmt.Sprintf(u, *server, *port, *contextRoot, s.ID)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Add("Accept", "application/json")
req.SetBasicAuth(*username, *password)
res, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
log.Fatalf("Expected status code %d but got %d",
http.StatusOK, res.StatusCode)
}
io.Copy(os.Stdout, res.Body)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment