File: standalone.go

package info (click to toggle)
golang-github-mesos-mesos-go 0.0.2+dfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, stretch
  • size: 3,964 kB
  • ctags: 6,435
  • sloc: makefile: 18
file content (244 lines) | stat: -rw-r--r-- 6,604 bytes parent folder | download | duplicates (2)
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
244
package detector

import (
	"encoding/binary"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"strconv"
	"sync"
	"time"

	log "github.com/golang/glog"
	mesos "github.com/mesos/mesos-go/mesosproto"
	"github.com/mesos/mesos-go/upid"
	"golang.org/x/net/context"
)

const (
	defaultMesosHttpClientTimeout  = 10 * time.Second //TODO(jdef) configurable via fiag?
	defaultMesosLeaderSyncInterval = 30 * time.Second //TODO(jdef) configurable via fiag?
	defaultMesosMasterPort         = 5050
)

// enables easier unit testing
type fetcherFunc func(ctx context.Context, address string) (*upid.UPID, error)

type Standalone struct {
	ch                 chan *mesos.MasterInfo
	client             *http.Client
	tr                 *http.Transport
	pollOnce           sync.Once
	initial            *mesos.MasterInfo
	done               chan struct{}
	cancelOnce         sync.Once
	leaderSyncInterval time.Duration
	httpClientTimeout  time.Duration
	assumedMasterPort  int
	poller             func(pf fetcherFunc)
	fetchPid           fetcherFunc
}

// Create a new stand alone master detector.
func NewStandalone(mi *mesos.MasterInfo) *Standalone {
	log.V(2).Infof("creating new standalone detector for %+v", mi)
	stand := &Standalone{
		ch:                 make(chan *mesos.MasterInfo),
		tr:                 &http.Transport{},
		initial:            mi,
		done:               make(chan struct{}),
		leaderSyncInterval: defaultMesosLeaderSyncInterval,
		httpClientTimeout:  defaultMesosHttpClientTimeout,
		assumedMasterPort:  defaultMesosMasterPort,
	}
	stand.poller = stand._poller
	stand.fetchPid = stand._fetchPid
	return stand
}

func (s *Standalone) String() string {
	return fmt.Sprintf("{initial: %+v}", s.initial)
}

// Detecting the new master.
func (s *Standalone) Detect(o MasterChanged) error {
	log.V(2).Info("Detect()")
	s.pollOnce.Do(func() {
		log.V(1).Info("spinning up asyc master detector poller")
		// delayed initialization allows unit tests to modify timeouts before detection starts
		s.client = &http.Client{
			Transport: s.tr,
			Timeout:   s.httpClientTimeout,
		}
		go s.poller(s.fetchPid)
	})
	if o != nil {
		log.V(1).Info("spawning asyc master detector listener")
		go func() {
			log.V(2).Infof("waiting for polled to send updates")
		pollWaiter:
			for {
				select {
				case mi, ok := <-s.ch:
					if !ok {
						break pollWaiter
					}
					log.V(1).Infof("detected master change: %+v", mi)
					o.OnMasterChanged(mi)
				case <-s.done:
					return
				}
			}
			o.OnMasterChanged(nil)
		}()
	} else {
		log.Warningf("detect called with a nil master change listener")
	}
	return nil
}

func (s *Standalone) Done() <-chan struct{} {
	return s.done
}

func (s *Standalone) Cancel() {
	s.cancelOnce.Do(func() { close(s.done) })
}

