vpac / src / ipc.v
661 lines · 602 sloc · 20.66 KB · 841315c100c81d9e6b14c4b55a25d4e3d12db762
Raw
1@[has_globals]
2module main
3
4import os
5import sync
6import json2
7
8#include <unistd.h>
9
10// --ui ipc is vpac spoken to by a program instead of a person: a GUI, a web
11// UI or a test runs a mode as a child and reads json lines, one event per
12// line, from its stdout, answering the questions on its stdin. a root child
13// re-executed through the root provider keeps the same pipes, so it speaks
14// on them too.
15// every event is an object whose "type" says what it is; protocol is bumped
16// when an event changes in a way a reader must know about: a new event
17// type, a new question kind, a field whose meaning or presence changes, or
18// a new field a reader has to read to get the answer right. a field that
19// is only ever left out when empty and adds detail a reader may ignore
20// rides along without a bump, and is described at its struct. 2: clean's
21// build_root is absent when no invoker is known, and owner sends one event
22// per owner of a directory. 3: the select question (a group's members,
23// answered with a list of indices), clean's unused sync dbs, and the
24// changelog event. 4: a provides event of an expression or a bare file name
25// carries files, the paths matched in each entry's package. 5: clean's
26// build_size_partial, which makes build_size a floor
27const ipc_protocol = 5
28
29// ui_kind is --ui: 'tty' draws for a terminal, 'ipc' speaks the protocol
30__global ui_kind = 'tty'
31
32// ipc_fd is the channel the events go out on, the stdout vpac was given.
33// fd 1 itself is pointed at stderr once the channel is open, so a plain
34// print of a mode not yet speaking the protocol lands in the log and never
35// in the channel
36__global ipc_fd = 1
37__global ipc_started = false
38__global ipc_mu = sync.new_mutex()
39
40fn C.dup2(oldfd int, newfd int) int
41
42fn C.fcntl(fd int, cmd int, arg int) int
43
44fn ipc_on() bool {
45 return ui_kind == 'ipc'
46}
47
48// ipc_start opens the channel. it runs in the process that does the work,
49// after the escalation: a re-executed child must find the original fds, and
50// opens its own channel. the channel is close-on-exec, so the builds and
51// hooks vpac runs never hold the frontend's pipe open
52fn ipc_start() {
53 if ipc_started {
54 return
55 }
56 ipc_started = true
57 fd := C.dup(1)
58 if fd < 0 {
59 // a frontend would read plain text as the protocol: better no run
60 eprintln(error_text('--ui ipc: could not open the channel on stdout'))
61 exit(1)
62 }
63 if C.fcntl(fd, C.F_SETFD, C.FD_CLOEXEC) < 0 {
64 // without it, every build and every hook keeps the frontend's pipe
65 // open: said, since the channel is still good for this run
66 eprintln('--ui ipc: could not mark the channel close-on-exec')
67 }
68 // dup2 answers its new fd (1) on success, so only a negative one is a
69 // failure: fd 1 otherwise still carries the channel, and a plain print
70 // of a mode that does not speak the protocol would land there
71 if C.dup2(2, 1) < 0 {
72 eprintln(error_text('--ui ipc: could not lead the logs onto stderr'))
73 exit(1)
74 }
75 ipc_fd = fd
76 // the texts of the events are plain
77 color_flag = 'never'
78 emit(HelloEvent{
79 protocol: ipc_protocol
80 root: os.geteuid() == 0
81 })
82}
83
84// emit writes one event as one line. the lock keeps the lines of the
85// download callbacks and the main thread whole
86fn emit[T](event T) {
87 line := json2.encode(event) + '\n'
88 ipc_mu.lock()
89 ok := channel_write(line)
90 ipc_mu.unlock()
91 if !ok {
92 // the reader of the channel is gone, so the run is over; stderr
93 // still reaches a log, where a person may learn why
94 eprintln('${error_text('the frontend closed the channel')} -- last event: ${line.trim_space()}')
95 exit(1)
96 }
97}
98
99// channel_write writes the whole line on the channel, and answers whether it
100// went out, through write(2)
101fn channel_write(line string) bool {
102 return channel_write_to(ipc_fd, line, ipc_write)
103}
104
105// WriteFn is write(2) as channel_write_to calls it: what it wrote, and the
106// errno's code when that is -1. the system's in a run; a test's own to script the
107// interruptions and the stalls no real channel produces on demand
108type WriteFn = fn (fd int, buf voidptr, n int) (int, int)
109
110fn ipc_write(fd int, buf voidptr, n int) (int, int) {
111 written := int(C.write(fd, buf, n))
112 return written, if written < 0 { C.errno } else { 0 }
113}
114
115// channel_write_to writes the whole line on fd. os.fd_write gives up without
116// a word when the reader is gone, and a half-written json line is garbage to
117// a frontend: every byte is seen out, any failure is reported. a write that
118// is interrupted is taken again, and a write that answers nothing has made
119// no progress, so it is a failure too — waiting it out would be an endless
120// loop for a channel nobody reads
121fn channel_write_to(fd int, line string, write WriteFn) bool {
122 str := line.clone()
123 mut p := unsafe { voidptr(uint(str.str)) }
124 mut left := str.len
125 for left > 0 {
126 written, code := write(fd, p, left)
127 if written < 0 {
128 // a signal cut the write short of starting: errno.h's name for
129 // it on this system, not a number
130 if code == C.EINTR {
131 continue
132 }
133 return false
134 }
135 if written == 0 {
136 return false
137 }
138 left -= written
139 p = unsafe { voidptr(uint(p) + uint(written)) }
140 }
141 return true
142}
143
144// HelpEvent is a help text, the overview or one mode's
145struct HelpEvent {
146 kind string = 'help' @[json: 'type']
147 text string
148}
149
150// HelloEvent opens the stream: the protocol, and whether this process runs
151// as root (a child the root provider started)
152struct HelloEvent {
153 kind string = 'hello' @[json: 'type']
154 protocol int
155 root bool
156}
157
158// ExitEvent closes it with the exit status the process is about to have
159struct ExitEvent {
160 kind string = 'exit' @[json: 'type']
161 status int
162}
163
164// ErrorEvent is an error line. target marks the error of one target a query
165// skipped and went on from; any other error ends the run
166struct ErrorEvent {
167 kind string = 'error' @[json: 'type']
168 msg string
169 target bool
170}
171
172// MessageEvent is a line of text a mode reports, a result line such as
173// 'system upgraded' or a warning. error marks one of libalpm's errors, which
174// is a warning too, for a reader that knows no error flag
175struct MessageEvent {
176 kind string = 'message' @[json: 'type']
177 text string
178 warning bool
179 error bool @[omitempty]
180 // verbose marks a line of the verbose log: a failure of housekeeping
181 // the run went on from, said only because --verbose asked
182 verbose bool @[omitempty]
183}
184
185// PhaseEvent is a step of the work: a terminal's spinner. it starts, may be
186// renamed by another start, and is done
187struct PhaseEvent {
188 kind string = 'phase' @[json: 'type']
189 text string
190 state string
191}
192
193// ProgressEvent is libalpm's progress through a transaction step: per
194// package for the package steps (pkg names it, current of total), once for
195// the whole-transaction checks. vpac's own counted steps use it too
196struct ProgressEvent {
197 kind string = 'progress' @[json: 'type']
198 op string
199 pkg string @[omitempty]
200 percent int
201 current int
202 total int
203}
204
205// DownloadEvent is a file libalpm downloads: sent as its percent moves (or
206// every quarter second while it does not), and once more when it is done,
207// with libalpm's result: 0 fetched, 1 already up to date, -1 failed. a retry
208// — libalpm moving on to the next mirror — is an event of its own, retry
209// set: resume says the download goes on from where it stopped, otherwise it
210// starts over, and its byte counts with it
211struct DownloadEvent {
212 kind string = 'download' @[json: 'type']
213 file string
214 downloaded i64
215 total i64
216 done bool
217 result int
218 retry bool @[omitempty]
219 resume bool @[omitempty]
220}
221
222// TransPkg is one package of a transaction listing. version is what the
223// transaction installs or removes; old_version the installed one an
224// install or upgrade replaces, empty for a new package. the sizes are in
225// bytes: what it downloads, and what it takes on disk once installed
226struct TransPkg {
227 name string
228 version string
229 old_version string
230 download_size i64
231 installed_size i64
232}
233
234// TransactionEvent is the listing a transaction asks its go-ahead for: the
235// proceed question follows it. action is install, upgrade, remove or
236// autoremove. a --print preview sends it with preview set, and stops there
237struct TransactionEvent {
238 kind string = 'transaction' @[json: 'type']
239 action string
240 packages []TransPkg
241 download_size i64
242 installed_size i64
243mut:
244 preview bool
245}
246
247// PackagesEvent is a titled list of packages shown beside a transaction or a
248// question: the packages an install removes, the ones an upgrade skips
249struct PackagesEvent {
250 kind string = 'packages' @[json: 'type']
251 title string
252 packages []TransPkg
253}
254
255// DoneEvent is a committed transaction's result, the last word of every
256// mode that commits one: what it did — installed, downloaded, removed,
257// upgraded, marked — and to which packages (install's and remove's targets,
258// autoremove's and upgrade's whole transaction). a mark says the reason the
259// packages have now: explicit, depend or unknown. a declined or failed
260// transaction sends none
261struct DoneEvent {
262 kind string = 'done' @[json: 'type']
263 action string
264 reason string @[omitempty]
265 packages []string
266}
267
268// QuestionEvent asks the frontend. question is confirm (yes or no, preset
269// the answer an empty one takes), proceed (a transaction's go-ahead, preset
270// true) or choose (one of choices, by index, preset 0). the answer is a line
271// {"id": id, "answer": true|false|index} on stdin, the same type as preset.
272// select asks for any number of choices: preset is every index, and the
273// answer a list of indices, an empty one for none.
274// under --noconfirm, answer carries the default taken and nothing is read
275struct QuestionEvent {
276 kind string = 'question' @[json: 'type']
277 id int
278 question string
279 msg string
280 preset json2.Any
281 choices []string @[omitempty]
282 answer ?json2.Any
283}
284
285// InvalidEvent says an answer line did not answer the question asked; the
286// question stands and the next line is read
287struct InvalidEvent {
288 kind string = 'invalid' @[json: 'type']
289 id int
290 msg string
291}
292
293// IpcPrompter asks over the channel: each question is an event with an id,
294// and its answer the next valid line on stdin. end of input answers as a
295// terminal's does: no, and the first choice
296struct IpcPrompter {
297mut:
298 noconfirm bool
299 last_id int
300}
301
302fn (mut p IpcPrompter) confirm(msg string, preset bool) bool {
303 return p.ask('confirm', msg, if preset { 1 } else { 0 }, []string{}) == 1
304}
305
306fn (mut p IpcPrompter) proceed(msg string) bool {
307 return p.ask('proceed', msg, 1, []string{}) == 1
308}
309
310fn (mut p IpcPrompter) choose(msg string, choices []string) int {
311 return p.ask('choose', msg, 0, choices)
312}
313
314// pick asks which of the choices, the select question. the choices were
315// sent ahead as the listing they are, so the question carries their count
316// as the preset alone: every index
317fn (mut p IpcPrompter) pick(msg string, count int) []bool {
318 p.last_id++
319 id := p.last_id
320 all := json2.Any([]json2.Any{len: count, init: json2.Any(index)})
321 if p.noconfirm {
322 emit(QuestionEvent{
323 id: id
324 question: 'select'
325 msg: msg
326 preset: all
327 answer: all
328 })
329 return []bool{len: count, init: true}
330 }
331 emit(QuestionEvent{
332 id: id
333 question: 'select'
334 msg: msg
335 preset: all
336 })
337 for {
338 // end of input selects nothing, as on a terminal
339 line := stdin_line() or { return []bool{len: count} }
340 return parse_select_answer(line, id, count) or {
341 emit(InvalidEvent{
342 id: id
343 msg: err.msg()
344 })
345 continue
346 }
347 }
348 return []bool{len: count}
349}
350
351// answer_of reads an answer line down to its answer: the object, and the id
352// of the question asked, are what tell an answer from noise
353fn answer_of(line string, id int) !json2.Any {
354 doc := json2.decode[json2.Any](line) or { return error('not json: ${line.trim_space()}') }
355 if doc !is map[string]json2.Any {
356 return error('an answer is an object: {"id": id, "answer": answer}')
357 }
358 m := doc.as_map()
359 got := m['id'] or { return error('the answer has no id') }
360 // json2 hands every json number over as f64: a whole one is an id's
361 // number, a text is not an id at all
362 gid := whole_of(got) or { return error("the answer's id is not a number") }
363 if gid != id {
364 return error('the question asked is ${id}, not ${gid}')
365 }
366 return m['answer'] or { return error('the answer has no answer') }
367}
368
369// parse_select_answer reads the answer to a select question: a list of
370// indices into its count choices, which may be empty
371fn parse_select_answer(line string, id int, count int) ![]bool {
372 answer := answer_of(line, id)!
373 if answer !is []json2.Any {
374 return error('question ${id} takes a list of indices, 0 to ${count - 1}')
375 }
376 mut picked := []bool{len: count}
377 for item in answer.as_array() {
378 n := whole_of(item) or {
379 return error('question ${id} takes a list of indices, 0 to ${count - 1}')
380 }
381 if n < 0 || n >= count {
382 return error('question ${id} takes a list of indices, 0 to ${count - 1}')
383 }
384 picked[n] = true
385 }
386 return picked
387}
388
389// ask sends a question and waits for its answer: 1 or 0 for a yes or no,
390// the index for a choice
391fn (mut p IpcPrompter) ask(kind string, msg string, preset int, choices []string) int {
392 p.last_id++
393 id := p.last_id
394 // a yes or no travels as a bool, a choice as its index
395 preset_v := if kind == 'choose' { json2.Any(preset) } else { json2.Any(preset == 1) }
396 if p.noconfirm {
397 emit(QuestionEvent{
398 id: id
399 question: kind
400 msg: msg
401 preset: preset_v
402 choices: choices
403 answer: preset_v
404 })
405 return preset
406 }
407 emit(QuestionEvent{
408 id: id
409 question: kind
410 msg: msg
411 preset: preset_v
412 choices: choices
413 })
414 for {
415 // end of input, or a stdin that cannot be read: no, or the first
416 // choice, as on a terminal. an empty line is a line, and invalid
417 line := stdin_line() or { return 0 }
418 answer := parse_answer(line, id, kind, choices.len) or {
419 emit(InvalidEvent{
420 id: id
421 msg: err.msg()
422 })
423 continue
424 }
425 return answer
426 }
427}
428
429// parse_answer reads one answer line for question id: a bool for a yes or
430// no, an index into the choices for a choose. the object, the id and the
431// answer's type are what tell an answer from noise, and anything else comes
432// back as the error the asker turns into an invalid event, keeping the
433// question and reading the next line
434fn parse_answer(line string, id int, kind string, count int) !int {
435 answer := answer_of(line, id)!
436 if kind == 'choose' {
437 n := whole_of(answer) or { return error('question ${id} takes an index, 0 to ${count - 1}') }
438 if n < 0 || n >= count {
439 return error('question ${id} takes an index, 0 to ${count - 1}')
440 }
441 return n
442 }
443 if answer !is bool {
444 return error('question ${id} takes true or false')
445 }
446 return if answer.bool() { 1 } else { 0 }
447}
448
449// whole_of keeps a json number that is a whole one, like 1 but not 1.5: the
450// question ids and the choice indices travel as integers, and json2's f64 is
451// the one type describing them
452fn whole_of(a json2.Any) ?int {
453 if a is f64 && a == f64(int(a)) {
454 return int(a)
455 }
456 return none
457}
458
459// report is a result line of a mode: printed on a terminal, a message event
460// for a frontend
461fn report(text string) {
462 if ipc_on() {
463 emit(MessageEvent{
464 text: text
465 })
466 return
467 }
468 println(text)
469}
470
471// advise is a plain line that goes with a warning, the advice after it: on
472// stderr for a terminal, a message event marked as a warning for a frontend
473fn advise(text string) {
474 warning_line(text, text)
475}
476
477// warn is a warning: on stderr for a terminal, a message event marked as a
478// warning for a frontend
479fn warn(text string) {
480 warning_line(text, warning(text))
481}
482
483// verbose_flag is --verbose on the command line, cfg_verbose the config's
484// (options #:verbose #t): either turns the verbose log on. the config's is
485// reset with the config; the flag is the command line's and stays
486__global verbose_flag = false
487__global cfg_verbose = false
488
489fn verbose_on() bool {
490 return verbose_flag || cfg_verbose
491}
492
493// went_on is the verbose log's one kind of line: something of the run's
494// housekeeping failed — a handle's release, a temp dir's removal — and the
495// run went on, because nothing the user asked for depended on it. without
496// --verbose it is kept quiet, as it always was; with it the failure is said,
497// on stderr for a terminal and as a message event marked verbose for a
498// frontend, so a run that leaves something behind can be asked why
499fn went_on(what string, err IError) {
500 if !verbose_on() {
501 return
502 }
503 text := 'could not ${what}: ${err.msg()}'
504 if ipc_on() {
505 emit(MessageEvent{
506 text: text
507 warning: true
508 verbose: true
509 })
510 return
511 }
512 eprintln('verbose: ${text}')
513}
514
515// warning_line is the one way a warning or its advice leaves: the plain
516// text as a warning message event for a frontend, the terminal's spelling
517// of it on stderr otherwise
518fn warning_line(text string, on_terminal string) {
519 if ipc_on() {
520 emit(MessageEvent{
521 text: text
522 warning: true
523 })
524 return
525 }
526 eprintln(on_terminal)
527}
528
529// ListingEvent is a package list, search's or orphans': the fields, and for
530// each package its name and its value of every field, in their order. a
531// quiet listing sends the names alone; search -g's entries name the group
532// they were listed for
533struct ListingEvent {
534 kind string = 'listing' @[json: 'type']
535 fields []string
536 entries []ListEntry
537}
538
539// GroupsEvent lists the groups of the sync dbs, search -g without names
540struct GroupsEvent {
541 kind string = 'groups' @[json: 'type']
542 groups []GroupRef
543}
544
545// InfoEvent is one package as info shows it: every field asked for, its
546// value as one text, and the items of a list field
547struct InfoEvent {
548 kind string = 'info' @[json: 'type']
549 fields []InfoField
550}
551
552// ChangelogEvent is a package's changelog, info -c: the text as the package
553// carries it
554struct ChangelogEvent {
555 kind string = 'changelog' @[json: 'type']
556 package string
557 text string
558}
559
560// FilesEvent is the files of a package: an installed one's under the root
561// (files), or a sync one's as its file db lists them (find -l, with repo)
562struct FilesEvent {
563 kind string = 'files' @[json: 'type']
564 package string
565 repo string @[omitempty]
566 paths []string
567}
568
569// ProvidesEvent is find's answer for one path: the sync packages whose files
570// hold it, as a listing. a target that matches many files (-x, or a file
571// name with no slash) also names them: files[i] are the paths matched in the
572// package of entries[i]
573struct ProvidesEvent {
574 kind string = 'provides' @[json: 'type']
575 path string
576 fields []string
577 entries []ListEntry
578 files [][]string @[omitempty]
579}
580
581// OwnerEvent is an installed package that owns a path: one event for a
582// file, one per owner for a directory (packages share those), the path
583// repeated, as pacman -Qo lists them
584struct OwnerEvent {
585 kind string = 'owner' @[json: 'type']
586 path string
587 package string
588 version string
589}
590
591// UnsatisfiedEvent is deptest's answer: the dependencies no installed
592// package satisfies, none when all are
593struct UnsatisfiedEvent {
594 kind string = 'unsatisfied' @[json: 'type']
595 deps []string
596}
597
598// TreeItem is a node of a dependency tree: a package (found), or the
599// dependency nothing provides (name is then how it was asked for). seen
600// marks a package expanded elsewhere in the tree, whose branches are there
601struct TreeItem {
602 name string
603 version string
604 found bool
605 optional bool
606 seen bool
607 children []TreeItem
608}
609
610// TreeEvent is one target's tree: its dependencies, or with reverse what
611// requires it
612struct TreeEvent {
613 kind string = 'tree' @[json: 'type']
614 reverse bool
615 root TreeItem
616}
617
618// VerifyEvent is verify's report: a line per finding, problem telling the
619// ones that count against a package from notes, and how many packages have
620// problems
621struct VerifyEvent {
622 kind string = 'verify' @[json: 'type']
623 lines []VerifyLine
624 bad int
625}
626
627// MirrorEvent is one mirror of a ranking: latency in ms, speed in bytes per
628// second, last_sync as the mirror status gives it
629struct MirrorEvent {
630 url string
631 latency_ms i64
632 speed f64
633 last_sync string
634}
635
636// MirrorsEvent is rank's result, the fastest first
637struct MirrorsEvent {
638 kind string = 'mirrors' @[json: 'type']
639 mirrors []MirrorEvent
640}
641
642// CleanEvent is what clean removes: the cached files and the pkgbuild build
643// dirs, with their sizes, and the sync db files of repos the config no
644// longer names (dbs). the proceed question follows it, except for a
645// --print preview, which stops there. build_root is absent when no invoker
646// is known (root running vpac c itself): the builds were not looked at then,
647// which an empty root beside an empty list would tell as none found
648struct CleanEvent {
649 kind string = 'clean' @[json: 'type']
650 cache_dirs []string
651 build_root ?string
652 files []string
653 files_size u64
654 builds []string
655 build_size u64
656 // build_size_partial: part of a build could not be read, and build_size
657 // is a floor, not the size
658 build_size_partial bool
659 dbs []string
660 preview bool
661}
662