github.com/jiasir/docker@v1.3.3-0.20170609024000-252e610103e7/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.mu.Lock() 165 s.closed = true 166 for reader := range s.readers.readers { 167 reader.Close() 168 } 169 s.mu.Unlock() 170 return nil 171 } 172 173 func (s *journald) drainJournal(logWatcher *logger.LogWatcher, config logger.ReadConfig, j *C.sd_journal, oldCursor *C.char) *C.char { 174 var msg, data, cursor *C.char 175 var length C.size_t 176 var stamp C.uint64_t 177 var priority, partial C.int 178 179 // Walk the journal from here forward until we run out of new entries. 180 drain: 181 for { 182 // Try not to send a given entry twice. 183 if oldCursor != nil { 184 for C.sd_journal_test_cursor(j, oldCursor) > 0 { 185 if C.sd_journal_next(j) <= 0 { 186 break drain 187 } 188 } 189 } 190 // Read and send the logged message, if there is one to read. 191 i := C.get_message(j, &msg, &length, &partial) 192 if i != -C.ENOENT && i != -C.EADDRNOTAVAIL { 193 // Read the entry's timestamp. 194 if C.sd_journal_get_realtime_usec(j, &stamp) != 0 { 195 break 196 } 197 // Set up the time and text of the entry. 198 timestamp := time.Unix(int64(stamp)/1000000, (int64(stamp)%1000000)*1000) 199 line := C.GoBytes(unsafe.Pointer(msg), C.int(length)) 200 if partial == 0 { 201 line = append(line, "\n"...) 202 } 203 // Recover the stream name by mapping 204 // from the journal priority back to 205 // the stream that we would have 206 // assigned that value. 207 source := "" 208 if C.get_priority(j, &priority) != 0 { 209 source = "" 210 } else if priority == C.int(journal.PriErr) { 211 source = "stderr" 212 } else if priority == C.int(journal.PriInfo) { 213 source = "stdout" 214 } 215 // Retrieve the values of any variables we're adding to the journal. 216 attrs := make(map[string]string) 217 C.sd_journal_restart_data(j) 218 for C.get_attribute_field(j, &data, &length) > C.int(0) { 219 kv := strings.SplitN(C.GoStringN(data, C.int(length)), "=", 2) 220 attrs[kv[0]] = kv[1] 221 } 222 if len(attrs) == 0 { 223 attrs = nil 224 } 225 // Send the log message. 226 logWatcher.Msg <- &logger.Message{ 227 Line: line, 228 Source: source, 229 Timestamp: timestamp.In(time.UTC), 230 Attrs: attrs, 231 } 232 } 233 // If we're at the end of the journal, we're done (for now). 234 if C.sd_journal_next(j) <= 0 { 235 break 236 } 237 } 238 239 // free(NULL) is safe 240 C.free(unsafe.Pointer(oldCursor)) 241 if C.sd_journal_get_cursor(j, &cursor) != 0 { 242 // ensure that we won't be freeing an address that's invalid 243 cursor = nil 244 } 245 return cursor 246 } 247 248 func (s *journald) followJournal(logWatcher *logger.LogWatcher, config logger.ReadConfig, j *C.sd_journal, pfd [2]C.int, cursor *C.char) *C.char { 249 s.mu.Lock() 250 s.readers.readers[logWatcher] = logWatcher 251 if s.closed { 252 // the journald Logger is closed, presumably because the container has been 253 // reset. So we shouldn't follow, because we'll never be woken up. But we 254 // should make one more drainJournal call to be sure we've got all the logs. 255 // Close pfd[1] so that one drainJournal happens, then cleanup, then return. 256 C.close(pfd[1]) 257 } 258 s.mu.Unlock() 259 260 newCursor := make(chan *C.char) 261 262 go func() { 263 for { 264 // Keep copying journal data out until we're notified to stop 265 // or we hit an error. 266 status := C.wait_for_data_cancelable(j, pfd[0]) 267 if status < 0 { 268 cerrstr := C.strerror(C.int(-status)) 269 errstr := C.GoString(cerrstr) 270 fmtstr := "error %q while attempting to follow journal for container %q" 271 logrus.Errorf(fmtstr, errstr, s.vars["CONTAINER_ID_FULL"]) 272 break 273 } 274 275 cursor = s.drainJournal(logWatcher, config, j, cursor) 276 277 if status != 1 { 278 // We were notified to stop 279 break 280 } 281 } 282 283 // Clean up. 284 C.close(pfd[0]) 285 s.mu.Lock() 286 delete(s.readers.readers, logWatcher) 287 s.mu.Unlock() 288 close(logWatcher.Msg) 289 newCursor <- cursor 290 }() 291 292 // Wait until we're told to stop. 293 select { 294 case cursor = <-newCursor: 295 case <-logWatcher.WatchClose(): 296 // Notify the other goroutine that its work is done. 297 C.close(pfd[1]) 298 cursor = <-newCursor 299 } 300 301 return cursor 302 } 303 304 func (s *journald) readLogs(logWatcher *logger.LogWatcher, config logger.ReadConfig) { 305 var j *C.sd_journal 306 var cmatch, cursor *C.char 307 var stamp C.uint64_t 308 var sinceUnixMicro uint64 309 var pipes [2]C.int 310 311 // Get a handle to the journal. 312 rc := C.sd_journal_open(&j, C.int(0)) 313 if rc != 0 { 314 logWatcher.Err <- fmt.Errorf("error opening journal") 315 close(logWatcher.Msg) 316 return 317 } 318 // If we end up following the log, we can set the journal context 319 // pointer and the channel pointer to nil so that we won't close them 320 // here, potentially while the goroutine that uses them is still 321 // running. Otherwise, close them when we return from this function. 322 following := false 323 defer func(pfollowing *bool) { 324 if !*pfollowing { 325 close(logWatcher.Msg) 326 } 327 C.sd_journal_close(j) 328 }(&following) 329 // Remove limits on the size of data items that we'll retrieve. 330 rc = C.sd_journal_set_data_threshold(j, C.size_t(0)) 331 if rc != 0 { 332 logWatcher.Err <- fmt.Errorf("error setting journal data threshold") 333 return 334 } 335 // Add a match to have the library do the searching for us. 336 cmatch = C.CString("CONTAINER_ID_FULL=" + s.vars["CONTAINER_ID_FULL"]) 337 defer C.free(unsafe.Pointer(cmatch)) 338 rc = C.sd_journal_add_match(j, unsafe.Pointer(cmatch), C.strlen(cmatch)) 339 if rc != 0 { 340 logWatcher.Err <- fmt.Errorf("error setting journal match") 341 return 342 } 343 // If we have a cutoff time, convert it to Unix time once. 344 if !config.Since.IsZero() { 345 nano := config.Since.UnixNano() 346 sinceUnixMicro = uint64(nano / 1000) 347 } 348 if config.Tail > 0 { 349 lines := config.Tail 350 // Start at the end of the journal. 351 if C.sd_journal_seek_tail(j) < 0 { 352 logWatcher.Err <- fmt.Errorf("error seeking to end of journal") 353 return 354 } 355 if C.sd_journal_previous(j) < 0 { 356 logWatcher.Err <- fmt.Errorf("error backtracking to previous journal entry") 357 return 358 } 359 // Walk backward. 360 for lines > 0 { 361 // Stop if the entry time is before our cutoff. 362 // We'll need the entry time if it isn't, so go 363 // ahead and parse it now. 364 if C.sd_journal_get_realtime_usec(j, &stamp) != 0 { 365 break 366 } else { 367 // Compare the timestamp on the entry 368 // to our threshold value. 369 if sinceUnixMicro != 0 && sinceUnixMicro > uint64(stamp) { 370 break 371 } 372 } 373 lines-- 374 // If we're at the start of the journal, or 375 // don't need to back up past any more entries, 376 // stop. 377 if lines == 0 || C.sd_journal_previous(j) <= 0 { 378 break 379 } 380 } 381 } else { 382 // Start at the beginning of the journal. 383 if C.sd_journal_seek_head(j) < 0 { 384 logWatcher.Err <- fmt.Errorf("error seeking to start of journal") 385 return 386 } 387 // If we have a cutoff date, fast-forward to it. 388 if sinceUnixMicro != 0 && C.sd_journal_seek_realtime_usec(j, C.uint64_t(sinceUnixMicro)) != 0 { 389 logWatcher.Err <- fmt.Errorf("error seeking to start time in journal") 390 return 391 } 392 if C.sd_journal_next(j) < 0 { 393 logWatcher.Err <- fmt.Errorf("error skipping to next journal entry") 394 return 395 } 396 } 397 cursor = s.drainJournal(logWatcher, config, j, nil) 398 if config.Follow { 399 // Allocate a descriptor for following the journal, if we'll 400 // need one. Do it here so that we can report if it fails. 401 if fd := C.sd_journal_get_fd(j); fd < C.int(0) { 402 logWatcher.Err <- fmt.Errorf("error opening journald follow descriptor: %q", C.GoString(C.strerror(-fd))) 403 } else { 404 // Create a pipe that we can poll at the same time as 405 // the journald descriptor. 406 if C.pipe(&pipes[0]) == C.int(-1) { 407 logWatcher.Err <- fmt.Errorf("error opening journald close notification pipe") 408 } else { 409 cursor = s.followJournal(logWatcher, config, j, pipes, cursor) 410 // Let followJournal handle freeing the journal context 411 // object and closing the channel. 412 following = true 413 } 414 } 415 } 416 417 C.free(unsafe.Pointer(cursor)) 418 return 419 } 420 421 func (s *journald) ReadLogs(config logger.ReadConfig) *logger.LogWatcher { 422 logWatcher := logger.NewLogWatcher() 423 go s.readLogs(logWatcher, config) 424 return logWatcher 425 }