-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
243 lines (199 loc) · 6.23 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package main
import (
"cloud.google.com/go/pubsub"
"context"
"encoding/json"
fluxapi_v9 "github.com/fluxcd/flux/pkg/api/v9"
fluxhttp "github.com/fluxcd/flux/pkg/http"
fluxclient "github.com/fluxcd/flux/pkg/http/client"
"github.com/prometheus/common/log"
flag "github.com/spf13/pflag"
"golang.org/x/oauth2/google"
"google.golang.org/api/compute/v1"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"net/http"
"os"
"strings"
"time"
)
const defaultApiBase = "http://localhost:3030/api/flux"
type updateType int
const (
create updateType = iota
updateFastForward
updateNonFastForward
delete
)
var updateTypes = map[string]updateType{
"CREATE": create,
"UPDATE_FAST_FORWARD": updateFastForward,
"UPDATE_NON_FAST_FORWARD": updateNonFastForward,
"DELETE": delete,
}
type sourceRepoRefUpdate struct {
RefName string `json:"refName"`
UpdateType string `json:"updateType"`
OldId string `json:"oldId"`
NewId string `json:"newId"`
}
type sourceRepoRefUpdateEvent struct {
Email string `json:"email"`
RefUpdates map[string]sourceRepoRefUpdate `json:"refUpdates"`
}
type sourceRepoNotification struct {
Name string `json:"name"`
Url string `json:"url"`
EventTime string `json:"eventTime"`
RefUpdateEvent sourceRepoRefUpdateEvent `json:"refUpdateEvent"`
}
func main() {
var (
projectId string
subId string
topicId string
syncTimeout time.Duration
)
flags := flag.NewFlagSet("flux-recv-gcsr", flag.ExitOnError)
flags.StringVar(&projectId, "projectId", "", "project id where pubsub topic is located")
flags.StringVar(&subId, "subId", "", "subscription id to consume messages from")
flags.StringVar(&topicId, "topicId", "", "topic id to subscribe to")
flags.DurationVar(&syncTimeout, "syncTimeout", 30*time.Second, "flux sync timeout")
flags.Parse(os.Args[1:])
ctx := context.Background()
if subId == "" {
log.Fatalf("No subscription id provided")
}
if projectId == "" {
credentials, err := google.FindDefaultCredentials(ctx, compute.ComputeReadonlyScope)
if err != nil {
log.Fatal(err)
}
projectId = credentials.ProjectID
}
log.Infof("Creating pubsub client for project, %v", projectId)
client, err := pubsub.NewClient(ctx, projectId)
if err != nil {
log.Fatalf("pubsub.NewClient: %v", err)
}
defer client.Close()
cm := make(chan *pubsub.Message)
log.Infof("Creating flux client at %v", defaultApiBase)
apiClient := fluxclient.New(http.DefaultClient, fluxhttp.NewAPIRouter(), defaultApiBase, fluxclient.Token(""))
version, err := apiClient.Version(ctx)
if err != nil {
log.Fatal(err)
}
log.Infof("Flux client connected to flux %v", version)
go func() {
log.Info("Handle loop starting")
handleLoop(ctx, cm, apiClient, syncTimeout)
}()
log.Info("Preparing subscription")
sub, err := prepare(ctx, client, cm, topicId, subId, syncTimeout)
if err != nil {
log.Fatal(err)
}
log.Info("Consuming")
err = consume(ctx, sub, cm)
if err != nil {
log.Fatal(err)
}
}
func prepare(ctx context.Context, client *pubsub.Client, cm chan *pubsub.Message, topicId string, subId string, syncTimeout time.Duration) (*pubsub.Subscription, error) {
var err error
var sub *pubsub.Subscription
log.Info("Preparing consumer loop")
if topicId != "" {
log.Infof("Attempting to create subscription, %v, for topic, %v", subId, topicId)
sub, err = client.CreateSubscription(ctx, subId, pubsub.SubscriptionConfig{
Topic: client.Topic(topicId),
AckDeadline: syncTimeout,
Labels: nil,
})
if err != nil {
switch status.Code(err) {
case codes.AlreadyExists:
log.Infof("Subscription already exists: %v", err)
case codes.NotFound:
log.Errorf("Topic not found: %v", err)
return nil, err
}
}
}
if sub == nil {
sub = client.Subscription(subId)
}
log.Infof("Got subscription, %v", subId)
// Turn on synchronous mode. This makes the subscriber use the Pull RPC rather
// than the StreamingPull RPC, which is useful for guaranteeing MaxOutstandingMessages,
// the max number of messages the client will hold in memory at a time.
sub.ReceiveSettings.Synchronous = true
sub.ReceiveSettings.MaxOutstandingMessages = 10
return sub, nil
}
func handleLoop(ctx context.Context, cm chan *pubsub.Message, apiClient *fluxclient.Client, syncTimeout time.Duration) {
for {
select {
case msg := <-cm:
var notification sourceRepoNotification
if err := json.Unmarshal(msg.Data, ¬ification); err != nil {
log.Errorf("Couldn't unmarshal pubsub message data, %v", err)
}
err := handleMsg(ctx, notification, apiClient, syncTimeout)
if err == nil {
msg.Ack()
} else {
msg.Nack()
}
case <-ctx.Done():
close(cm)
return
}
}
}
func handleMsg(ctx context.Context, notification sourceRepoNotification, apiClient *fluxclient.Client, syncTimeout time.Duration) error {
log.Infof("Handling notification for repo, %v", notification.Url)
for _, ref := range notification.RefUpdateEvent.RefUpdates {
update := fluxapi_v9.GitUpdate{
URL: notification.Url,
Branch: strings.TrimPrefix(ref.RefName, "refs/heads/"),
}
change := fluxapi_v9.Change{
Kind: fluxapi_v9.GitChange,
Source: update,
}
log.Infof("Notifying flux of git update for ref, %v, on repo, %v", ref.RefName, notification.Url)
err := func() error {
ctx, cancel := context.WithTimeout(ctx, syncTimeout)
defer cancel()
err := apiClient.NotifyChange(ctx, change)
if err != nil {
select {
case <-ctx.Done():
log.Warnf("Timed out waiting for response from downstream API: %v", err)
default:
log.Errorf("Error while calling downstream API: %v", err)
}
return err
}
log.Info("Successfully notified flux")
return nil
}()
if err != nil {
return err
}
}
return nil
}
func consume(ctx context.Context, sub *pubsub.Subscription, cm chan *pubsub.Message) error {
// Receive blocks until the passed in context is done.
err := sub.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) {
log.Infof("Received message,%v, for the %vst/rd/th time", msg.ID, msg.DeliveryAttempt)
cm <- msg
})
if err != nil && status.Code(err) != codes.Canceled {
return err
}
return nil
}