github.com/coreos/rocket@v1.30.1-0.20200224141603-171c416fac02/rkt/api_service_sdjournal.go (about)

     1  // Copyright 2016 The rkt Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // +build sdjournal
    16  
    17  package main
    18  
    19  import (
    20  	"fmt"
    21  	"io/ioutil"
    22  	"os"
    23  	"time"
    24  
    25  	"github.com/coreos/go-systemd/sdjournal"
    26  	"github.com/rkt/rkt/api/v1alpha"
    27  	"github.com/rkt/rkt/common"
    28  	pkgPod "github.com/rkt/rkt/pkg/pod"
    29  )
    30  
    31  func (s *v1AlphaAPIServer) constrainedGetLogs(request *v1alpha.GetLogsRequest, server v1alpha.PublicAPI_GetLogsServer) error {
    32  	pod, err := pkgPod.PodFromUUIDString(getDataDir(), request.PodId)
    33  	if err != nil {
    34  		return err
    35  	}
    36  	defer pod.Close()
    37  
    38  	path, err := pod.JournalLogPath()
    39  	if _, err := os.Stat(path); os.IsNotExist(err) {
    40  		return fmt.Errorf("logging unsupported for pod %q", request.PodId)
    41  	}
    42  
    43  	jconf := sdjournal.JournalReaderConfig{
    44  		Path: path,
    45  	}
    46  	if request.AppName != "" {
    47  		jconf.Matches = []sdjournal.Match{
    48  			{
    49  				Field: sdjournal.SD_JOURNAL_FIELD_SYSLOG_IDENTIFIER,
    50  				Value: request.AppName,
    51  			},
    52  		}
    53  	}
    54  	if request.SinceTime != 0 {
    55  		t := time.Unix(request.SinceTime, 0)
    56  		jconf.Since = -time.Since(t)
    57  	}
    58  	if request.Lines != 0 {
    59  		jconf.NumFromTail = uint64(request.Lines)
    60  	}
    61  
    62  	jr, err := sdjournal.NewJournalReader(jconf)
    63  	if err != nil {
    64  		return err
    65  	}
    66  	defer jr.Close()
    67  
    68  	if request.Follow {
    69  		return jr.Follow(nil, LogsStreamWriter{server: server})
    70  	}
    71  
    72  	data, err := ioutil.ReadAll(jr)
    73  	if err != nil {
    74  		return err
    75  	}
    76  
    77  	return server.Send(&v1alpha.GetLogsResponse{Lines: common.RemoveEmptyLines(string(data))})
    78  }