| 1 |
/* |
| 2 |
Copyright 2013-2014 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 launch_helper |
| 18 |
|
| 19 |
import ( |
| 20 |
"encoding/json" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"io/ioutil" |
| 24 |
"os" |
| 25 |
"path" |
| 26 |
"sync" |
| 27 |
"time" |
| 28 |
|
| 29 |
"github.com/adrg/xdg" |
| 30 |
|
| 31 |
"gitlab.com/ubports/development/core/lomiri-push-service/click" |
| 32 |
"gitlab.com/ubports/development/core/lomiri-push-service/launch_helper/cual" |
| 33 |
"gitlab.com/ubports/development/core/lomiri-push-service/launch_helper/legacy" |
| 34 |
"gitlab.com/ubports/development/core/lomiri-push-service/logger" |
| 35 |
) |
| 36 |
|
| 37 |
var ( |
| 38 |
ErrCantFindHelper = errors.New("can't find helper") |
| 39 |
ErrCantFindLauncher = errors.New("can't find launcher for helper") |
| 40 |
) |
| 41 |
|
| 42 |
type HelperArgs struct { |
| 43 |
Input *HelperInput |
| 44 |
AppId string |
| 45 |
FileIn string |
| 46 |
FileOut string |
| 47 |
Timer *time.Timer |
| 48 |
ForcedStop bool |
| 49 |
} |
| 50 |
|
| 51 |
type HelperLauncher interface { |
| 52 |
HelperAppID(app *click.AppId) string |
| 53 |
InstallObserver(done func(string)) error |
| 54 |
RemoveObserver() error |
| 55 |
Launch(appId string, f1 string, f2 string) (string, error) |
| 56 |
Stop(appId string, instanceId string) error |
| 57 |
} |
| 58 |
|
| 59 |
type kindHelperPool struct { |
| 60 |
log logger.Logger |
| 61 |
chOut chan *HelperResult |
| 62 |
chIn chan *HelperInput |
| 63 |
chDone chan *click.AppId |
| 64 |
chStopped chan struct{} |
| 65 |
launchers map[string]HelperLauncher |
| 66 |
lock sync.Mutex |
| 67 |
hmap map[string]*HelperArgs |
| 68 |
maxRuntime time.Duration |
| 69 |
maxNum int |
| 70 |
// hook |
| 71 |
growBacklog func([]*HelperInput, *HelperInput) []*HelperInput |
| 72 |
} |
| 73 |
|
| 74 |
// DefaultLaunchers produces the default map for kind -> HelperLauncher |
| 75 |
func DefaultLaunchers(log logger.Logger) map[string]HelperLauncher { |
| 76 |
return map[string]HelperLauncher{ |
| 77 |
"click": cual.New(log), |
| 78 |
"legacy": legacy.New(log), |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
// a HelperPool that delegates to different per kind HelperLaunchers |
| 83 |
func NewHelperPool(launchers map[string]HelperLauncher, log logger.Logger) HelperPool { |
| 84 |
newPool := &kindHelperPool{ |
| 85 |
log: log, |
| 86 |
hmap: make(map[string]*HelperArgs), |
| 87 |
launchers: launchers, |
| 88 |
maxRuntime: 5 * time.Second, |
| 89 |
maxNum: 5, |
| 90 |
} |
| 91 |
newPool.growBacklog = newPool.doGrowBacklog |
| 92 |
return newPool |
| 93 |
} |
| 94 |
|
| 95 |
func (pool *kindHelperPool) Start() chan *HelperResult { |
| 96 |
pool.chOut = make(chan *HelperResult) |
| 97 |
pool.chIn = make(chan *HelperInput, InputBufferSize) |
| 98 |
pool.chDone = make(chan *click.AppId) |
| 99 |
pool.chStopped = make(chan struct{}) |
| 100 |
|
| 101 |
for kind, launcher := range pool.launchers { |
| 102 |
kind1 := kind |
| 103 |
err := launcher.InstallObserver(func(iid string) { |
| 104 |
pool.OneDone(kind1 + ":" + iid) |
| 105 |
}) |
| 106 |
if err != nil { |
| 107 |
panic(fmt.Errorf("failed to install helper observer for %s: %v", kind, err)) |
| 108 |
} |
| 109 |
} |
| 110 |
|
| 111 |
go pool.loop() |
| 112 |
|
| 113 |
return pool.chOut |
| 114 |
} |
| 115 |
|
| 116 |
func (pool *kindHelperPool) loop() { |
| 117 |
running := make(map[string]bool) |
| 118 |
var backlog []*HelperInput |
| 119 |
|
| 120 |
for { |
| 121 |
select { |
| 122 |
case in, ok := <-pool.chIn: |
| 123 |
if !ok { |
| 124 |
close(pool.chStopped) |
| 125 |
return |
| 126 |
} |
| 127 |
if len(running) >= pool.maxNum || running[in.App.Original()] { |
| 128 |
backlog = pool.growBacklog(backlog, in) |
| 129 |
} else { |
| 130 |
if pool.tryOne(in) { |
| 131 |
running[in.App.Original()] = true |
| 132 |
} |
| 133 |
} |
| 134 |
case app := <-pool.chDone: |
| 135 |
delete(running, app.Original()) |
| 136 |
if len(backlog) == 0 { |
| 137 |
continue |
| 138 |
} |
| 139 |
backlogSz := 0 |
| 140 |
done := false |
| 141 |
for i, in := range backlog { |
| 142 |
if in != nil { |
| 143 |
if !done && !running[in.App.Original()] { |
| 144 |
backlog[i] = nil |
| 145 |
if pool.tryOne(in) { |
| 146 |
running[in.App.Original()] = true |
| 147 |
done = true |
| 148 |
} |
| 149 |
} else { |
| 150 |
backlogSz++ |
| 151 |
} |
| 152 |
} |
| 153 |
} |
| 154 |
backlog = pool.shrinkBacklog(backlog, backlogSz) |
| 155 |
pool.log.Debugf("current helper input backlog has shrunk to %d entries.", backlogSz) |
| 156 |
} |
| 157 |
} |
| 158 |
} |
| 159 |
|
| 160 |
func (pool *kindHelperPool) doGrowBacklog(backlog []*HelperInput, in *HelperInput) []*HelperInput { |
| 161 |
backlog = append(backlog, in) |
| 162 |
pool.log.Debugf("current helper input backlog has grown to %d entries.", len(backlog)) |
| 163 |
return backlog |
| 164 |
} |
| 165 |
|
| 166 |
func (pool *kindHelperPool) shrinkBacklog(backlog []*HelperInput, backlogSz int) []*HelperInput { |
| 167 |
if backlogSz == 0 { |
| 168 |
return nil |
| 169 |
} |
| 170 |
if cap(backlog) < 2*backlogSz { |
| 171 |
return backlog |
| 172 |
} |
| 173 |
pool.log.Debugf("copying backlog to avoid wasting too much space (%d/%d used)", backlogSz, cap(backlog)) |
| 174 |
clean := make([]*HelperInput, 0, backlogSz) |
| 175 |
for _, bentry := range backlog { |
| 176 |
if bentry != nil { |
| 177 |
clean = append(clean, bentry) |
| 178 |
} |
| 179 |
} |
| 180 |
return clean |
| 181 |
} |
| 182 |
|
| 183 |
func (pool *kindHelperPool) Stop() { |
| 184 |
close(pool.chIn) |
| 185 |
for kind, launcher := range pool.launchers { |
| 186 |
err := launcher.RemoveObserver() |
| 187 |
if err != nil { |
| 188 |
panic(fmt.Errorf("failed to remove helper observer for %s: %v", kind, err)) |
| 189 |
} |
| 190 |
} |
| 191 |
// make Stop sync for tests |
| 192 |
<-pool.chStopped |
| 193 |
} |
| 194 |
|
| 195 |
func (pool *kindHelperPool) Run(kind string, input *HelperInput) { |
| 196 |
input.kind = kind |
| 197 |
pool.chIn <- input |
| 198 |
} |
| 199 |
|
| 200 |
func (pool *kindHelperPool) tryOne(input *HelperInput) bool { |
| 201 |
if pool.handleOne(input) != nil { |
| 202 |
pool.failOne(input) |
| 203 |
return false |
| 204 |
} |
| 205 |
return true |
| 206 |
} |
| 207 |
|
| 208 |
func (pool *kindHelperPool) failOne(input *HelperInput) { |
| 209 |
pool.log.Errorf("unable to get helper output; putting payload into message") |
| 210 |
pool.chOut <- &HelperResult{HelperOutput: HelperOutput{Message: input.Payload, Notification: nil}, Input: input} |
| 211 |
} |
| 212 |
|
| 213 |
func (pool *kindHelperPool) cleanupTempFiles(f1, f2 string) { |
| 214 |
if f1 != "" { |
| 215 |
os.Remove(f1) |
| 216 |
} |
| 217 |
if f2 != "" { |
| 218 |
os.Remove(f2) |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
func (pool *kindHelperPool) handleOne(input *HelperInput) error { |
| 223 |
launcher, ok := pool.launchers[input.kind] |
| 224 |
if !ok { |
| 225 |
pool.log.Errorf("unable to find launcher for kind: %v", input.kind) |
| 226 |
return ErrCantFindLauncher |
| 227 |
} |
| 228 |
helperAppId := launcher.HelperAppID(input.App) |
| 229 |
if helperAppId == "" { |
| 230 |
pool.log.Errorf("can't locate helper for app") |
| 231 |
return ErrCantFindHelper |
| 232 |
} |
| 233 |
pool.log.Debugf("using helper %s for app %s", helperAppId, input.App) |
| 234 |
var f1, f2 string |
| 235 |
f1, err := pool.createInputTempFile(input) |
| 236 |
defer func() { |
| 237 |
if err != nil { |
| 238 |
pool.cleanupTempFiles(f1, f2) |
| 239 |
} |
| 240 |
}() |
| 241 |
if err != nil { |
| 242 |
pool.log.Errorf("unable to create input tempfile: %v", err) |
| 243 |
return err |
| 244 |
} |
| 245 |
f2, err = pool.createOutputTempFile(input) |
| 246 |
if err != nil { |
| 247 |
pool.log.Errorf("unable to create output tempfile: %v", err) |
| 248 |
return err |
| 249 |
} |
| 250 |
|
| 251 |
args := HelperArgs{ |
| 252 |
AppId: helperAppId, |
| 253 |
Input: input, |
| 254 |
FileIn: f1, |
| 255 |
FileOut: f2, |
| 256 |
} |
| 257 |
|
| 258 |
pool.lock.Lock() |
| 259 |
defer pool.lock.Unlock() |
| 260 |
iid, err := launcher.Launch(helperAppId, f1, f2) |
| 261 |
if err != nil { |
| 262 |
pool.log.Errorf("unable to launch helper %s: %v", helperAppId, err) |
| 263 |
return err |
| 264 |
} |
| 265 |
uid := input.kind + ":" + iid // unique across launchers |
| 266 |
args.Timer = time.AfterFunc(pool.maxRuntime, func() { |
| 267 |
pool.peekId(uid, func(a *HelperArgs) { |
| 268 |
a.ForcedStop = true |
| 269 |
err := launcher.Stop(helperAppId, iid) |
| 270 |
if err != nil { |
| 271 |
pool.log.Errorf("unable to forcefully stop helper %s: %v", helperAppId, err) |
| 272 |
} |
| 273 |
}) |
| 274 |
}) |
| 275 |
pool.hmap[uid] = &args |
| 276 |
|
| 277 |
return nil |
| 278 |
} |
| 279 |
|
| 280 |
func (pool *kindHelperPool) peekId(uid string, cb func(*HelperArgs)) *HelperArgs { |
| 281 |
pool.lock.Lock() |
| 282 |
defer pool.lock.Unlock() |
| 283 |
args, ok := pool.hmap[uid] |
| 284 |
if ok { |
| 285 |
cb(args) |
| 286 |
return args |
| 287 |
} |
| 288 |
return nil |
| 289 |
} |
| 290 |
|
| 291 |
func (pool *kindHelperPool) OneDone(uid string) { |
| 292 |
args := pool.peekId(uid, func(a *HelperArgs) { |
| 293 |
a.Timer.Stop() |
| 294 |
// dealt with, remove it |
| 295 |
delete(pool.hmap, uid) |
| 296 |
}) |
| 297 |
if args == nil { |
| 298 |
// nothing to do |
| 299 |
return |
| 300 |
} |
| 301 |
// mark it done only once we have sent the output so to order things |
| 302 |
defer func() { |
| 303 |
pool.chDone <- args.Input.App |
| 304 |
}() |
| 305 |
defer func() { |
| 306 |
pool.cleanupTempFiles(args.FileIn, args.FileOut) |
| 307 |
}() |
| 308 |
if args.ForcedStop { |
| 309 |
pool.failOne(args.Input) |
| 310 |
return |
| 311 |
} |
| 312 |
payload, err := ioutil.ReadFile(args.FileOut) |
| 313 |
if err != nil { |
| 314 |
pool.log.Errorf("unable to read output from %v helper: %v", args.AppId, err) |
| 315 |
} else { |
| 316 |
pool.log.Debugf("%v helper output: %s", args.AppId, payload) |
| 317 |
res := &HelperResult{Input: args.Input} |
| 318 |
err = json.Unmarshal(payload, &res.HelperOutput) |
| 319 |
if err != nil { |
| 320 |
pool.log.Errorf("failed to parse HelperOutput from %v helper output: %v", args.AppId, err) |
| 321 |
} else { |
| 322 |
pool.chOut <- res |
| 323 |
} |
| 324 |
} |
| 325 |
if err != nil { |
| 326 |
pool.failOne(args.Input) |
| 327 |
} |
| 328 |
} |
| 329 |
|
| 330 |
func (pool *kindHelperPool) createInputTempFile(input *HelperInput) (string, error) { |
| 331 |
f1, err := getTempFilename(input.App.Package) |
| 332 |
if err != nil { |
| 333 |
return "", err |
| 334 |
} |
| 335 |
return f1, ioutil.WriteFile(f1, input.Payload, os.ModeTemporary) |
| 336 |
} |
| 337 |
|
| 338 |
func (pool *kindHelperPool) createOutputTempFile(input *HelperInput) (string, error) { |
| 339 |
return getTempFilename(input.App.Package) |
| 340 |
} |
| 341 |
|
| 342 |
// helper helpers: |
| 343 |
|
| 344 |
var xdgCacheHome = func() string { |
| 345 |
return xdg.CacheHome |
| 346 |
} |
| 347 |
|
| 348 |
func _getTempDir(pkgName string) (string, error) { |
| 349 |
tmpDir := path.Join(xdgCacheHome(), pkgName) |
| 350 |
err := os.MkdirAll(tmpDir, 0700) |
| 351 |
return tmpDir, err |
| 352 |
} |
| 353 |
|
| 354 |
// override GetTempDir for testing without writing to ~/.cache/<pkgName> |
| 355 |
var GetTempDir func(pkgName string) (string, error) = _getTempDir |
| 356 |
|
| 357 |
func _getTempFilename(pkgName string) (string, error) { |
| 358 |
tmpDir, err := GetTempDir(pkgName) |
| 359 |
if err != nil { |
| 360 |
return "", err |
| 361 |
} |
| 362 |
file, err := ioutil.TempFile(tmpDir, "push-helper") |
| 363 |
if err != nil { |
| 364 |
return "", err |
| 365 |
} |
| 366 |
defer file.Close() |
| 367 |
return file.Name(), nil |
| 368 |
} |
| 369 |
|
| 370 |
var getTempFilename = _getTempFilename |