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