Skip to content

Commit 8851570

Browse files
author
Dean Karn
authored
Merge pull request #53 from bnfinet/v5
receive docker hub notification of automated build
2 parents 26ca2ef + f1f5db7 commit 8851570

File tree

3 files changed

+218
-0
lines changed

3 files changed

+218
-0
lines changed

docker/docker.go

+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package docker
2+
3+
// this package recieves the Docker Hub Automated Build webhook
4+
// https://docs.docker.com/docker-hub/webhooks/
5+
// NOT the Docker Trusted Registry webhook
6+
// https://docs.docker.com/ee/dtr/user/create-and-manage-webhooks/
7+
8+
import (
9+
"encoding/json"
10+
"errors"
11+
"io"
12+
"io/ioutil"
13+
"net/http"
14+
)
15+
16+
// parse errors
17+
var (
18+
ErrInvalidHTTPMethod = errors.New("invalid HTTP Method")
19+
ErrParsingPayload = errors.New("error parsing payload")
20+
)
21+
22+
// Event defines a Docker hook event type
23+
type Event string
24+
25+
// Docker hook types (only one for now)
26+
const (
27+
BuildEvent Event = "build"
28+
)
29+
30+
// BuildPayload a docker hub build notice
31+
// https://docs.docker.com/docker-hub/webhooks/
32+
type BuildPayload struct {
33+
CallbackURL string `json:"callback_url"`
34+
PushData struct {
35+
Images []string `json:"images"`
36+
PushedAt float32 `json:"pushed_at"`
37+
Pusher string `json:"pusher"`
38+
Tag string `json:"tag"`
39+
} `json:"push_data"`
40+
Repository struct {
41+
CommentCount int `json:"comment_count"`
42+
DateCreated float32 `json:"date_created"`
43+
Description string `json:"description"`
44+
Dockerfile string `json:"dockerfile"`
45+
FullDescription string `json:"full_description"`
46+
IsOfficial bool `json:"is_official"`
47+
IsPrivate bool `json:"is_private"`
48+
IsTrusted bool `json:"is_trusted"`
49+
Name string `json:"name"`
50+
Namespace string `json:"namespace"`
51+
Owner string `json:"owner"`
52+
RepoName string `json:"repo_name"`
53+
RepoURL string `json:"repo_url"`
54+
StarCount int `json:"star_count"`
55+
Status string `json:"status"`
56+
} `json:"repository"`
57+
}
58+
59+
// Webhook instance contains all methods needed to process events
60+
type Webhook struct {
61+
secret string
62+
}
63+
64+
// New creates and returns a WebHook instance
65+
func New() (*Webhook, error) {
66+
hook := new(Webhook)
67+
return hook, nil
68+
}
69+
70+
// Parse verifies and parses the events specified and returns the payload object or an error
71+
func (hook Webhook) Parse(r *http.Request, events ...Event) (interface{}, error) {
72+
defer func() {
73+
_, _ = io.Copy(ioutil.Discard, r.Body)
74+
_ = r.Body.Close()
75+
}()
76+
77+
if r.Method != http.MethodPost {
78+
return nil, ErrInvalidHTTPMethod
79+
}
80+
81+
payload, err := ioutil.ReadAll(r.Body)
82+
if err != nil || len(payload) == 0 {
83+
return nil, ErrParsingPayload
84+
}
85+
86+
var pl BuildPayload
87+
err = json.Unmarshal([]byte(payload), &pl)
88+
if err != nil {
89+
return nil, ErrParsingPayload
90+
}
91+
return pl, err
92+
93+
}

docker/docker_test.go