// poll for changes to master leadership via current leader's /state.json endpoint.
// we poll the `initial` leader, aborting if none was specified.
//
// TODO(jdef) follow the leader: change who we poll based on the prior leader
// TODO(jdef) somehow determine all masters in cluster from the state.json?
//
func (s *Standalone) _poller(pf fetcherFunc) {
	defer func() {
		defer s.Cancel()
		log.Warning("shutting down standalone master detection")
	}()
	if s.initial == nil {
		log.Errorf("aborting master poller since initial master info is nil")
		return
	}
	addr := s.initial.GetHostname()
	if len(addr) == 0 {
		if s.initial.GetIp() == 0 {
			log.Warningf("aborted mater poller since initial master info has no host")
			return
		}
		ip := make([]byte, 4)
		binary.BigEndian.PutUint32(ip, s.initial.GetIp())
		addr = net.IP(ip).To4().String()
	}
	port := uint32(s.assumedMasterPort)
	if s.initial.Port != nil && *s.initial.Port != 0 {
		port = *s.initial.Port
	}
	addr = net.JoinHostPort(addr, strconv.Itoa(int(port)))
	log.V(1).Infof("polling for master leadership at '%v'", addr)
	var lastpid *upid.UPID
	for {
		startedAt := time.Now()
		ctx, cancel := context.WithTimeout(context.Background(), s.leaderSyncInterval)
		if pid, err := pf(ctx, addr); err == nil {
			if !pid.Equal(lastpid) {
				log.V(2).Infof("detected leadership change from '%v' to '%v'", lastpid, pid)
				lastpid = pid
				elapsed := time.Now().Sub(startedAt)
				mi := CreateMasterInfo(pid)
				select {
				case s.ch <- mi: // noop
				case <-time.After(s.leaderSyncInterval - elapsed):
					// no one heard the master change, oh well - poll again
					goto continuePolling
				case <-s.done:
					cancel()
					return
				}
			} else {
				log.V(2).Infof("no change to master leadership: '%v'", lastpid)
			}
		} else if err == context.DeadlineExceeded {
			if lastpid != nil {
				lastpid = nil
				select {
				case s.ch <- nil: // lost master
				case <-s.done: // no need to cancel ctx
					return
				}
			}
			goto continuePolling
		} else {
			select {
			case <-s.done:
				cancel()
				return
			default:
				if err != context.Canceled {
					log.Error(err)
				}
			}
		}
		if remaining := s.leaderSyncInterval - time.Now().Sub(startedAt); remaining > 0 {
			log.V(3).Infof("master leader poller sleeping for %v", remaining)
			time.Sleep(remaining)
		}
	continuePolling:
		cancel()
	}
}

// assumes that address is in host:port format
func (s *Standalone) _fetchPid(ctx context.Context, address string) (*upid.UPID, error) {
	//TODO(jdef) need SSL support
	uri := fmt.Sprintf("http://%s/state.json", address)
	req, err := http.NewRequest("GET", uri, nil)
	if err != nil {
		return nil, err
	}
	var pid *upid.UPID
	err = s.httpDo(ctx, req, func(res *http.Response, err error) error {
		if err != nil {
			return err
		}
		defer res.Body.Close()
		if res.StatusCode != 200 {
			return fmt.Errorf("HTTP request failed with code %d: %v", res.StatusCode, res.Status)
		}
		blob, err1 := ioutil.ReadAll(res.Body)
		if err1 != nil {
			return err1
		}
		log.V(3).Infof("Got mesos state, content length %v", len(blob))
		type State struct {
			Leader string `json:"leader"` // ex: master(1)@10.22.211.18:5050
		}
		state := &State{}
		err = json.Unmarshal(blob, state)
		if err != nil {
			return err
		}
		pid, err = upid.Parse(state.Leader)
		return err
	})
	return pid, err
}

type responseHandler func(*http.Response, error) error

// hacked from https://blog.golang.org/context
func (s *Standalone) httpDo(ctx context.Context, req *http.Request, f responseHandler) error {
	// Run the HTTP request in a goroutine and pass the response to f.
	ch := make(chan error, 1)
	go func() { ch <- f(s.client.Do(req)) }()
	select {
	case <-ctx.Done():
		s.tr.CancelRequest(req)
		<-ch // Wait for f to return.
		return ctx.Err()
	case err := <-ch:
		return err
	}
}