nspkg / engine / action_log.v
84 lines · 76 sloc · 2.55 KB · c01b0795d1db56c7bce2539b2c46b110637fdc1a
Raw
1// logfile lifetime and action records follow pacman log.c and handle.c.
2module engine
3
4import os
5import time
6
7#include <syslog.h>
8
9fn C.syslog(i32, &char, ...voidptr)
10
11pub fn (mut handle Handle) log_action(prefix string, message string) ! {
12 if handle == unsafe { nil } { return AlpmError{ kind: .handle_null } }
13 if handle.released { return handle.fail(.handle_null, '') }
14 mut problem := Errno.ok
15 mut detail := ''
16 if handle.action_log_fd < 0 && StringOption.logfile in handle.opts.strings {
17 path := c_string_prefix(handle.opts.strings[.logfile])
18 for {
19 handle.action_log_fd = C.open(unsafe { &char(path.str) }, C.O_WRONLY | C.O_APPEND | C.O_CREAT | C.O_CLOEXEC, 0o644)
20 if handle.action_log_fd >= 0 { break }
21 if C.errno == C.EINTR { continue }
22 failure := os.last_error()
23 detail = failure.msg()
24 problem = match failure.code() {
25 13 { Errno.badperms }
26 2 { Errno.not_a_dir }
27 else { Errno.system }
28 }
29 break
30 }
31 }
32 text := c_string_prefix(message)
33 if handle.opts.integers[.use_syslog] != 0 {
34 C.syslog(C.LOG_WARNING, c'%s', text.str)
35 }
36 if handle.action_log_fd >= 0 {
37 supplied := c_string_prefix(prefix)
38 caller := if supplied == '' { 'UNKNOWN' } else { supplied }
39 stamp := time.now().custom_format('YYYY-MM-DDTHH:mm:ssZZ')
40 record := '[${stamp}] [${caller}] ${text}'
41 mut position := 0
42 for position < record.len {
43 count := C.write(handle.action_log_fd, unsafe { record.str + position }, uint(record.len - position))
44 if count < 0 && C.errno == C.EINTR { continue }
45 if count <= 0 {
46 problem = .system
47 detail = os.last_error().msg()
48 break
49 }
50 position += count
51 }
52 }
53 if problem != .ok { return handle.fail(problem, detail) }
54}
55
56fn (mut handle Handle) close_action_log() {
57 if handle.action_log_fd < 0 { return }
58 descriptor := handle.action_log_fd
59 handle.action_log_fd = -1
60 if C.close(descriptor) != 0 {
61 handle.diagnostics << 'could not close action log: ${os.last_error().msg()}'
62 }
63}
64
65fn (mut handle Handle) record_action(message string) {
66 handle.record_action_as('ALPM', message)
67}
68
69fn (mut handle Handle) record_action_as(prefix string, message string) {
70 handle.log_action(prefix, message) or {
71 handle.diagnostics << 'could not write action log: ${err.msg()}'
72 }
73}
74
75fn (mut handle Handle) record_failed_transaction() {
76 // trans.c preserves the transaction error even if writing its failure fails.
77 kind := handle.last_error
78 detail := handle.last_detail
79 valid := handle.last_detail_valid
80 handle.record_action('transaction failed\n')
81 handle.last_error = kind
82 handle.last_detail = detail
83 handle.last_detail_valid = valid
84}
85