+95
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
package docker
2+
3+
import (
4+
"log"
5+
"net/http"
6+
"net/http/httptest"
7+
"os"
8+
"testing"
9+
10+
"reflect"
11+
12+
"github.com/stretchr/testify/require"
13+
)
14+
15+
// NOTES:
16+
// - Run "go test" to run tests
17+
// - Run "gocov test | gocov report" to report on test converage by file
18+
// - Run "gocov test | gocov annotate -" to report on all code and functions, those ,marked with "MISS" were never called
19+
//
20+
// or
21+
//
22+
// -- may be a good idea to change to output path to somewherelike /tmp
23+
// go test -coverprofile cover.out && go tool cover -html=cover.out -o cover.html
24+
//
25+
26+
const (
27+
path = "/webhooks"
28+
)
29+
30+
var hook *Webhook
31+
32+
func TestMain(m *testing.M) {
33+
34+
// setup
35+
var err error
36+
hook, err = New()
37+
if err != nil {
38+
log.Fatal(err)
39+
}
40+
os.Exit(m.Run())
41+
// teardown
42+
}
43+
44+
func newServer(handler http.HandlerFunc) *httptest.Server {
45+
mux := http.NewServeMux()
46+
mux.HandleFunc(path, handler)
47+
return httptest.NewServer(mux)
48+
}
49+
50+
func TestWebhooks(t *testing.T) {
51+
assert := require.New(t)
52+
tests := []struct {
53+
name string
54+
event Event
55+
typ interface{}
56+
filename string
57+
headers http.Header
58+
}{
59+
{
60+
name: "BuildEvent",
61+
event: BuildEvent,
62+
typ: BuildPayload{},
63+
filename: "../testdata/docker/docker_hub_build_notice.json",
64+
},
65+
}
66+
67+
for _, tt := range tests {
68+
tc := tt
69+
client := &http.Client{}
70+
t.Run(tt.name, func(t *testing.T) {
71+
t.Parallel()
72+
payload, err := os.Open(tc.filename)
73+
assert.NoError(err)
74+
defer func() {
75+
_ = payload.Close()
76+
}()
77+
78+
var parseError error
79+
var results interface{}
80+
server := newServer(func(w http.ResponseWriter, r *http.Request) {
81+
results, parseError = hook.Parse(r, tc.event)
82+
})
83+
defer server.Close()
84+
req, err := http.NewRequest(http.MethodPost, server.URL+path, payload)
85+
assert.NoError(err)
86+
req.Header.Set("Content-Type", "application/json")
87+
88+
resp, err := client.Do(req)
89+
assert.NoError(err)
90+
assert.Equal(http.StatusOK, resp.StatusCode)
91+
assert.NoError(parseError)
92+
assert.Equal(reflect.TypeOf(tc.typ), reflect.TypeOf(results))
93+
})
94+
}
95+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
{
2+
"callback_url": "https://registry.hub.docker.com/u/svendowideit/testhook/hook/2141b5bi5i5b02bec211i4eeih0242eg11000a/",
3+
"push_data": {
4+
"images": [
5+
"27d47432a69bca5f2700e4dff7de0388ed65f9d3fb1ec645e2bc24c223dc1cc3",
6+
"51a9c7c1f8bb2fa19bcd09789a34e63f35abb80044bc10196e304f6634cc582c",
7+
"..."
8+
],
9+
"pushed_at": 1.417566161e+09,
10+
"pusher": "trustedbuilder",
11+
"tag": "latest"
12+
},
13+
"repository": {
14+
"comment_count": 0,
15+
"date_created": 1.417494799e+09,
16+
"description": "",
17+
"dockerfile": "#\n# BUILD\u0009\u0009docker build -t svendowideit/apt-cacher .\n# RUN\u0009\u0009docker run -d -p 3142:3142 -name apt-cacher-run apt-cacher\n#\n# and then you can run containers with:\n# \u0009\u0009docker run -t -i -rm -e http_proxy http://192.168.1.2:3142/ debian bash\n#\nFROM\u0009\u0009ubuntu\n\n\nVOLUME\u0009\u0009[/var/cache/apt-cacher-ng]\nRUN\u0009\u0009apt-get update ; apt-get install -yq apt-cacher-ng\n\nEXPOSE \u0009\u00093142\nCMD\u0009\u0009chmod 777 /var/cache/apt-cacher-ng ; /etc/init.d/apt-cacher-ng start ; tail -f /var/log/apt-cacher-ng/*\n",
18+
"full_description": "Docker Hub based automated build from a GitHub repo",
19+
"is_official": false,
20+
"is_private": true,
21+
"is_trusted": true,
22+
"name": "testhook",
23+
"namespace": "svendowideit",
24+
"owner": "svendowideit",
25+
"repo_name": "svendowideit/testhook",
26+
"repo_url": "https://registry.hub.docker.com/u/svendowideit/testhook/",
27+
"star_count": 0,
28+
"status": "Active"
29+
}
30+
}

0 commit comments

Comments
 (0)