github.com/fabiokung/docker@v0.11.2-0.20170222101415-4534dcd49497/daemon/logger/journald/read.go (about) 1 // +build linux,cgo,!static_build,journald 2 3 package journald 4 5 // #include <sys/types.h> 6 // #include <sys/poll.h> 7 // #include <systemd/sd-journal.h> 8 // #include <errno.h> 9 // #include <stdio.h> 10 // #include <stdlib.h> 11 // #include <string.h> 12 // #include <time.h> 13 // #include <unistd.h> 14 // 15 //static int get_message(sd_journal *j, const char **msg, size_t *length, int *partial) 16 //{ 17 // int rc; 18 // size_t plength; 19 // *msg = NULL; 20 // *length = 0; 21 // plength = strlen("CONTAINER_PARTIAL_MESSAGE=true"); 22 // rc = sd_journal_get_data(j, "CONTAINER_PARTIAL_MESSAGE", (const void **) msg, length); 23 // *partial = ((rc == 0) && (*length == plength) && (memcmp(*msg, "CONTAINER_PARTIAL_MESSAGE=true", plength) == 0)); 24 // rc = sd_journal_get_data(j, "MESSAGE", (const void **) msg, length); 25 // if (rc == 0) { 26 // if (*length > 8) { 27 // (*msg) += 8; 28 // *length -= 8; 29 // } else { 30 // *msg = NULL; 31 // *length = 0; 32 // rc = -ENOENT; 33 // } 34 // } 35 // return rc; 36 //} 37 //static int get_priority(sd_journal *j, int *priority) 38 //{ 39 // const void *data; 40 // size_t i, length; 41 // int rc; 42 // *priority = -1; 43 // rc = sd_journal_get_data(j, "PRIORITY", &data, &length); 44 // if (rc == 0) { 45 // if ((length > 9) && (strncmp(data, "PRIORITY=", 9) == 0)) { 46 // *priority = 0; 47 // for (i = 9; i < length; i++) { 48 // *priority = *priority * 10 + ((const char *)data)[i] - '0'; 49 // } 50 // if (length > 9) { 51 // rc = 0; 52 // } 53 // } 54 // } 55 // return rc; 56 //} 57 //static int is_attribute_field(const char *msg, size_t length) 58 //{ 59 // static const struct known_field { 60 // const char *name; 61 // size_t length; 62 // } fields[] = { 63 // {"MESSAGE", sizeof("MESSAGE") - 1}, 64 // {"MESSAGE_ID", sizeof("MESSAGE_ID") - 1}, 65 // {"PRIORITY", sizeof("PRIORITY") - 1}, 66 // {"CODE_FILE", sizeof("CODE_FILE") - 1}, 67 // {"CODE_LINE", sizeof("CODE_LINE") - 1}, 68 // {"CODE_FUNC", sizeof("CODE_FUNC") - 1}, 69 // {"ERRNO", sizeof("ERRNO") - 1}, 70 // {"SYSLOG_FACILITY", sizeof("SYSLOG_FACILITY") - 1}, 71 // {"SYSLOG_IDENTIFIER", sizeof("SYSLOG_IDENTIFIER") - 1}, 72 // {"SYSLOG_PID", sizeof("SYSLOG_PID") - 1}, 73 // {"CONTAINER_NAME", sizeof("CONTAINER_NAME") - 1}, 74 // {"CONTAINER_ID", sizeof("CONTAINER_ID") - 1}, 75 // {"CONTAINER_ID_FULL", sizeof("CONTAINER_ID_FULL") - 1}, 76 // {"CONTAINER_TAG", sizeof("CONTAINER_TAG") - 1}, 77 // }; 78 // unsigned int i; 79 // void *p; 80 // if ((length < 1) || (msg[0] == '_') || ((p = memchr(msg, '=', length)) == NULL)) { 81 // return -1; 82 // } 83 // length = ((const char *) p) - msg; 84 // for (i = 0; i < sizeof(fields) / sizeof(fields[0]); i++) { 85 // if ((fields[i].length == length) && (memcmp(fields[i].name, msg, length) == 0)) { 86 // return -1; 87 // } 88 // } 89 // return 0; 90 //} 91 //static int get_attribute_field(sd_journal *j, const char **msg, size_t *length) 92 //{ 93 // int rc; 94 // *msg = NULL; 95 // *length = 0; 96 // while ((rc = sd_journal_enumerate_data(j, (const void **) msg, length)) > 0) { 97 // if (is_attribute_field(*msg, *length) == 0) { 98 // break; 99 // } 100 // rc = -ENOENT; 101 // } 102 // return rc; 103 //} 104 //static int wait_for_data_cancelable(sd_journal *j, int pipefd) 105 //{ 106 // struct pollfd fds[2]; 107 // uint64_t when = 0; 108 // int timeout, jevents, i; 109 // struct timespec ts; 110 // uint64_t now; 111 // 112 // memset(&fds, 0, sizeof(fds)); 113 // fds[0].fd = pipefd; 114 // fds[0].events = POLLHUP; 115 // fds[1].fd = sd_journal_get_fd(j); 116 // if (fds[1].fd < 0) { 117 // return fds[1].fd; 118 // } 119 // 120 // do { 121 // jevents = sd_journal_get_events(j); 122 // if (jevents < 0) { 123 // return jevents; 124 // } 125 // fds[1].events = jevents; 126 // sd_journal_get_timeout(j, &when); 127 // if (when == -1) { 128 // timeout = -1; 129 // } else { 130 // clock_gettime(CLOCK_MONOTONIC, &ts); 131 // now = (uint64_t) ts.tv_sec * 1000000 + ts.tv_nsec / 1000; 132 // timeout = when > now ? (int) ((when - now + 999) / 1000) : 0; 133 // } 134 // i = poll(fds, 2, timeout); 135 // if ((i == -1) && (errno != EINTR)) { 136 // /* An unexpected error. */ 137 // return (errno != 0) ? -errno : -EINTR; 138 // } 139 // if (fds[0].revents & POLLHUP) { 140 // /* The close notification pipe was closed. */ 141 // return 0; 142 // } 143 // if (sd_journal_process(j) == SD_JOURNAL_APPEND) { 144 // /* Data, which we might care about, was appended. */ 145 // return 1; 146 // } 147 // } while ((fds[0].revents & POLLHUP) == 0); 148 // return 0; 149 //} 150 import "C" 151 152 import ( 153 "fmt" 154 "strings" 155 "time" 156 "unsafe" 157 158 "github.com/Sirupsen/logrus" 159 "github.com/coreos/go-systemd/journal" 160 "github.com/docker/docker/daemon/logger" 161 ) 162 163 func (s *journald) Close() error { 164 s.readers.mu.Lock() 165 for reader := range s.readers.readers { 166 reader.Close() 167 } 168 s.readers.mu.Unlock() 169 return nil 170 } 171 172 func (s *journald) drainJournal(logWatcher *logger.LogWatcher, config logger.ReadConfig, j *C.sd_journal, oldCursor *C.char) *C.char { 173 var msg, data, cursor *C.char 174 var length C.size_t 175 var stamp C.uint64_t 176 var priority, partial C.int 177 178 // Walk the journal from here forward until we run out of new entries. 179 drain: 180 for { 181 // Try not to send a given entry twice. 182 if oldCursor != nil { 183 for C.sd_journal_test_cursor(j, oldCursor) > 0 { 184 if C.sd_journal_next(j) <= 0 { 185 break drain 186 } 187 } 188 } 189 // Read and send the logged message, if there is one to read. 190 i := C.get_message(j, &msg, &length, &partial) 191 if i != -C.ENOENT && i != -C.EADDRNOTAVAIL { 192 // Read the entry's timestamp. 193 if C.sd_journal_get_realtime_usec(j, &stamp) != 0 { 194 break 195 } 196 // Set up the time and text of the entry. 197 timestamp := time.Unix(int64(stamp)/1000000, (int64(stamp)%1000000)*1000) 198 line := C.GoBytes(unsafe.Pointer(msg), C.int(length)) 199 if partial == 0 { 200 line = append(line, "\n"...) 201 } 202 // Recover the stream name by mapping 203 // from the journal priority back to 204 // the stream that we would have 205 // assigned that value. 206 source := "" 207 if C.get_priority(j, &priority) != 0 { 208 source = "" 209 } else if priority == C.int(journal.PriErr) { 210 source = "stderr" 211 } else if priority == C.int(journal.PriInfo) { 212 source = "stdout" 213 } 214 // Retrieve the values of any variables we're adding to the journal. 215 attrs := make(map[string]string) 216 C.sd_journal_restart_data(j) 217 for C.get_attribute_field(j, &data, &length) > C.int(0) { 218 kv := strings.SplitN(C.GoStringN(data, C.int(length)), "=", 2) 219 attrs[kv[0]] = kv[1] 220 } 221 if len(attrs) == 0 { 222 attrs = nil 223 } 224 // Send the log message. 225 logWatcher.Msg <- &logger.Message{ 226 Line: line, 227 Source: source, 228 Timestamp: timestamp.In(time.UTC), 229 Attrs: attrs, 230 } 231 } 232 // If we're at the end of the journal, we're done (for now). 233 if C.sd_journal_next(j) <= 0 { 234 break 235 } 236 } 237 238 // free(NULL) is safe 239 C.free(unsafe.Pointer(oldCursor)) 240 C.sd_journal_get_cursor(j, &cursor) 241 return cursor 242 } 243 244 func (s *journald) followJournal(logWatcher *logger.LogWatcher, config logger.ReadConfig, j *C.sd_journal, pfd [2]C.int, cursor *C.char) *C.char { 245 s.readers.mu.Lock() 246 s.readers.readers[logWatcher] = logWatcher 247 s.readers.mu.Unlock() 248 249 go func() { 250 for { 251 // Keep copying journal data out until we're notified to stop 252 // or we hit an error. 253 status := C.wait_for_data_cancelable(j, pfd[0]) 254 if status < 0 { 255 cerrstr := C.strerror(C.int(-status)) 256 errstr := C.GoString(cerrstr) 257 fmtstr := "error %q while attempting to follow journal for container %q" 258 logrus.Errorf(fmtstr, errstr, s.vars["CONTAINER_ID_FULL"]) 259 break 260 } 261 262 cursor = s.drainJournal(logWatcher, config, j, cursor) 263 264 if status != 1 { 265 // We were notified to stop 266 break 267 } 268 } 269 270 // Clean up. 271 C.close(pfd[0]) 272 s.readers.mu.Lock() 273 delete(s.readers.readers, logWatcher) 274 s.readers.mu.Unlock() 275 C.sd_journal_close(j) 276 close(logWatcher.Msg) 277 }() 278 279 // Wait until we're told to stop. 280 select { 281 case <-logWatcher.WatchClose(): 282 // Notify the other goroutine that its work is done. 283 C.close(pfd[1]) 284 } 285 286 return cursor 287 } 288 289 func (s *journald) readLogs(logWatcher *logger.LogWatcher, config logger.ReadConfig) { 290 var j *C.sd_journal 291 var cmatch, cursor *C.char 292 var stamp C.uint64_t 293 var sinceUnixMicro uint64 294 var pipes [2]C.int 295 296 // Get a handle to the journal. 297 rc := C.sd_journal_open(&j, C.int(0)) 298 if rc != 0 { 299 logWatcher.Err <- fmt.Errorf("error opening journal") 300 close(logWatcher.Msg) 301 return 302 } 303 // If we end up following the log, we can set the journal context 304 // pointer and the channel pointer to nil so that we won't close them 305 // here, potentially while the goroutine that uses them is still 306 // running. Otherwise, close them when we return from this function. 307 following := false 308 defer func(pfollowing *bool) { 309 if !*pfollowing { 310 C.sd_journal_close(j) 311 close(logWatcher.Msg) 312 } 313 }(&following) 314 // Remove limits on the size of data items that we'll retrieve. 315 rc = C.sd_journal_set_data_threshold(j, C.size_t(0)) 316 if rc != 0 { 317 logWatcher.Err <- fmt.Errorf("error setting journal data threshold") 318 return 319 } 320 // Add a match to have the library do the searching for us. 321 cmatch = C.CString("CONTAINER_ID_FULL=" + s.vars["CONTAINER_ID_FULL"]) 322 defer C.free(unsafe.Pointer(cmatch)) 323 rc = C.sd_journal_add_match(j, unsafe.Pointer(cmatch), C.strlen(cmatch)) 324 if rc != 0 { 325 logWatcher.Err <- fmt.Errorf("error setting journal match") 326 return 327 } 328 // If we have a cutoff time, convert it to Unix time once. 329 if !config.Since.IsZero() { 330 nano := config.Since.UnixNano() 331 sinceUnixMicro = uint64(nano / 1000) 332 } 333 if config.Tail > 0 { 334 lines := config.Tail 335 // Start at the end of the journal. 336 if C.sd_journal_seek_tail(j) < 0 { 337 logWatcher.Err <- fmt.Errorf("error seeking to end of journal") 338 return 339 } 340 if C.sd_journal_previous(j) < 0 { 341 logWatcher.Err <- fmt.Errorf("error backtracking to previous journal entry") 342 return 343 } 344 // Walk backward. 345 for lines > 0 { 346 // Stop if the entry time is before our cutoff. 347 // We'll need the entry time if it isn't, so go 348 // ahead and parse it now. 349 if C.sd_journal_get_realtime_usec(j, &stamp) != 0 { 350 break 351 } else { 352 // Compare the timestamp on the entry 353 // to our threshold value. 354 if sinceUnixMicro != 0 && sinceUnixMicro > uint64(stamp) { 355 break 356 } 357 } 358 lines-- 359 // If we're at the start of the journal, or 360 // don't need to back up past any more entries, 361 // stop. 362 if lines == 0 || C.sd_journal_previous(j) <= 0 { 363 break 364 } 365 } 366 } else { 367 // Start at the beginning of the journal. 368 if C.sd_journal_seek_head(j) < 0 { 369 logWatcher.Err <- fmt.Errorf("error seeking to start of journal") 370 return 371 } 372 // If we have a cutoff date, fast-forward to it. 373 if sinceUnixMicro != 0 && C.sd_journal_seek_realtime_usec(j, C.uint64_t(sinceUnixMicro)) != 0 { 374 logWatcher.Err <- fmt.Errorf("error seeking to start time in journal") 375 return 376 } 377 if C.sd_journal_next(j) < 0 { 378 logWatcher.Err <- fmt.Errorf("error skipping to next journal entry") 379 return 380 } 381 } 382 cursor = s.drainJournal(logWatcher, config, j, nil) 383 if config.Follow { 384 // Allocate a descriptor for following the journal, if we'll 385 // need one. Do it here so that we can report if it fails. 386 if fd := C.sd_journal_get_fd(j); fd < C.int(0) { 387 logWatcher.Err <- fmt.Errorf("error opening journald follow descriptor: %q", C.GoString(C.strerror(-fd))) 388 } else { 389 // Create a pipe that we can poll at the same time as 390 // the journald descriptor. 391 if C.pipe(&pipes[0]) == C.int(-1) { 392 logWatcher.Err <- fmt.Errorf("error opening journald close notification pipe") 393 } else { 394 cursor = s.followJournal(logWatcher, config, j, pipes, cursor) 395 // Let followJournal handle freeing the journal context 396 // object and closing the channel. 397 following = true 398 } 399 } 400 } 401 402 C.free(unsafe.Pointer(cursor)) 403 return 404 } 405 406 func (s *journald) ReadLogs(config logger.ReadConfig) *logger.LogWatcher { 407 logWatcher := logger.NewLogWatcher() 408 go s.readLogs(logWatcher, config) 409 return logWatcher 410 }