Add hub stats function

This commit is contained in:
Alex 2017-01-08 17:10:17 +00:00
parent 37ad1e8e84
commit 86b4cfbb49
5 changed files with 87 additions and 0 deletions

View File

@ -0,0 +1 @@
DockerHubStats

View File

@ -0,0 +1,13 @@
FROM golang:1.7.3-alpine
MAINTAINER alexellis2@gmail.com
ENTRYPOINT []
RUN apk --no-cache add make
WORKDIR /go/src/github.com/alexellis/faas/sample-functions/DockerHubStats
COPY . /go/src/github.com/alexellis/faas/sample-functions/DockerHubStats
RUN make
COPY fwatchdog /usr/bin/fwatchdog
ENV fprocess "/go/bin/DockerHubStats"
CMD [ "/usr/bin/fwatchdog"]

View File

@ -0,0 +1,9 @@
.PHONY: install image
install:
@go install .
image:
@docker build -t alexellis2/dockerhub-stats .

View File

@ -0,0 +1,11 @@
Building:
```
# docker service rm hubstats ; docker service create --network=functions --name=hubstats alexellis2/dockerhub-stats
```
Query the function through the gateway:
```
# curl -X POST -d "alexellis2" -v http://localhost:8080/function/hubstats
```

View File

@ -0,0 +1,53 @@
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
type dockerHubStatsType struct {
Count int `json:"count"`
}
func sanitizeInput(input string) string {
parts := strings.Split(input, "\n")
return strings.Trim(parts[0], " ")
}
func requestHubStats(org string) dockerHubStatsType {
client := http.Client{}
res, err := client.Get("https://hub.docker.com/v2/repositories/" + org)
if err != nil {
log.Fatalln("Unable to reach Docker Hub server.")
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatalln("Unable to parse response from server.")
}
dockerHubStats := dockerHubStatsType{}
json.Unmarshal(body, &dockerHubStats)
return dockerHubStats
}
func main() {
input, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatal("Unable to read standard input:", err)
}
org := string(input)
if len(input) == 0 {
log.Fatalln("A username or organisation is required.")
}
org = sanitizeInput(org)
dockerHubStats := requestHubStats(org)
fmt.Printf("The organisation or user %s has %d repositories on the Docker hub.\n", org, dockerHubStats.Count)
}