Debian Codegraph @

poller/poller.go

raw
1 /*
2 Copyright 2014-2015 Canonical Ltd.
3
4 This program is free software: you can redistribute it and/or modify it
5 under the terms of the GNU General Public License version 3, as published
6 by the Free Software Foundation.
7
8 This program is distributed in the hope that it will be useful, but
9 WITHOUT ANY WARRANTY; without even the implied warranties of
10 MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11 PURPOSE. See the GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License along
14 with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17 // Package poller implements Poller, a thing that uses (hw) alarms to
18 // wake the device up from deep sleep periodically, check for
19 // notifications, and poke polld.
20 package poller
21
22 import (
23 "errors"
24 "sync"
25 "time"
26
27 "gitlab.com/ubports/development/core/lomiri-push-service/bus"
28 "gitlab.com/ubports/development/core/lomiri-push-service/bus/polld"
29 "gitlab.com/ubports/development/core/lomiri-push-service/bus/powerd"
30 "gitlab.com/ubports/development/core/lomiri-push-service/client/session"
31 "gitlab.com/ubports/development/core/lomiri-push-service/logger"
32 "gitlab.com/ubports/development/core/lomiri-push-service/util"
33 )
34
35 var (
36 ErrUnconfigured = errors.New("not configured")
37 ErrAlreadyStarted = errors.New("already started")
38 ErrNotStarted = errors.New("not started")
39 )
40
41 type stater interface {
42 State() session.ClientSessionState
43 }
44
45 type Times struct {
46 AlarmInterval time.Duration
47 SessionStateSettle time.Duration
48 NetworkWait time.Duration
49 PolldWait time.Duration
50 DoneWait time.Duration
51 BusyWait time.Duration
52 }
53
54 type Poller interface {
55 IsConnected() bool
56 Start() error
57 Run() error
58 HasConnectivity(bool)
59 }
60
61 type PollerSetup struct {
62 Times Times
63 Log logger.Logger
64 SessionStateGetter stater
65 }
66
67 type poller struct {
68 times Times
69 log logger.Logger
70 powerd powerd.Powerd
71 polld polld.Polld
72 cookie string
73 sessionState stater
74 connCh chan bool
75 requestWakeupCh chan struct{}
76 requestedWakeupErrCh chan error
77 holdsWakeLockCh chan bool
78 }
79
80 func New(setup *PollerSetup) Poller {
81 return &poller{
82 times: setup.Times,
83 log: setup.Log,
84 powerd: nil,
85 polld: nil,
86 sessionState: setup.SessionStateGetter,
87 connCh: make(chan bool),
88 requestWakeupCh: make(chan struct{}),
89 requestedWakeupErrCh: make(chan error),
90 holdsWakeLockCh: make(chan bool),
91 }
92 }
93
94 func (p *poller) IsConnected() bool {
95 return p.sessionState.State() == session.Running
96 }
97
98 func (p *poller) HasConnectivity(hasConn bool) {
99 p.connCh <- hasConn
100 }
101
102 func (p *poller) Start() error {
103 if p.log == nil {
104 return ErrUnconfigured
105 }
106 if p.powerd != nil || p.polld != nil {
107 return ErrAlreadyStarted
108 }
109
110 powerdEndp := bus.SystemBus.Endpoint(powerd.BusAddress, p.log)
111 polldEndp := bus.SessionBus.Endpoint(polld.BusAddress, p.log)
112
113 var wg sync.WaitGroup
114 wg.Add(2)
115 go func() {
116 n := util.NewAutoRedialer(powerdEndp).Redial()
117 p.log.Debugf("powerd dialed on try %d", n)
118 wg.Done()
119 }()
120 go func() {
121 n := util.NewAutoRedialer(polldEndp).Redial()
122 p.log.Debugf("polld dialed in on try %d", n)
123 wg.Done()
124 }()
125 wg.Wait()
126
127 p.powerd = powerd.New(powerdEndp, p.log)
128 p.polld = polld.New(polldEndp, p.log)
129
130 // busy sleep loop to workaround go's timer/sleep
131 // not accounting for time when the system is suspended
132 // see https://bugs.launchpad.net/ubuntu/+source/ubuntu-push/+bug/1435109
133 if p.times.BusyWait > 0 {
134 p.log.Debugf("starting busy loop with %s interval", p.times.BusyWait)
135 go func() {
136 for {
137 time.Sleep(p.times.BusyWait)
138 }
139 }()
140 } else {
141 p.log.Debugf("skipping busy loop")
142 }
143
144 return nil
145 }
146
147 func (p *poller) Run() error {
148 if p.log == nil {
149 return ErrUnconfigured
150 }
151 if p.powerd == nil || p.polld == nil {
152 return ErrNotStarted
153 }
154 wakeupCh, err := p.powerd.WatchWakeups()
155 if err != nil {
156 return err
157 }
158 doneCh, err := p.polld.WatchDones()
159 if err != nil {
160 return err
161 }
162 filteredWakeUpCh := make(chan bool)
163 go p.control(wakeupCh, filteredWakeUpCh)
164 go p.run(filteredWakeUpCh, doneCh)
165 return nil
166 }
167
168 func (p *poller) doRequestWakeup(delta time.Duration) (time.Time, string, error) {
169 t := time.Now().Add(delta).Truncate(time.Second)
170 cookie, err := p.powerd.RequestWakeup("lomiri push client", t)
171 if err == nil {
172 p.log.Debugf("requested wakeup at %s", t)
173 } else {
174 p.log.Errorf("RequestWakeup got %v", err)
175 t = time.Time{}
176 cookie = ""
177 }
178 return t, cookie, err
179 }
180
181 func (p *poller) control(wakeupCh <-chan bool, filteredWakeUpCh chan<- bool) {
182 // Assume a connection, and poll immediately.
183 connected := true
184 dontPoll := !connected
185 var t time.Time
186 cookie := ""
187 holdsWakeLock := false
188 for {
189 select {
190 case holdsWakeLock = <-p.holdsWakeLockCh:
191 case <-p.requestWakeupCh:
192 if !t.IsZero() || dontPoll {
193 // earlier wakeup or we shouldn't be polling
194 // => don't request wakeup
195 if dontPoll {
196 p.log.Debugf("skip requesting wakeup")
197 }
198 p.requestedWakeupErrCh <- nil
199 break
200 }
201 var err error
202 t, cookie, err = p.doRequestWakeup(p.times.AlarmInterval)
203 p.requestedWakeupErrCh <- err
204 case b := <-wakeupCh:
205 // seems we get here also on clear wakeup, oh well
206 if !b {
207 panic("WatchWakeups channel produced a false value (??)")
208 }
209 // the channel will produce a true for every
210 // wakeup, not only the one we asked for
211 now := time.Now()
212 if t.IsZero() {
213 p.log.Debugf("got woken up; time is %s", now)
214 } else {
215 p.log.Debugf("got woken up; time is %s (𝛥: %s)", now, now.Sub(t))
216 if !now.Before(t) {
217 t = time.Time{}
218 filteredWakeUpCh <- true
219 }
220 }
221 case state := <-p.connCh:
222 connected = state
223 p.log.Debugf("control: connected:%v", state)
224 }
225 newDontPoll := !connected
226 p.log.Debugf("control: prevDontPoll:%v dontPoll:%v wakeupReq:%v holdsWakeLock:%v", dontPoll, newDontPoll, !t.IsZero(), holdsWakeLock)
227 if newDontPoll != dontPoll {
228 if dontPoll = newDontPoll; dontPoll {
229 if !t.IsZero() {
230 err := p.powerd.ClearWakeup(cookie)
231 if err == nil {
232 // cleared
233 t = time.Time{}
234 p.log.Debugf("cleared wakeup")
235 } else {
236 p.log.Errorf("ClearWakeup got %v", err)
237 }
238 }
239 } else {
240 if t.IsZero() && !holdsWakeLock {
241 // reschedule soon
242 var err error
243 t, cookie, err = p.doRequestWakeup(p.times.NetworkWait / 20)
244 if err != nil {
245 // Make sure we break a potential deadlock by trying again.
246 filteredWakeUpCh <- true
247 }
248 }
249 }
250 }
251 }
252 }
253
254 func (p *poller) requestWakeup() error {
255 p.requestWakeupCh <- struct{}{}
256 return <-p.requestedWakeupErrCh
257 }
258
259 func (p *poller) holdsWakeLock(has bool) {
260 p.holdsWakeLockCh <- has
261 }
262
263 func (p *poller) run(wakeupCh <-chan bool, doneCh <-chan bool) {
264 var lockCookie string
265
266 for {
267 lockCookie = p.step(wakeupCh, doneCh, lockCookie)
268 }
269 }
270
271 func (p *poller) step(wakeupCh <-chan bool, doneCh <-chan bool, lockCookie string) string {
272
273 err := p.requestWakeup()
274 if err != nil {
275 // Don't do this too quickly. Pretend we are just skipping one wakeup
276 time.Sleep(p.times.AlarmInterval)
277 return lockCookie
278 }
279 p.holdsWakeLock(false)
280 if lockCookie != "" {
281 if err := p.powerd.ClearWakelock(lockCookie); err != nil {
282 p.log.Errorf("ClearWakelock(%#v) got %v", lockCookie, err)
283 }
284 lockCookie = ""
285 }
286 <-wakeupCh
287 lockCookie, err = p.powerd.RequestWakelock("lomiri push client")
288 if err != nil {
289 p.log.Errorf("RequestWakelock got %v", err)
290 return lockCookie
291 }
292 p.holdsWakeLock(true)
293 p.log.Debugf("got wakelock cookie of %s, checking conn state", lockCookie)
294 time.Sleep(p.times.SessionStateSettle)
295 for i := 0; i < 20; i++ {
296 if p.IsConnected() {
297 p.log.Debugf("iter %02d: connected", i)
298 break
299 }
300 p.log.Debugf("iter %02d: not connected, sleeping for %s", i, p.times.NetworkWait/20)
301 time.Sleep(p.times.NetworkWait / 20)
302 p.log.Debugf("iter %02d: slept", i)
303 }
304 if !p.IsConnected() {
305 p.log.Errorf("not connected after %s; giving up", p.times.NetworkWait)
306 } else {
307 p.log.Debugf("poking polld.")
308 // drain the doneCH
309 drain:
310 for {
311 select {
312 case <-doneCh:
313 default:
314 break drain
315 }
316 }
317
318 if err := p.polld.Poll(); err != nil {
319 p.log.Errorf("Poll got %v", err)
320 } else {
321 p.log.Debugf("waiting for polld to signal Done.")
322 select {
323 case b := <-doneCh:
324 if !b {
325 panic("WatchDones channel produced a false value (??)")
326 }
327 p.log.Debugf("polld Done.")
328 case <-time.After(p.times.PolldWait):
329 p.log.Errorf("polld still not done after %s; giving up", p.times.PolldWait)
330 }
331 }
332
333 // XXX check whether something was actually done before waiting
334 p.log.Debugf("sleeping for DoneWait %s", p.times.DoneWait)
335 time.Sleep(p.times.DoneWait)
336 p.log.Debugf("slept")
337 }
338
339 return lockCookie
340 }