Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(425)

Side by Side Diff: milo/common/pubsub.go

Issue 2981683002: Milo: Move buildbucket pubsub sub from buildbucket project to milo project (Closed)
Patch Set: review Created 3 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | milo/common/pubsub_test.go » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 package common 1 package common
2 2
3 import ( 3 import (
4 "encoding/base64" 4 "encoding/base64"
5 "errors" 5 "errors"
6 "fmt" 6 "fmt"
7 "net/url" 7 "net/url"
8 "strings" 8 "strings"
9 "sync"
9 "time" 10 "time"
10 11
11 "cloud.google.com/go/pubsub" 12 "cloud.google.com/go/pubsub"
12 "golang.org/x/net/context" 13 "golang.org/x/net/context"
13 14
14 "github.com/luci/gae/service/info" 15 "github.com/luci/gae/service/info"
16 luciErrors "github.com/luci/luci-go/common/errors"
15 "github.com/luci/luci-go/common/logging" 17 "github.com/luci/luci-go/common/logging"
16 "github.com/luci/luci-go/milo/api/config" 18 "github.com/luci/luci-go/milo/api/config"
17 ) 19 )
18 20
19 var pubSubClientKey = "stores a pubsubClient" 21 var pubSubClientKey = "stores a pubsubClient"
20 22
21 type PubSubMessage struct { 23 type PubSubMessage struct {
22 Attributes map[string]string `json:"attributes"` 24 Attributes map[string]string `json:"attributes"`
23 Data string `json:"data"` 25 Data string `json:"data"`
24 MessageID string `json:"message_id"` 26 MessageID string `json:"message_id"`
(...skipping 20 matching lines...) Expand all
45 getTopic(string) (*pubsub.Topic, error) 47 getTopic(string) (*pubsub.Topic, error)
46 48
47 // getSubscription returns the pubsub subscription if it exists, 49 // getSubscription returns the pubsub subscription if it exists,
48 // a notExist error if it does not exist, or an error if there was an er ror. 50 // a notExist error if it does not exist, or an error if there was an er ror.
49 getSubscription(string) (*pubsub.Subscription, error) 51 getSubscription(string) (*pubsub.Subscription, error)
50 52
51 createSubscription(string, pubsub.SubscriptionConfig) ( 53 createSubscription(string, pubsub.SubscriptionConfig) (
52 *pubsub.Subscription, error) 54 *pubsub.Subscription, error)
53 } 55 }
54 56
57 type pubsubClients struct {
58 clients map[string]pubsubClient
59 lock sync.RWMutex
60 }
61
62 func newClientsBundle() *pubsubClients {
63 return &pubsubClients{
64 clients: map[string]pubsubClient{},
65 lock: sync.RWMutex{},
nodir 2017/07/12 23:06:58 this line is noop, unnecessary
Ryan Tseng 2017/07/13 01:08:26 Oh you're right, removed.
66 }
67 }
68
55 // prodPubSubClient is a wrapper around the production pubsub client. 69 // prodPubSubClient is a wrapper around the production pubsub client.
56 type prodPubSubClient struct { 70 type prodPubSubClient struct {
57 ctx context.Context 71 ctx context.Context
58 client *pubsub.Client 72 client *pubsub.Client
59 } 73 }
60 74
61 func (pc *prodPubSubClient) getTopic(id string) (*pubsub.Topic, error) { 75 func (pc *prodPubSubClient) getTopic(id string) (*pubsub.Topic, error) {
62 topic := pc.client.Topic(id) 76 topic := pc.client.Topic(id)
63 exists, err := topic.Exists(pc.ctx) 77 exists, err := topic.Exists(pc.ctx)
64 switch { 78 switch {
(...skipping 17 matching lines...) Expand all
82 return sub, nil 96 return sub, nil
83 } 97 }
84 98
85 func (pc *prodPubSubClient) createSubscription(id string, cfg pubsub.Subscriptio nConfig) ( 99 func (pc *prodPubSubClient) createSubscription(id string, cfg pubsub.Subscriptio nConfig) (
86 *pubsub.Subscription, error) { 100 *pubsub.Subscription, error) {
87 101
88 return pc.client.CreateSubscription(pc.ctx, id, cfg) 102 return pc.client.CreateSubscription(pc.ctx, id, cfg)
89 } 103 }
90 104
91 // getPubSubClient extracts a debug PubSub client out of the context. 105 // getPubSubClient extracts a debug PubSub client out of the context.
92 func getPubSubClient(c context.Context) (pubsubClient, error) { 106 func getPubSubClient(c context.Context, projectID string) (pubsubClient, error) {
93 » if client, ok := c.Value(&pubSubClientKey).(pubsubClient); ok { 107 » v := c.Value(&pubSubClientKey)
94 » » return client, nil 108 » if clients, ok := v.(*pubsubClients); ok {
109 » » clients.lock.RLock()
110 » » client, ok := clients.clients[projectID]
111 » » clients.lock.RUnlock()
112 » » if ok {
113 » » » return client, nil
114 » » }
115 » » return nil, fmt.Errorf("no pubsub clients installed for " + proj ectID)
95 } 116 }
96 return nil, errors.New("no pubsub clients installed") 117 return nil, errors.New("no pubsub clients installed")
97 } 118 }
98 119
99 // withClient returns a context with a pubsub client instantiated to the 120 // withClient returns a context with a pubsub client instantiated to the
100 // given project ID 121 // given project ID
101 func withClient(c context.Context, projectID string) (context.Context, error) { 122 func withClient(c context.Context, projectID string) (context.Context, error) {
102 if projectID == "" { 123 if projectID == "" {
103 » » return nil, errors.New("missing buildbucket project") 124 » » return nil, errors.New("missing project id")
104 } 125 }
105 client, err := pubsub.NewClient(c, projectID) 126 client, err := pubsub.NewClient(c, projectID)
106 if err != nil { 127 if err != nil {
107 return nil, err 128 return nil, err
108 } 129 }
109 » return context.WithValue(c, &pubSubClientKey, &prodPubSubClient{c, clien t}), nil 130 » var clients *pubsubClients
131 » var ok bool
132 » if clients, ok = c.Value(&pubSubClientKey).(*pubsubClients); !ok {
133 » » clients = newClientsBundle()
134 » » c = context.WithValue(c, &pubSubClientKey, clients)
135 » }
136 » clients.lock.Lock()
137 » clients.clients[projectID] = &prodPubSubClient{c, client}
nodir 2017/07/12 23:06:58 this may cause a memory leak. Consider: - there i
Ryan Tseng 2017/07/13 01:08:26 I see, you're right. I used this pattern only bec
Ryan Tseng 2017/07/13 02:42:57 Actually on second thought, withClient() is called
nodir 2017/07/13 05:58:46 indeed, pubsub client is not global. my concern w
Ryan Tseng 2017/07/13 18:02:30 I think it is very confusing to have multiple ways
nodir 2017/07/13 19:38:39 I understand that you prefer services be in contex
nodir 2017/07/13 21:55:00 another issue with the current patchset is: c1 :=
138 » clients.lock.Unlock()
139 » return c, nil
110 } 140 }
111 141
112 func getTopic(c context.Context, id string) (*pubsub.Topic, error) { 142 func getTopic(c context.Context, project, id string) (*pubsub.Topic, error) {
113 » client, err := getPubSubClient(c) 143 » client, err := getPubSubClient(c, project)
114 if err != nil { 144 if err != nil {
115 return nil, err 145 return nil, err
116 } 146 }
117 return client.getTopic(id) 147 return client.getTopic(id)
118 } 148 }
119 149
120 func getSubscription(c context.Context, id string) (*pubsub.Subscription, error) { 150 func getSubscription(c context.Context, project, id string) (*pubsub.Subscriptio n, error) {
121 » client, err := getPubSubClient(c) 151 » client, err := getPubSubClient(c, project)
122 if err != nil { 152 if err != nil {
123 return nil, err 153 return nil, err
124 } 154 }
125 return client.getSubscription(id) 155 return client.getSubscription(id)
126 } 156 }
127 157
128 func createSubscription(c context.Context, id string, cfg pubsub.SubscriptionCon fig) ( 158 func createSubscription(c context.Context, project, id string, cfg pubsub.Subscr iptionConfig) (
129 *pubsub.Subscription, error) { 159 *pubsub.Subscription, error) {
130 160
131 » client, err := getPubSubClient(c) 161 » client, err := getPubSubClient(c, project)
132 if err != nil { 162 if err != nil {
133 return nil, err 163 return nil, err
134 } 164 }
135 return client.createSubscription(id, cfg) 165 return client.createSubscription(id, cfg)
136 } 166 }
137 167
138 // EnsurePubSubSubscribed makes sure the following subscriptions are in place: 168 // EnsurePubSubSubscribed makes sure the following subscriptions are in place:
139 // * buildbucket, via the settings.Buildbucket.Topic setting 169 // * buildbucket, via the settings.Buildbucket.Topic setting
140 func EnsurePubSubSubscribed(c context.Context, settings *config.Settings) error { 170 func EnsurePubSubSubscribed(c context.Context, settings *config.Settings) error {
141 if settings.Buildbucket != nil { 171 if settings.Buildbucket != nil {
142 // Install the production pubsub client pointing to the buildbuc ket project 172 // Install the production pubsub client pointing to the buildbuc ket project
143 » » // into the context. 173 » » // into the context, so that we can get a reference to the topic .
144 c, err := withClient(c, settings.Buildbucket.Project) 174 c, err := withClient(c, settings.Buildbucket.Project)
145 if err != nil { 175 if err != nil {
146 return err 176 return err
147 } 177 }
178 // We also need a client for this project for the subscription.
179 c, err = withClient(c, info.AppID(c))
180 if err != nil {
181 return err
182 }
148 return ensureBuildbucketSubscribed(c, settings.Buildbucket.Proje ct) 183 return ensureBuildbucketSubscribed(c, settings.Buildbucket.Proje ct)
149 } 184 }
150 // TODO(hinoka): Ensure buildbot subscribed. 185 // TODO(hinoka): Ensure buildbot subscribed.
151 return nil 186 return nil
152 } 187 }
153 188
154 // ensureSubscribed is called by a cron job and ensures that the Milo 189 // ensureSubscribed is called by a cron job and ensures that the Milo
155 // instance is properly subscribed to the buildbucket subscription endpoint. 190 // instance is properly subscribed to the buildbucket subscription endpoint.
156 func ensureBuildbucketSubscribed(c context.Context, projectID string) error { 191 func ensureBuildbucketSubscribed(c context.Context, projectID string) error {
157 topicID := "builds" 192 topicID := "builds"
158 // Check to see if the topic exists first. 193 // Check to see if the topic exists first.
159 » topic, err := getTopic(c, topicID) 194 » topic, err := getTopic(c, projectID, topicID)
160 switch err { 195 switch err {
161 case errNotExist: 196 case errNotExist:
162 » » logging.WithError(err).Errorf(c, "%s does not exist", topicID) 197 » » luciErrors.Annotate(err, "%s does not exist", topicID).Err()
nodir 2017/07/12 23:06:58 this is noop because the return value of Err() is
Ryan Tseng 2017/07/13 01:08:26 my bad, thanks.
163 return err 198 return err
164 case nil: 199 case nil:
165 // continue 200 // continue
166 default: 201 default:
167 if strings.Contains(err.Error(), "PermissionDenied") { 202 if strings.Contains(err.Error(), "PermissionDenied") {
168 URL := "https://console.cloud.google.com/iam-admin/iam/p roject?project=" + projectID 203 URL := "https://console.cloud.google.com/iam-admin/iam/p roject?project=" + projectID
169 acct, serr := info.ServiceAccount(c) 204 acct, serr := info.ServiceAccount(c)
170 if serr != nil { 205 if serr != nil {
171 acct = fmt.Sprintf("Unknown: %s", serr.Error()) 206 acct = fmt.Sprintf("Unknown: %s", serr.Error())
172 } 207 }
173 // The documentation is incorrect. We need Editor permi ssion because 208 // The documentation is incorrect. We need Editor permi ssion because
174 // the Subscriber permission does NOT permit attaching s ubscriptions to 209 // the Subscriber permission does NOT permit attaching s ubscriptions to
175 // topics or to view topics. 210 // topics or to view topics.
176 logging.WithError(err).Errorf( 211 logging.WithError(err).Errorf(
177 c, "please go to %s and add %s as a Pub/Sub Edit or", URL, acct) 212 c, "please go to %s and add %s as a Pub/Sub Edit or", URL, acct)
178 } else { 213 } else {
179 logging.WithError(err).Errorf(c, "could not check topic %#v", topic) 214 logging.WithError(err).Errorf(c, "could not check topic %#v", topic)
180 } 215 }
181 return err 216 return err
182 } 217 }
183 // Now check to see if the subscription already exists. 218 // Now check to see if the subscription already exists.
184 » subID := info.AppID(c) 219 » appID := info.AppID(c)
185 » // Get the pubsub module of our app. We do not want to use info.ModuleH ostname() 220 » sub, err := getSubscription(c, appID, "buildbucket")
186 » // because it returns a version pinned hostname instead of the default r oute.
187 » sub, err := getSubscription(c, subID)
188 switch err { 221 switch err {
189 case errNotExist: 222 case errNotExist:
190 // continue 223 // continue
191 case nil: 224 case nil:
192 logging.Infof(c, "subscription %#v exists, no need to update", s ub) 225 logging.Infof(c, "subscription %#v exists, no need to update", s ub)
193 return nil 226 return nil
194 default: 227 default:
195 logging.WithError(err).Errorf(c, "could not check subscription % #v", sub) 228 logging.WithError(err).Errorf(c, "could not check subscription % #v", sub)
196 return err 229 return err
197 } 230 }
231 // Get the pubsub module of our app. We do not want to use info.ModuleH ostname()
232 // because it returns a version pinned hostname instead of the default r oute.
198 pubsubModuleHost := "pubsub." + info.DefaultVersionHostname(c) 233 pubsubModuleHost := "pubsub." + info.DefaultVersionHostname(c)
199 234
200 // No subscription exists, attach a new subscription to the existing top ic. 235 // No subscription exists, attach a new subscription to the existing top ic.
201 endpointURL := url.URL{ 236 endpointURL := url.URL{
202 Scheme: "https", 237 Scheme: "https",
203 Host: pubsubModuleHost, 238 Host: pubsubModuleHost,
204 Path: "/_ah/push-handlers/buildbucket", 239 Path: "/_ah/push-handlers/buildbucket",
205 } 240 }
206 subConfig := pubsub.SubscriptionConfig{ 241 subConfig := pubsub.SubscriptionConfig{
207 Topic: topic, 242 Topic: topic,
208 PushConfig: pubsub.PushConfig{Endpoint: endpointURL.String()}, 243 PushConfig: pubsub.PushConfig{Endpoint: endpointURL.String()},
209 AckDeadline: time.Minute * 10, 244 AckDeadline: time.Minute * 10,
210 } 245 }
211 » newSub, err := createSubscription(c, subID, subConfig) 246 » newSub, err := createSubscription(c, appID, "buildbucket", subConfig)
212 if err != nil { 247 if err != nil {
213 » » if strings.Contains(err.Error(), "The supplied HTTP URL is not r egistered") { 248 » » return luciErrors.Annotate(err, "could not create subscription % #v", sub).Err()
214 » » » registerURL := "https://console.cloud.google.com/apis/cr edentials/domainverification?project=" + projectID
215 » » » verifyURL := "https://www.google.com/webmasters/verifica tion/verification?hl=en-GB&siteUrl=http://" + pubsubModuleHost
216 » » » logging.WithError(err).Errorf(
217 » » » » c, "The domain has to be verified and added.\n\n "+
218 » » » » » "1. Go to %s\n"+
219 » » » » » "2. Verify the domain\n"+
220 » » » » » "3. Go to %s\n"+
221 » » » » » "4. Add %s to allowed domains\n\n",
222 » » » » verifyURL, registerURL, pubsubModuleHost)
223 » » } else {
224 » » » logging.WithError(err).Errorf(c, "could not create subsc ription %#v", sub)
225 » » }
226 » » return err
227 } 249 }
228 // Success! 250 // Success!
229 logging.Infof(c, "successfully created subscription %#v", newSub) 251 logging.Infof(c, "successfully created subscription %#v", newSub)
230 return nil 252 return nil
231 } 253 }
OLDNEW
« no previous file with comments | « no previous file | milo/common/pubsub_test.go » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698