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