Debian Codegraph @

api/v0/messenger/messenger.go

raw symbols SCIP
1 /**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 package messenger
20
21 import (
22 "fmt"
23 "net"
24 "reflect"
25 "strconv"
26 "sync"
27
28 "github.com/gogo/protobuf/proto"
29 log "github.com/golang/glog"
30 mesos "github.com/mesos/mesos-go/api/v0/mesosproto"
31 "github.com/mesos/mesos-go/api/v0/mesosproto/scheduler"
32 "github.com/mesos/mesos-go/api/v0/mesosutil/process"
33 "github.com/mesos/mesos-go/api/v0/messenger/sessionid"
34 "github.com/mesos/mesos-go/api/v0/upid"
35 "golang.org/x/net/context"
36 )
37
38 const (
39 defaultQueueSize = 1024
40 )
41
42 // MessageHandler is the callback of the message. When the callback
43 // is invoked, the sender's upid and the message is passed to the callback.
44 type MessageHandler func(from *upid.UPID, pbMsg proto.Message)
45
46 // Messenger defines the interfaces that should be implemented.
47 type Messenger interface {
48 Install(handler MessageHandler, msg proto.Message) error
49 Send(ctx context.Context, upid *upid.UPID, msg proto.Message) error
50 Route(ctx context.Context, from *upid.UPID, msg proto.Message) error
51 Start() error
52 Stop() error
53 UPID() upid.UPID
54 }
55
56 type errorHandlerFunc func(context.Context, *Message, error) error
57 type dispatchFunc func(errorHandlerFunc)
58
59 // MesosMessenger is an implementation of the Messenger interface.
60 type MesosMessenger struct {
61 upid upid.UPID
62 sendingQueue chan dispatchFunc
63 installedMessages map[string]reflect.Type
64 installedHandlers map[string]MessageHandler
65 stop chan struct{}
66 stopOnce sync.Once
67 tr Transporter
68 guardHandlers sync.RWMutex // protect simultaneous changes to messages/handlers maps
69 }
70
71 // ForHostname creates a new default messenger (HTTP), using UPIDBindingAddress to
72 // determine the binding-address used for both the UPID.Host and Transport binding address.
73 func ForHostname(proc *process.Process, hostname string, bindingAddress net.IP, port uint16, publishedAddress net.IP) (Messenger, error) {
74 upid := upid.UPID{
75 ID: proc.Label(),
76 Port: strconv.Itoa(int(port)),
77 }
78 host, err := UPIDBindingAddress(hostname, bindingAddress)
79 if err != nil {
80 return nil, err
81 }
82
83 var publishedHost string
84 if publishedAddress != nil {
85 publishedHost, err = UPIDBindingAddress(hostname, publishedAddress)
86 if err != nil {
87 return nil, err
88 }
89 }
90
91 if publishedHost != "" {
92 upid.Host = publishedHost
93 } else {
94 upid.Host = host
95 }
96
97 return NewHttpWithBindingAddress(upid, bindingAddress), nil
98 }
99
100 // UPIDBindingAddress determines the value of UPID.Host that will be used to build
101 // a Transport. If a non-nil, non-wildcard bindingAddress is specified then it will be used
102 // for both the UPID and Transport binding address. Otherwise hostname is resolved to an IP
103 // address and the UPID.Host is set to that address and the bindingAddress is passed through
104 // to the Transport.
105 func UPIDBindingAddress(hostname string, bindingAddress net.IP) (string, error) {
106 upidHost := ""
107 if bindingAddress != nil && "0.0.0.0" != bindingAddress.String() {
108 upidHost = bindingAddress.String()
109 } else {
110 if hostname == "" || hostname == "0.0.0.0" {
111 return "", fmt.Errorf("invalid hostname (%q) specified with binding address %v", hostname, bindingAddress)
112 }
113 ip := net.ParseIP(hostname)
114 if ip != nil {
115 ip = ip.To4()
116 }
117 if ip == nil {
118 ips, err := net.LookupIP(hostname)
119 if err != nil {
120 return "", err
121 }
122 // try to find an ipv4 and use that
123 for _, addr := range ips {
124 if ip = addr.To4(); ip != nil {
125 break
126 }
127 }
128 if ip == nil {
129 // no ipv4? best guess, just take the first addr
130 if len(ips) > 0 {
131 ip = ips[0]
132 log.Warningf("failed to find an IPv4 address for '%v', best guess is '%v'", hostname, ip)
133 } else {
134 return "", fmt.Errorf("failed to determine IP address for host '%v'", hostname)
135 }
136 }
137 }
138 upidHost = ip.String()
139 }
140 return upidHost, nil
141 }
142
143 // NewMesosMessenger creates a new mesos messenger.
144 func NewHttp(upid upid.UPID, opts ...httpOpt) *MesosMessenger {
145 return NewHttpWithBindingAddress(upid, nil, opts...)
146 }
147
148 func NewHttpWithBindingAddress(upid upid.UPID, address net.IP, opts ...httpOpt) *MesosMessenger {
149 return New(NewHTTPTransporter(upid, address, opts...))
150 }
151
152 func New(t Transporter) *MesosMessenger {
153 return &MesosMessenger{
154 sendingQueue: make(chan dispatchFunc, defaultQueueSize),
155 installedMessages: make(map[string]reflect.Type),
156 installedHandlers: make(map[string]MessageHandler),
157 tr: t,
158 }
159 }
160
161 /// Install installs the handler with the given message.
162 func (m *MesosMessenger) Install(handler MessageHandler, msg proto.Message) error {
163 // Check if the message is a pointer.
164 mtype := reflect.TypeOf(msg)
165 if mtype.Kind() != reflect.Ptr {
166 return fmt.Errorf("Message %v is not a Ptr type", msg)
167 }
168
169 // Check if the message is already installed.
170 name := getMessageName(msg)
171 if _, ok := m.installedMessages[name]; ok {
172 return fmt.Errorf("Message %v is already installed", name)
173 }
174
175 m.guardHandlers.Lock()
176 defer m.guardHandlers.Unlock()
177
178 m.installedMessages[name] = mtype.Elem()
179 m.installedHandlers[name] = handler
180 m.tr.Install(name)
181 return nil
182 }
183
184 // Send puts a message into the outgoing queue, waiting to be sent.
185 // With buffered channels, this will not block under moderate throughput.
186 // When an error is generated, the error can be communicated by placing
187 // a message on the incoming queue to be handled upstream.
188 func (m *MesosMessenger) Send(ctx context.Context, upid *upid.UPID, msg proto.Message) error {
189 if upid == nil {
190 panic("cannot sent a message to a nil pid")
191 } else if *upid == m.upid {
192 return fmt.Errorf("Send the message to self")
193 }
194
195 b, err := proto.Marshal(msg)
196 if err != nil {
197 return err
198 }
199
200 name := getMessageName(msg)
201 log.V(2).Infof("Sending message %v to %v\n", name, upid)
202
203 wrapped := &Message{upid, name, msg, b}
204 d := dispatchFunc(func(rf errorHandlerFunc) {
205 err := m.tr.Send(ctx, wrapped)
206 err = rf(ctx, wrapped, err)
207 if err != nil {
208 m.reportError("send", wrapped, err)
209 }
210 })
211 select {
212 case <-ctx.Done():
213 return ctx.Err()
214 case m.sendingQueue <- d:
215 return nil
216 }
217 }
218
219 // Route puts a message either in the incoming or outgoing queue.
220 // This method is useful for:
221 // 1) routing internal error to callback handlers
222 // 2) testing components without starting remote servers.
223 func (m *MesosMessenger) Route(ctx context.Context, upid *upid.UPID, msg proto.Message) error {
224 if upid == nil {
225 panic("cannot route a message to a nil pid")
226 } else if *upid != m.upid {
227 // if destination is not self, send to outbound.
228 return m.Send(ctx, upid, msg)
229 }
230
231 name := getMessageName(msg)
232 log.V(2).Infof("routing message %q to self", name)
233
234 _, handler, ok := m.messageBinding(name)
235 if !ok {
236 return fmt.Errorf("failed to route message, no message binding for %q", name)
237 }
238
239 // the implication of this is that messages can be delivered to self even if the
240 // messenger has been stopped. is that OK?
241 go handler(upid, msg)
242 return nil
243 }
244
245 // Start starts the messenger; expects to be called once and only once.
246 func (m *MesosMessenger) Start() error {
247
248 m.stop = make(chan struct{})
249
250 pid, errChan := m.tr.Start()
251 if pid == (upid.UPID{}) {
252 err := <-errChan
253 return fmt.Errorf("failed to start messenger: %v", err)
254 }
255
256 // the pid that we're actually bound as
257 m.upid = pid
258
259 go m.sendLoop()
260 go m.decodeLoop()
261
262 // wait for a listener error or a stop signal; either way stop the messenger
263
264 // TODO(jdef) a better implementation would attempt to re-listen; need to coordinate
265 // access to m.upid in that case. probably better off with a state machine instead of
266 // what we have now.
267 go func() {
268 select {
269 case err := <-errChan:
270 if err != nil {
271 //TODO(jdef) should the driver abort in this case? probably
272 //since this messenger will never attempt to re-establish the
273 //transport
274 log.Errorln("transport stopped unexpectedly:", err.Error())
275 }
276 err = m.Stop()
277 if err != nil && err != errTerminal {
278 log.Errorln("failed to stop messenger cleanly: ", err.Error())
279 }
280 case <-m.stop:
281 }
282 }()
283 return nil
284 }
285
286 // Stop stops the messenger and clean up all the goroutines.
287 func (m *MesosMessenger) Stop() (err error) {
288 m.stopOnce.Do(func() {
289 select {
290 case <-m.stop:
291 default:
292 defer close(m.stop)
293 }
294
295 log.Infof("stopping messenger %v..", m.upid)
296
297 //TODO(jdef) don't hardcode the graceful flag here
298 if err2 := m.tr.Stop(true); err2 != nil && err2 != errTerminal {
299 log.Warningf("failed to stop the transporter: %v\n", err2)
300 err = err2
301 }
302 })
303 return
304 }
305
306 // UPID returns the upid of the messenger.
307 func (m *MesosMessenger) UPID() upid.UPID {
308 return m.upid
309 }
310
311 func (m *MesosMessenger) reportError(action string, msg *Message, err error) {
312 // log message transmission errors but don't shoot the messenger.
313 // this approach essentially drops all undelivered messages on the floor.
314 name := ""
315 if msg != nil {
316 name = msg.Name
317 }
318 log.Errorf("failed to %s message %q: %+v", action, name, err)
319 }
320
321 func (m *MesosMessenger) sendLoop() {
322 for {
323 select {
324 case <-m.stop:
325 return
326 case f := <-m.sendingQueue:
327 f(errorHandlerFunc(func(ctx context.Context, msg *Message, err error) error {
328 if _, ok := err.(*networkError); ok {
329 // if transport reports a network error, then
330 // we're probably disconnected from the remote process?
331 pid := msg.UPID.String()
332 neterr := &mesos.InternalNetworkError{Pid: &pid}
333 sessionID, ok := sessionid.FromContext(ctx)
334 if ok {
335 neterr.Session = &sessionID
336 }
337 log.V(1).Infof("routing network error for pid %q session %q", pid, sessionID)
338 err2 := m.Route(ctx, &m.upid, neterr)
339 if err2 != nil {
340 log.Error(err2)
341 } else {
342 log.V(1).Infof("swallowing raw error because we're reporting a networkError: %v", err)
343 return nil
344 }
345 }
346 return err
347 }))
348 }
349 }
350 }
351
352 // Since HTTPTransporter.Recv() is already buffered, so we don't need a 'recvLoop' here.
353 func (m *MesosMessenger) decodeLoop() {
354 for {
355 select {
356 case <-m.stop:
357 return
358 default:
359 }
360 msg, err := m.tr.Recv()
361 if err != nil {
362 if err == discardOnStopError {
363 log.V(1).Info("exiting decodeLoop, transport shutting down")
364 return
365 } else {
366 panic(fmt.Sprintf("unexpected transport error: %v", err))
367 }
368 }
369
370 log.V(2).Infof("Receiving message %v from %v\n", msg.Name, msg.UPID)
371 protoMessage, handler, found := m.messageBinding(msg.Name)
372 if !found {
373 log.Warningf("no message binding for message %q", msg.Name)
374 continue
375 }
376
377 msg.ProtoMessage = protoMessage
378 if err := proto.Unmarshal(msg.Bytes, msg.ProtoMessage); err != nil {
379 log.Errorf("Failed to unmarshal message %v: %v\n", msg, err)
380 continue
381 }
382
383 handler(msg.UPID, msg.ProtoMessage)
384 }
385 }
386
387 func (m *MesosMessenger) messageBinding(name string) (proto.Message, MessageHandler, bool) {
388 m.guardHandlers.RLock()
389 defer m.guardHandlers.RUnlock()
390
391 gotype, ok := m.installedMessages[name]
392 if !ok {
393 return nil, nil, false
394 }
395
396 handler, ok := m.installedHandlers[name]
397 if !ok {
398 return nil, nil, false
399 }
400
401 protoMessage := reflect.New(gotype).Interface().(proto.Message)
402 return protoMessage, handler, true
403 }
404
405 // getMessageName returns the name of the message in the mesos manner.
406 func getMessageName(msg proto.Message) string {
407 var msgName string
408
409 switch msg := msg.(type) {
410 case *scheduler.Call:
411 msgName = "scheduler"
412 default:
413 msgName = fmt.Sprintf("%v.%v", "mesos.internal", reflect.TypeOf(msg).Elem().Name())
414 }
415
416 return msgName
417 }