github.com/yogeshlonkar/moby@v1.13.2-0.20201203103638-c0b64beaea94/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  	if C.sd_journal_get_cursor(j, &cursor) != 0 {
   241  		// ensure that we won't be freeing an address that's invalid
   242  		cursor = nil
   243  	}
   244  	return cursor
   245  }
   246  
   247  func (s *journald) followJournal(logWatcher *logger.LogWatcher, config logger.ReadConfig, j *C.sd_journal, pfd [2]C.int, cursor *C.char) *C.char {
   248  	s.readers.mu.Lock()
   249  	s.readers.readers[logWatcher] = logWatcher
   250  	s.readers.mu.Unlock()
   251  
   252  	newCursor := make(chan *C.char)
   253  
   254  	go func() {
   255  		// Keep copying journal data out until we're notified to stop
   256  		// or we hit an error.
   257  		status := C.wait_for_data_cancelable(j, pfd[0])
   258  		for status == 1 {
   259  			cursor = s.drainJournal(logWatcher, config, j, cursor)
   260  			status = C.wait_for_data_cancelable(j, pfd[0])
   261  		}
   262  		if status < 0 {
   263  			cerrstr := C.strerror(C.int(-status))
   264  			errstr := C.GoString(cerrstr)
   265  			fmtstr := "error %q while attempting to follow journal for container %q"
   266  			logrus.Errorf(fmtstr, errstr, s.vars["CONTAINER_ID_FULL"])
   267  		}
   268  		// Clean up.
   269  		C.close(pfd[0])
   270  		s.readers.mu.Lock()
   271  		delete(s.readers.readers, logWatcher)
   272  		s.readers.mu.Unlock()
   273  		close(logWatcher.Msg)
   274  		newCursor <- cursor
   275  	}()
   276  	// Wait until we're told to stop.
   277  	select {
   278  	case <-logWatcher.WatchClose():
   279  		// Notify the other goroutine that its work is done.
   280  		C.close(pfd[1])
   281  	}
   282  
   283  	cursor = <-newCursor
   284  
   285  	return cursor
   286  }
   287  
   288  func (s *journald) readLogs(logWatcher *logger.LogWatcher, config logger.ReadConfig) {
   289  	var j *C.sd_journal
   290  	var cmatch, cursor *C.char
   291  	var stamp C.uint64_t
   292  	var sinceUnixMicro uint64
   293  	var pipes [2]C.int
   294  
   295  	// Get a handle to the journal.
   296  	rc := C.sd_journal_open(&j, C.int(0))
   297  	if rc != 0 {
   298  		logWatcher.Err <- fmt.Errorf("error opening journal")
   299  		close(logWatcher.Msg)
   300  		return
   301  	}
   302  	// If we end up following the log, we can set the journal context
   303  	// pointer and the channel pointer to nil so that we won't close them
   304  	// here, potentially while the goroutine that uses them is still
   305  	// running.  Otherwise, close them when we return from this function.
   306  	following := false
   307  	defer func(pfollowing *bool) {
   308  		if !*pfollowing {
   309  			close(logWatcher.Msg)
   310  		}
   311  		C.sd_journal_close(j)
   312  	}(&following)
   313  	// Remove limits on the size of data items that we'll retrieve.
   314  	rc = C.sd_journal_set_data_threshold(j, C.size_t(0))
   315  	if rc != 0 {
   316  		logWatcher.Err <- fmt.Errorf("error setting journal data threshold")
   317  		return
   318  	}
   319  	// Add a match to have the library do the searching for us.
   320  	cmatch = C.CString("CONTAINER_ID_FULL=" + s.vars["CONTAINER_ID_FULL"])
   321  	defer C.free(unsafe.Pointer(cmatch))
   322  	rc = C.sd_journal_add_match(j, unsafe.Pointer(cmatch), C.strlen(cmatch))
   323  	if rc != 0 {
   324  		logWatcher.Err <- fmt.Errorf("error setting journal match")
   325  		return
   326  	}
   327  	// If we have a cutoff time, convert it to Unix time once.
   328  	if !config.Since.IsZero() {
   329  		nano := config.Since.UnixNano()
   330  		sinceUnixMicro = uint64(nano / 1000)
   331  	}
   332  	if config.Tail > 0 {
   333  		lines := config.Tail
   334  		// Start at the end of the journal.
   335  		if C.sd_journal_seek_tail(j) < 0 {
   336  			logWatcher.Err <- fmt.Errorf("error seeking to end of journal")
   337  			return
   338  		}
   339  		if C.sd_journal_previous(j) < 0 {
   340  			logWatcher.Err <- fmt.Errorf("error backtracking to previous journal entry")
   341  			return
   342  		}
   343  		// Walk backward.
   344  		for lines > 0 {
   345  			// Stop if the entry time is before our cutoff.
   346  			// We'll need the entry time if it isn't, so go
   347  			// ahead and parse it now.
   348  			if C.sd_journal_get_realtime_usec(j, &stamp) != 0 {
   349  				break
   350  			} else {
   351  				// Compare the timestamp on the entry
   352  				// to our threshold value.
   353  				if sinceUnixMicro != 0 && sinceUnixMicro > uint64(stamp) {
   354  					break
   355  				}
   356  			}
   357  			lines--
   358  			// If we're at the start of the journal, or
   359  			// don't need to back up past any more entries,
   360  			// stop.
   361  			if lines == 0 || C.sd_journal_previous(j) <= 0 {
   362  				break
   363  			}
   364  		}
   365  	} else {
   366  		// Start at the beginning of the journal.
   367  		if C.sd_journal_seek_head(j) < 0 {
   368  			logWatcher.Err <- fmt.Errorf("error seeking to start of journal")
   369  			return
   370  		}
   371  		// If we have a cutoff date, fast-forward to it.
   372  		if sinceUnixMicro != 0 && C.sd_journal_seek_realtime_usec(j, C.uint64_t(sinceUnixMicro)) != 0 {
   373  			logWatcher.Err <- fmt.Errorf("error seeking to start time in journal")
   374  			return
   375  		}
   376  		if C.sd_journal_next(j) < 0 {
   377  			logWatcher.Err <- fmt.Errorf("error skipping to next journal entry")
   378  			return
   379  		}
   380  	}
   381  	cursor = s.drainJournal(logWatcher, config, j, nil)
   382  	if config.Follow {
   383  		// Allocate a descriptor for following the journal, if we'll
   384  		// need one.  Do it here so that we can report if it fails.
   385  		if fd := C.sd_journal_get_fd(j); fd < C.int(0) {
   386  			logWatcher.Err <- fmt.Errorf("error opening journald follow descriptor: %q", C.GoString(C.strerror(-fd)))
   387  		} else {
   388  			// Create a pipe that we can poll at the same time as
   389  			// the journald descriptor.
   390  			if C.pipe(&pipes[0]) == C.int(-1) {
   391  				logWatcher.Err <- fmt.Errorf("error opening journald close notification pipe")
   392  			} else {
   393  				cursor = s.followJournal(logWatcher, config, j, pipes, cursor)
   394  				// Let followJournal handle freeing the journal context
   395  				// object and closing the channel.
   396  				following = true
   397  			}
   398  		}
   399  	}
   400  
   401  	C.free(unsafe.Pointer(cursor))
   402  	return
   403  }
   404  
   405  func (s *journald) ReadLogs(config logger.ReadConfig) *logger.LogWatcher {
   406  	logWatcher := logger.NewLogWatcher()
   407  	go s.readLogs(logWatcher, config)
   408  	return logWatcher
   409  }