github.com/containerd/nerdctl/v2@v2.0.0-beta.5.0.20240520001846-b5758f54fa28/pkg/logging/tail/tail.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 /* 18 Forked from https://github.com/kubernetes/kubernetes/blob/master/pkg/util/tail/tail.go 19 Copyright The Kubernetes Authors. 20 Licensed under the Apache License, Version 2.0 21 */ 22 23 package tail 24 25 import ( 26 "bytes" 27 "io" 28 ) 29 30 const ( 31 // blockSize is the block size used in tail. 32 blockSize = 1024 33 ) 34 35 var ( 36 // eol is the end-of-line sign in the log. 37 eol = []byte{'\n'} 38 ) 39 40 // FindTailLineStartIndex returns the start of last nth line. 41 // * If n <= 0, return the beginning of the file. 42 // * If n > 0, return the beginning of last nth line. 43 // Notice that if the last line is incomplete (no end-of-line), it will not be counted 44 // as one line. 45 func FindTailLineStartIndex(f io.ReadSeeker, n uint) (int64, error) { 46 if n <= 0 { 47 return 0, nil 48 } 49 size, err := f.Seek(0, io.SeekEnd) 50 if err != nil { 51 return 0, err 52 } 53 var left, cnt int64 54 buf := make([]byte, blockSize) 55 for right := size; right > 0 && uint(cnt) <= n; right -= blockSize { 56 left = right - blockSize 57 if left < 0 { 58 left = 0 59 buf = make([]byte, right) 60 } 61 if _, err := f.Seek(left, io.SeekStart); err != nil { 62 return 0, err 63 } 64 if _, err := f.Read(buf); err != nil { 65 return 0, err 66 } 67 cnt += int64(bytes.Count(buf, eol)) 68 } 69 for ; uint(cnt) > n; cnt-- { 70 idx := bytes.Index(buf, eol) + 1 71 buf = buf[idx:] 72 left += int64(idx) 73 } 74 return left, nil 75 }