vpac / src / mirrors.v
625 lines · 579 sloc · 19.97 KB · 2174b556a01596a2fb43f9b2308a53ae30e1290b
Raw
1@[has_globals]
2module main
3
4import blip.vlib.blip.printer
5import json2
6import net.http
7import os
8import time
9
10// mirror ranking, after rate-mirrors (westandskif/rate-mirrors): gather the
11// candidates, drop the unusable ones, time one byte for latency, then time a
12// repo database for speed, and rank by speed. the oses the ranker knows are
13// in rank_oses; the protocols to rank come from the config
14
15// the rank form's filters and sizes, (rank :completion :max-delay :candidates
16// :retest :top): how complete and how fresh a mirror must be to be probed,
17// how many of the lowest latencies get the speed test, how many of the
18// fastest are timed again, and how many are answered when -n names none
19__global rank_min_completion = 1.0
20__global rank_max_delay = i64(86400)
21
22// rank_parallelism is how many mirrors to probe at once: the rank form's
23// :parallel when it sets one, else the network's :parallel
24fn rank_parallelism() int {
25 return if rank_parallel > 0 { rank_parallel } else { parallel_downloads }
26}
27
28__global rank_speed_candidates = 40
29__global rank_retest = 5
30__global rank_top = 10
31
32// RankOs is one os the ranker knows. the mirror data comes from the status
33// api when the os publishes one, else from a plain Server = mirrorlist, which
34// carries no completion or delay to filter by. repo is the repo whose db the
35// speed test pulls, named again in the written urls
36struct RankOs {
37 status_json string
38 mirrorlist string
39 repo string
40}
41
42// default_rank_oses are the oses the ranker knows before the config speaks
43fn default_rank_oses() map[string]RankOs {
44 return {
45 'artix': RankOs{
46 status_json: 'https://status.artixlinux.org/mirrors/status/json/'
47 repo: 'system'
48 }
49 'arch': RankOs{
50 status_json: 'https://archlinux.org/mirrors/status/json/'
51 repo: 'core'
52 }
53 'cachyos': RankOs{
54 mirrorlist: 'https://raw.githubusercontent.com/CachyOS/CachyOS-PKGBUILDS/master/cachyos-mirrorlist/cachyos-mirrorlist'
55 repo: 'cachyos'
56 }
57 }
58}
59
60// rank_oses are the oses the ranker knows: the defaults, and every one the
61// config's (mirrorlist ...) form defines or redefines. rank_dir is where a
62// ranking is written for the config to require, (rank :dir)
63__global rank_oses = default_rank_oses()
64__global rank_dir = '/etc/vpac.d/mirrors'
65
66// rank_os_names spells the known oses for a message, sorted: the text is
67// the same whatever order the config's forms came in
68fn rank_os_names() string {
69 mut names := rank_oses.keys()
70 names.sort()
71 return names.join(', ')
72}
73
74// rank_os_name picks the os to rank: the one named on the command line, or
75// the running system's, read from /etc/os-release
76fn rank_os_name(query []string) !string {
77 if query.len > 1 {
78 return error('rank takes one os: ${rank_os_names()}')
79 }
80 if query.len == 1 {
81 if query[0] !in rank_oses.keys() {
82 return error('the ranker knows ${rank_os_names()}, not "${query[0]}": define it with (mirrorlist :name ...) in the config')
83 }
84 return query[0]
85 }
86 text := os.read_file('/etc/os-release') or {
87 return error('could not read /etc/os-release to detect the os: pass one of ${rank_os_names()}')
88 }
89 mut id := ''
90 mut like := ''
91 for line in text.split_into_lines() {
92 if line.starts_with('ID=') {
93 id = line[3..].trim_space().trim('"\'')
94 } else if line.starts_with('ID_LIKE=') {
95 like = line[8..].trim_space().trim('"\'')
96 }
97 }
98 for candidate in [id, ...like.split(' ')] {
99 if candidate in rank_oses.keys() {
100 return candidate
101 }
102 }
103 return error('this system (${id}) is not one the ranker knows: pass one of ${rank_os_names()}, or define it with (mirrorlist :name ...) in the config')
104}
105
106// rank_write_target is where a ranked os is written for the config to require
107fn rank_write_target(os_name string) string {
108 return os.join_path(rank_dir, '${os_name}.lip')
109}
110
111struct StatusMirror {
112 url string
113 protocol string
114 last_sync string
115 completion_pct ?f64
116 delay ?i64
117 active bool
118 country_code string
119}
120
121struct StatusList {
122 urls []StatusMirror
123}
124
125// Mirror is a candidate: its full url template, with the repo and arch
126// placeholders left in place the way the config's mirror files hold them, and
127// when it last synced
128struct Mirror {
129 url string
130 last_sync string
131}
132
133// probe_url is the concrete url of one mirror's repo db: the template with
134// the repo and arch substituted in, plus the db file. a path override takes
135// the mirror root instead, which is where a custom file hangs from
136fn probe_url(m Mirror, spec RankOs, override string) string {
137 if override != '' {
138 return m.url.all_before('$') + override
139 }
140 return m.url.replace('$repo', spec.repo).replace('$arch', arch) + '/${spec.repo}.db'
141}
142
143fn with_slash(url string) string {
144 return if url.ends_with('/') { url } else { url + '/' }
145}
146
147// timed_fetch fetches one url with the rank timeout on both directions, and
148// hands back the body: it is what the ranker asks of the network, from the
149// mirror status on to the mirrorlists, since a stalled dns or a captive
150// portal would otherwise visit its hang on the ranking
151fn timed_fetch(url string, what string) !string {
152 return http_text(url, rank_timeout, what, url)
153}
154
155// http_text is one GET bounded by a timeout, in seconds, on both
156// directions, answering the body of an answer that succeeded. what names
157// the fetch and from the server in the error, so a refusal is told from a
158// stall. the ranker's fetches and the pkgbuild rpc both go through it
159fn http_text(url string, seconds int, what string, from string) !string {
160 mut req := http.Request{
161 url: url
162 read_timeout: seconds * time.second
163 write_timeout: seconds * time.second
164 }
165 resp := req.do() or { return error('${what} failed: ${err}') }
166 if resp.status_code < 200 || resp.status_code >= 300 {
167 return error('${what} failed: http ${resp.status_code} from ${from}')
168 }
169 return resp.body
170}
171
172// fetch_status_mirrors reads an os's mirror status and keeps the mirrors that
173// are usable: active, on a configured protocol, fully synced, recently synced,
174// with a known country
175fn fetch_status_mirrors(os_name string, spec RankOs) ![]Mirror {
176 body := timed_fetch(spec.status_json, 'fetching the ${os_name} mirror status')!
177 status := json2.decode[StatusList](body) or {
178 return error('could not read the ${os_name} mirror status: ${err.msg()}')
179 }
180 mut out := []Mirror{}
181 for m in status.urls {
182 completion := m.completion_pct or { continue }
183 delay := m.delay or { continue }
184 if m.active && m.protocol in cfg_protocols && completion >= rank_min_completion
185 && delay <= rank_max_delay && m.country_code != '' {
186 // the status api gives the mirror root; the repo layout of the os
187 // completes it to the template the config's mirror files hold
188 out << Mirror{
189 url: with_slash(m.url) + '$repo/os/$arch'
190 last_sync: m.last_sync
191 }
192 }
193 }
194 return out
195}
196
197// fetch_mirrorlist reads a plain Server = list, for the oses that publish no
198// status api: fetched, or read from the disk when the config names a path
199fn fetch_mirrorlist(spec RankOs) ![]Mirror {
200 if spec.mirrorlist.starts_with('/') {
201 text := os.read_file(spec.mirrorlist) or {
202 return error('could not read the mirrorlist ${spec.mirrorlist}: ${err.msg()}')
203 }
204 return parse_mirrors(text)
205 }
206 body := timed_fetch(spec.mirrorlist, 'fetching the mirrorlist')!
207 return parse_mirrors(body)
208}
209
210// parse_mirrors reads 'Server = url' lines or bare urls, one per line, as the
211// mirrorlists write them. the line already carries the os's repo layout, so
212// it is kept whole
213fn parse_mirrors(text string) []Mirror {
214 mut out := []Mirror{}
215 mut seen := map[string]bool{}
216 for line in text.split_into_lines() {
217 mut s := line.trim_space()
218 if s.starts_with('Server = ') {
219 s = s.all_after('Server = ').trim_space()
220 }
221 if s.starts_with('#') || !(s.starts_with('https://') || s.starts_with('http://')) {
222 continue
223 }
224 if seen[s] {
225 continue
226 }
227 seen[s] = true
228 out << Mirror{
229 url: s
230 }
231 }
232 return out
233}
234
235// stdin_text reads stdin to its end, the lines joined again. a read error is
236// an error here, not an end: a mirror list cut short must not rank as the
237// whole of it
238fn stdin_text() !string {
239 mut lines := []string{}
240 for {
241 lines << stdin_line() or {
242 if err is StdinEnd {
243 break
244 }
245 return err
246 }
247 }
248 return lines.join('\n')
249}
250
251// FetchOutcome is what a fetch hands back over its job's reply channel: the
252// measurement of an answer that came whole, the failure text of one that did
253// not
254struct FetchOutcome {
255 ms i64
256 size int
257 err string
258}
259
260// FetchJob is one fetch for a fetcher thread: the request to make and the
261// channel to answer on. the job crosses to the fetcher as a value: the
262// arguments of a spawned call and heap objects handed across threads have
263// been seen carrying another probe's values, so a fetch travels by copy and
264// the fetcher spawns with no arguments at all
265struct FetchJob {
266 url string
267 range bool
268 limit i64
269 deadline time.Time
270 reply chan FetchOutcome
271}
272
273// fetch_jobs is the queue the fetcher threads serve
274__global fetch_jobs = chan FetchJob{cap: 256}
275
276// timed_get fetches a url and returns the milliseconds it took and the size
277// of the answer. range asks for the first byte only, which measures latency.
278// the timeout comes from the config, and it bounds the probe twice over: each
279// read and write on its own, and the answer as a whole. the socket timeouts
280// alone start over with every read, so a mirror that trickles its db a few
281// bytes at a time would hold a speed probe for as long as it cared to. the
282// request therefore runs on a fetcher thread and the wait on its answer is
283// bounded by the deadline directly — a bound that holds even when no chunk
284// arrives to fire on_progress, as from a mirror that falls silent. the
285// callback stays as the fetcher's own early exit: the first chunk past the
286// deadline unwinds it, so a stalled fetch does not linger past its read_timeout
287fn timed_get(url string, range bool) !(i64, int) {
288 limit := rank_timeout
289 job := FetchJob{
290 url: url
291 range: range
292 limit: limit
293 deadline: time.now().add(limit * time.second)
294 reply: chan FetchOutcome{cap: 1}
295 }
296 fetch_jobs <- job
297 spawn fetch_worker()
298 mut res := FetchOutcome{}
299 mut timed := false
300 select {
301 res = <-job.reply {
302 }
303 // the timeout branch counts nanoseconds, the unit of time.Duration
304 job.deadline - time.now() {
305 timed = true
306 }
307 }
308 if timed {
309 return error('no whole answer within ${limit}s')
310 }
311 if res.err != '' {
312 return error(res.err)
313 }
314 return res.ms, res.size
315}
316
317// fetch_worker serves one queued fetch and dies. it takes no arguments on
318// purpose — the job comes off the queue — and one fetcher per fetch keeps the
319// pairing exact: every queued job has a thread waiting to pop it, whichever
320// thread answers which
321fn fetch_worker() {
322 job := <-fetch_jobs or { return }
323 mut req := http.Request{
324 url: job.url
325 read_timeout: job.limit * time.second
326 write_timeout: job.limit * time.second
327 on_progress: fn [job] (_ &http.Request, _ []u8, _ u64) ! {
328 if time.now() > job.deadline {
329 return error('no whole answer within ${job.limit}s')
330 }
331 }
332 }
333 if job.range {
334 req.header.add_custom('Range', 'bytes=0-0') or {
335 job.reply <- FetchOutcome{ err: err.msg() }
336 return
337 }
338 }
339 start := time.now()
340 resp := req.do() or {
341 job.reply <- FetchOutcome{ err: err.msg() }
342 return
343 }
344 // an answer that needs no body — a 404, a 403 — is a mirror that does
345 // not serve the repo db: a probe without body size is ranked on air
346 // unless the status is turned into the probe's failure
347 if resp.status_code < 200 || resp.status_code >= 300 {
348 job.reply <- FetchOutcome{ err: 'http ${resp.status_code} from ${job.url}' }
349 return
350 }
351 job.reply <- FetchOutcome{
352 ms: (time.now() - start).milliseconds()
353 size: resp.body.len
354 }
355}
356
357fn probe_latency(m Mirror, spec RankOs, override string) Probe {
358 ms, _ := timed_get(probe_url(m, spec, override), true) or {
359 return Probe{
360 url: m.url
361 }
362 }
363 return timed_probe(m.url, ms, 0, false)
364}
365
366fn probe_speed(m Mirror, spec RankOs, override string) Probe {
367 ms, bytes := timed_get(probe_url(m, spec, override), false) or {
368 return Probe{
369 url: m.url
370 }
371 }
372 return timed_probe(m.url, ms, bytes, true)
373}
374
375// timed_probe is a probe's result out of what the timed request measured:
376// the latency always, and with speed the bytes a second of a whole fetch —
377// one that brought no bytes failed, and one quicker than the clock's
378// millisecond counts as one, never a division by zero
379fn timed_probe(url string, ms i64, bytes int, speed bool) Probe {
380 if !speed {
381 return Probe{
382 url: url
383 latency_ms: ms
384 ok: true
385 }
386 }
387 if bytes <= 0 {
388 return Probe{
389 url: url
390 }
391 }
392 elapsed := if ms <= 0 { 1 } else { ms }
393 return Probe{
394 url: url
395 latency_ms: ms
396 speed: f64(bytes) / (f64(elapsed) / 1000.0)
397 ok: true
398 }
399}
400
401// Probe is the result of testing one mirror
402struct Probe {
403 url string
404 latency_ms i64
405 speed f64
406 ok bool
407}
408
409// ProbeFn measures one mirror, the os and the path override closed over. it
410// answers a Probe on every path — a failure is a Probe that is not ok — and
411// that is what lets probe_batch count on one answer per mirror
412type ProbeFn = fn (Mirror) Probe
413
414// probe_batch tests every mirror, rank_parallelism() at a time, and advances
415// the bar by each finished probe. quiet draws no bar, so the output can be
416// piped. the answers come back in the order they finish, not the input's
417fn probe_batch(mut ui TransUI, label string, mirrors []Mirror, probe ProbeFn, quiet bool) []Probe {
418 mut out := []Probe{cap: mirrors.len}
419 if mirrors.len == 0 {
420 return out
421 }
422 mut bar := unsafe { &Meter(nil) }
423 if !quiet {
424 bar = ui.meter(i64(mirrors.len), label)
425 bar.start()
426 }
427 // a parallelism that slipped past the config's floor would start no
428 // worker at all: one at a time is the least
429 conc := if rank_parallelism() < 1 { 1 } else { rank_parallelism() }
430 workers := if conc < mirrors.len { conc } else { mirrors.len }
431 // the whole batch is queued, then the queue closed: a worker that finds
432 // it drained is done. a pool rather than slots of conc means a slow probe
433 // holds back only its own worker, not the next slot's fast ones
434 jobs := chan Mirror{cap: mirrors.len}
435 for m in mirrors {
436 jobs <- m
437 }
438 jobs.close()
439 // the answers channel holds a whole batch, so a worker never waits on the
440 // collector to hand its answer over
441 answers := chan Probe{cap: mirrors.len}
442 for _ in 0 .. workers {
443 spawn probe_worker(jobs, answers, probe)
444 }
445 // one answer per mirror, each sent by the worker that took it: the probe
446 // answers on every path, and a panic in any thread ends the process
447 // rather than stranding this loop. a probe that hangs is bounded by the
448 // network's own timeouts (rank_timeout on read and write, the net
449 // module's on connect) and by timed_get's deadline on the whole answer
450 for _ in 0 .. mirrors.len {
451 out << <-answers
452 if !quiet {
453 bar.add(i64(1))
454 }
455 }
456 return out
457}
458
459// probe_worker measures mirrors until the queue runs dry. the probe runs on
460// this thread: the arguments of a spawned call are evaluated by the caller,
461// so spawning the send of a probe's result runs every probe on the collector,
462// one after another
463fn probe_worker(jobs chan Mirror, answers chan Probe, probe ProbeFn) {
464 for {
465 m := <-jobs or { return }
466 answers <- probe(m)
467 }
468}
469
470fn speed_mib(bytes_per_sec f64) string {
471 return '${bytes_per_sec / 1048576.0:.2f} MiB/s'
472}
473
474fn sync_age(last_sync string) string {
475 if last_sync == '' {
476 return '-'
477 }
478 synced := time.parse_rfc3339(last_sync) or { return '-' }
479 hours := (time.now().unix() - synced.unix()) / 3600
480 return '${hours}h ago'
481}
482
483// mirrors_lip is the blip file of the ranked urls: mirrors/<os>.lip defines
484// mirrors-<os>, the way repos.lip expects. each url is a string literal
485// escaped by blip's own printer: the urls come from the network and the file
486// is config that vpac runs as root, so a quote in a url must stay inside its
487// string
488fn mirrors_lip(os_name string, urls []string, date string) string {
489 var := 'mirrors-${os_name}'
490 mut content := '; mirrors for ${os_name}, ranked by vpac k -w on ${date}\n'
491 content += '(unless (defined? ${var}) (define ${var} []))\n'
492 content += '(array-append! ${var} [${urls.map(printer.quote_string(it)).join(' ')}])\n'
493 return content
494}
495
496// write_config_mirrors writes the ranked urls as the blip file the config
497// requires
498fn write_config_mirrors(os_name string, urls []string) !string {
499 target := rank_write_target(os_name)
500 os.mkdir_all(os.dir(target))!
501 os.write_file(target, mirrors_lip(os_name, urls, time.now().custom_format('YYYY-MM-DD')))!
502 return target
503}
504
505// Ranked is one mirror of a ranking: its probe, and when it last synced as
506// the mirror status says ('' when it is not known)
507struct Ranked {
508 Probe
509 last_sync string
510}
511
512// rank_mirrors measures the mirrors of an os and returns the best of them,
513// at most config.top, fastest first. the probes draw on the ui unless the
514// result goes to a file or a mirrorlist
515fn rank_mirrors(mut ui TransUI, os_name string, config ConfigRank) ![]Ranked {
516 spec := rank_oses[os_name]
517 mirrors := if config.stdin {
518 parse_mirrors(stdin_text()!)
519 } else if spec.status_json != '' {
520 fetch_status_mirrors(os_name, spec)!
521 } else {
522 fetch_mirrorlist(spec)!
523 }
524 if mirrors.len == 0 {
525 return error('no usable mirrors to rank')
526 }
527 mut sync_of := map[string]string{}
528 for m in mirrors {
529 sync_of[m.url] = m.last_sync
530 }
531
532 quiet := config.mirrorlist || config.output != ''
533 override := config.path
534 mut latency := probe_batch(mut ui, 'latency', mirrors, fn [spec, override] (m Mirror) Probe {
535 return probe_latency(m, spec, override)
536 }, quiet).filter(it.ok)
537 latency.sort(a.latency_ms < b.latency_ms)
538 if latency.len > rank_speed_candidates {
539 latency = latency[..rank_speed_candidates].clone()
540 }
541 candidates := latency.map(Mirror{
542 url: it.url
543 last_sync: sync_of[it.url] or { '' }
544 })
545
546 mut results := probe_batch(mut ui, 'speed', candidates, fn [spec, override] (m Mirror) Probe {
547 return probe_speed(m, spec, override)
548 }, quiet).filter(it.ok)
549 results.sort(a.speed > b.speed)
550
551 // the best few are measured again, one at a time, and averaged, so one
552 // lucky or unlucky transfer does not decide the order
553 for i in 0 .. if results.len < rank_retest { results.len } else { rank_retest } {
554 again := probe_speed(Mirror{ url: results[i].url }, spec, config.path)
555 if again.ok {
556 results[i] = Probe{
557 url: results[i].url
558 latency_ms: results[i].latency_ms
559 speed: (results[i].speed + again.speed) / 2.0
560 ok: true
561 }
562 }
563 }
564 results.sort(a.speed > b.speed)
565 ui.stop()
566
567 if results.len == 0 {
568 return error('no mirror answered the speed test')
569 }
570 top := if results.len < config.top { results.len } else { config.top }
571 return results[..top].map(Ranked{
572 Probe: it
573 last_sync: sync_of[it.url] or { '' }
574 })
575}
576
577// rank ranks the mirrors, then writes them where config says, or prints them
578fn rank(config ConfigRank) ! {
579 os_name := rank_os_name(config.query)!
580 mut ui := new_trans_ui()
581 defer {
582 ui.stop()
583 }
584 ranked := rank_mirrors(mut ui, os_name, config)!
585
586 urls := ranked.map(it.url)
587 if config.write {
588 target := write_config_mirrors(os_name, urls)!
589 report('wrote ${urls.len} mirrors to ${target}')
590 }
591 // a frontend gets the ranking itself, and formats it as it needs: the
592 // mirrorlist and output forms shape the printable text, which under
593 // --ui ipc lands in the log anyway, so the event goes out before
594 // whatever those flags do with the result
595 if ipc_on() {
596 emit(MirrorsEvent{
597 mirrors: ranked.map(MirrorEvent{
598 url: it.url
599 latency_ms: it.latency_ms
600 speed: it.speed
601 last_sync: it.last_sync
602 })
603 })
604 }
605 if config.output != '' {
606 os.write_file(config.output, urls.map('Server = ${it}').join('\n') + '\n')!
607 report('wrote ${urls.len} mirrors to ${config.output}')
608 return
609 }
610 if config.mirrorlist {
611 println(urls.map('Server = ${it}').join('\n'))
612 return
613 }
614 if ipc_on() {
615 return
616 }
617 // sync paints the finished spinner frames before the ranking prints
618 ui.sync()
619 mut rows := []Row{}
620 for i, m in ranked {
621 rows << row('${i + 1}', m.url.all_before('$'), '${m.latency_ms} ms', speed_mib(m.speed),
622 sync_age(m.last_sync))
623 }
624 println(table_text(rows, '', ' '))
625}
626