| 1 |
package testutils |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"fmt" |
| 6 |
"io" |
| 7 |
"os" |
| 8 |
"path/filepath" |
| 9 |
"regexp" |
| 10 |
"sort" |
| 11 |
"time" |
| 12 |
|
| 13 |
"github.com/juju/errors" |
| 14 |
) |
| 15 |
|
| 16 |
type TestCaseLogfiles struct { |
| 17 |
Kind LogfilesKind `yaml:"kind"` |
| 18 |
|
| 19 |
// Dir is only relevant for LogfilesKindAllFromDir |
| 20 |
Dir string `yaml:"dir"` |
| 21 |
|
| 22 |
// JournalctlDataFile is only relevant for LogfilesKindJournalctl |
| 23 |
JournalctlDataFile string `yaml:"journalctl_data_file"` |
| 24 |
} |
| 25 |
|
| 26 |
type LogfilesKind string |
| 27 |
|
| 28 |
const ( |
| 29 |
LogfilesKindAllFromDir LogfilesKind = "all_from_dir" |
| 30 |
LogfilesKindJournalctl LogfilesKind = "journalctl" |
| 31 |
) |
| 32 |
|
| 33 |
var AllLogfilesKinds = map[LogfilesKind]struct{}{ |
| 34 |
LogfilesKindAllFromDir: {}, |
| 35 |
LogfilesKindJournalctl: {}, |
| 36 |
} |
| 37 |
|
| 38 |
type ResolvedLogFiles struct { |
| 39 |
// If files is not empty, we need to use these files. |
| 40 |
Files []string |
| 41 |
|
| 42 |
// If journalctlDataFile is not empty, we need to use that file |
| 43 |
// as the data for mocked journalctl. |
| 44 |
JournalctlDataFile string |
| 45 |
} |
| 46 |
|
| 47 |
func ResolveLogfiles( |
| 48 |
testCaseDir string, logfilesDescr *TestCaseLogfiles, |
| 49 |
) (*ResolvedLogFiles, error) { |
| 50 |
switch logfilesDescr.Kind { |
| 51 |
case LogfilesKindAllFromDir: |
| 52 |
logfilesDir := filepath.Join(testCaseDir, logfilesDescr.Dir) |
| 53 |
|
| 54 |
entries, err := os.ReadDir(logfilesDir) |
| 55 |
if err != nil { |
| 56 |
return nil, errors.Annotatef(err, "reading logfiles dir %q", logfilesDir) |
| 57 |
} |
| 58 |
|
| 59 |
var files []string |
| 60 |
for _, entry := range entries { |
| 61 |
if entry.IsDir() { |
| 62 |
return nil, errors.Errorf("a dir %q in the logfiles dir %q", entry.Name(), logfilesDir) |
| 63 |
} |
| 64 |
|
| 65 |
files = append(files, filepath.Join(logfilesDir, entry.Name())) |
| 66 |
} |
| 67 |
|
| 68 |
sort.Strings(files) |
| 69 |
|
| 70 |
return &ResolvedLogFiles{ |
| 71 |
Files: files, |
| 72 |
}, nil |
| 73 |
|
| 74 |
case LogfilesKindJournalctl: |
| 75 |
if logfilesDescr.JournalctlDataFile == "" { |
| 76 |
return nil, errors.Errorf("kind is journalctl, but JournalctlDataFile is empty") |
| 77 |
} |
| 78 |
|
| 79 |
return &ResolvedLogFiles{ |
| 80 |
JournalctlDataFile: filepath.Join( |
| 81 |
testCaseDir, logfilesDescr.JournalctlDataFile, |
| 82 |
), |
| 83 |
}, nil |
| 84 |
|
| 85 |
default: |
| 86 |
return nil, errors.Errorf("invalid logfiles kind %q", logfilesDescr.Kind) |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
type ProvisionedLogFiles struct { |
| 91 |
LogfileLast, LogfilePrev string |
| 92 |
|
| 93 |
// extraEnv contains extra env vars in the format "VARIABLE=VALUE" |
| 94 |
ExtraEnv []string |
| 95 |
} |
| 96 |
|
| 97 |
func ProvisionLogFiles(resolved *ResolvedLogFiles, testOutputDir, repoRoot string) (*ProvisionedLogFiles, error) { |
| 98 |
var logfileLast, logfilePrev string |
| 99 |
|
| 100 |
// extraEnv contains extra env vars in the format "VARIABLE=VALUE" |
| 101 |
var extraEnv []string |
| 102 |
|
| 103 |
if len(resolved.Files) > 0 { |
| 104 |
logfiles := resolved.Files |
| 105 |
if len(logfiles) == 0 || len(logfiles) > 2 { |
| 106 |
return nil, errors.Errorf( |
| 107 |
"For now, there must be exactly 1 or 2 logfiles, but got %d: %v", |
| 108 |
len(logfiles), logfiles, |
| 109 |
) |
| 110 |
} |
| 111 |
|
| 112 |
logfileLast = filepath.Join(testOutputDir, "logfile") |
| 113 |
logfilePrev = filepath.Join(testOutputDir, "logfile.1") |
| 114 |
|
| 115 |
if err := CopyFile(logfiles[0], logfileLast); err != nil { |
| 116 |
return nil, errors.Annotatef(err, "copying logfile last: from %s to %s", logfiles[0], logfileLast) |
| 117 |
} |
| 118 |
|
| 119 |
if err := setSyslogFileModTime(logfileLast); err != nil { |
| 120 |
return nil, errors.Trace(err) |
| 121 |
} |
| 122 |
|
| 123 |
if len(logfiles) > 1 { |
| 124 |
if err := CopyFile(logfiles[1], logfilePrev); err != nil { |
| 125 |
return nil, errors.Annotatef(err, "copying logfile prev: from %s to %s", logfiles[1], logfilePrev) |
| 126 |
} |
| 127 |
|
| 128 |
if err := setSyslogFileModTime(logfilePrev); err != nil { |
| 129 |
return nil, errors.Trace(err) |
| 130 |
} |
| 131 |
} |
| 132 |
} else if resolved.JournalctlDataFile != "" { |
| 133 |
srcJournalctlMockDir := filepath.Join(repoRoot, "cmd", "journalctl_mock") |
| 134 |
srcJournalctlMockShFname := filepath.Join(srcJournalctlMockDir, "journalctl_mock.sh") |
| 135 |
srcJournalctlMockGoFname := filepath.Join(srcJournalctlMockDir, "journalctl_mock.go") |
| 136 |
srcJournalctlMockGoModFname := filepath.Join(srcJournalctlMockDir, "go.mod") |
| 137 |
srcJournalctlMockGoSumFname := filepath.Join(srcJournalctlMockDir, "go.sum") |
| 138 |
|
| 139 |
tgtJournalctlMockDir := filepath.Join(testOutputDir, "journalctl_mock") |
| 140 |
tgtJournalctlMockShFname := filepath.Join(tgtJournalctlMockDir, "journalctl_mock.sh") |
| 141 |
tgtJournalctlMockGoFname := filepath.Join(tgtJournalctlMockDir, "journalctl_mock.go") |
| 142 |
tgtJournalctlMockGoModFname := filepath.Join(tgtJournalctlMockDir, "go.mod") |
| 143 |
tgtJournalctlMockGoSumFname := filepath.Join(tgtJournalctlMockDir, "go.sum") |
| 144 |
|
| 145 |
if err := os.MkdirAll(tgtJournalctlMockDir, 0755); err != nil { |
| 146 |
return nil, errors.Errorf("unable to create journalctl_mock output dir %s: %s", tgtJournalctlMockDir, err.Error()) |
| 147 |
} |
| 148 |
|
| 149 |
if err := CopyFile(srcJournalctlMockShFname, tgtJournalctlMockShFname); err != nil { |
| 150 |
return nil, errors.Annotatef(err, "copying from %s to %s", srcJournalctlMockShFname, tgtJournalctlMockShFname) |
| 151 |
} |
| 152 |
if err := os.Chmod(tgtJournalctlMockShFname, 0755); err != nil { |
| 153 |
return nil, errors.Annotatef(err, "changing permissions for journalctl mock %s", tgtJournalctlMockShFname) |
| 154 |
} |
| 155 |
|
| 156 |
if err := CopyFile(srcJournalctlMockGoFname, tgtJournalctlMockGoFname); err != nil { |
| 157 |
return nil, errors.Annotatef(err, "copying from %s to %s", srcJournalctlMockGoFname, tgtJournalctlMockGoFname) |
| 158 |
} |
| 159 |
|
| 160 |
if err := CopyFile(srcJournalctlMockGoModFname, tgtJournalctlMockGoModFname); err != nil { |
| 161 |
return nil, errors.Annotatef(err, "copying from %s to %s", srcJournalctlMockGoModFname, tgtJournalctlMockGoModFname) |
| 162 |
} |
| 163 |
|
| 164 |
if err := CopyFile(srcJournalctlMockGoSumFname, tgtJournalctlMockGoSumFname); err != nil { |
| 165 |
return nil, errors.Annotatef(err, "copying from %s to %s", srcJournalctlMockGoSumFname, tgtJournalctlMockGoSumFname) |
| 166 |
} |
| 167 |
|
| 168 |
// Special case for the journalctl, no need to copy any files. |
| 169 |
logfileLast = "journalctl" |
| 170 |
logfilePrev = "journalctl" |
| 171 |
extraEnv = append( |
| 172 |
extraEnv, |
| 173 |
fmt.Sprintf("NERDLOG_JOURNALCTL_MOCK=%s", tgtJournalctlMockShFname), |
| 174 |
fmt.Sprintf("NERDLOG_JOURNALCTL_MOCK_DATA=%s", resolved.JournalctlDataFile), |
| 175 |
) |
| 176 |
} else { |
| 177 |
return nil, errors.Errorf( |
| 178 |
"For now, there must be exactly 1 or 2 logfiles, or journalctl data file, but got nothing", |
| 179 |
) |
| 180 |
} |
| 181 |
|
| 182 |
return &ProvisionedLogFiles{ |
| 183 |
LogfileLast: logfileLast, |
| 184 |
LogfilePrev: logfilePrev, |
| 185 |
ExtraEnv: extraEnv, |
| 186 |
}, nil |
| 187 |
} |
| 188 |
|
| 189 |
func CopyFile(srcPath, destPath string) error { |
| 190 |
// Open the source file |
| 191 |
srcFile, err := os.Open(srcPath) |
| 192 |
if err != nil { |
| 193 |
return errors.Annotatef(err, "opening source file") |
| 194 |
} |
| 195 |
defer srcFile.Close() |
| 196 |
|
| 197 |
// Create the destination file |
| 198 |
destFile, err := os.Create(destPath) |
| 199 |
if err != nil { |
| 200 |
return errors.Annotatef(err, "creating destination file") |
| 201 |
} |
| 202 |
defer destFile.Close() |
| 203 |
|
| 204 |
// Copy the contents of the source file to the destination file |
| 205 |
_, err = io.Copy(destFile, srcFile) |
| 206 |
if err != nil { |
| 207 |
return errors.Annotatef(err, "copying data") |
| 208 |
} |
| 209 |
|
| 210 |
// Ensure the destination file is written to disk |
| 211 |
err = destFile.Sync() |
| 212 |
if err != nil { |
| 213 |
return errors.Annotatef(err, "syncing destination file") |
| 214 |
} |
| 215 |
|
| 216 |
return nil |
| 217 |
} |
| 218 |
|
| 219 |
// setSyslogFileModTime takes the path to a syslog file, and sets its modification |
| 220 |
// time to the timestamp of the last log message from that file. |
| 221 |
func setSyslogFileModTime(fname string) error { |
| 222 |
lastLogTime, err := getLatestSyslogTimestamp(fname) |
| 223 |
if err != nil { |
| 224 |
return errors.Annotatef(err, "getting timestamp of the last log message in %s", fname) |
| 225 |
} |
| 226 |
|
| 227 |
if err := os.Chtimes(fname, lastLogTime, lastLogTime); err != nil { |
| 228 |
return errors.Annotatef(err, "setting mod time of %s", fname) |
| 229 |
} |
| 230 |
|
| 231 |
return nil |
| 232 |
} |
| 233 |
|
| 234 |
// Function to extract the latest timestamp from a syslog file |
| 235 |
func getLatestSyslogTimestamp(filePath string) (time.Time, error) { |
| 236 |
// Open the syslog file |
| 237 |
file, err := os.Open(filePath) |
| 238 |
if err != nil { |
| 239 |
return time.Time{}, err |
| 240 |
} |
| 241 |
defer file.Close() |
| 242 |
|
| 243 |
// Regular expression to match a typical syslog timestamp (e.g., "Apr 5 14:33:22") |
| 244 |
re := regexp.MustCompile(`^([A-Za-z]{3} \s?\d{1,2} \d{2}:\d{2}:\d{2})`) |
| 245 |
|
| 246 |
var latestTimestamp time.Time |
| 247 |
|
| 248 |
// Read the file backwards (find the last line) |
| 249 |
var lastLine string |
| 250 |
scanner := bufio.NewScanner(file) |
| 251 |
for scanner.Scan() { |
| 252 |
lastLine = scanner.Text() // Keep updating lastLine until the last line |
| 253 |
} |
| 254 |
|
| 255 |
if err := scanner.Err(); err != nil { |
| 256 |
return time.Time{}, err |
| 257 |
} |
| 258 |
|
| 259 |
// Extract the timestamp from the last line |
| 260 |
matches := re.FindStringSubmatch(lastLine) |
| 261 |
if len(matches) > 0 { |
| 262 |
timestampStr := matches[1] |
| 263 |
latestTimestamp, err = time.ParseInLocation("Jan 2 15:04:05", timestampStr, time.UTC) |
| 264 |
if err != nil { |
| 265 |
return time.Time{}, err |
| 266 |
} |
| 267 |
|
| 268 |
latestTimestamp = setYear(latestTimestamp, time.Now().Year()) |
| 269 |
} |
| 270 |
|
| 271 |
return latestTimestamp, nil |
| 272 |
} |
| 273 |
|
| 274 |
func setYear(t time.Time, year int) time.Time { |
| 275 |
// Return a new time.Time with the desired year |
| 276 |
return time.Date(year, t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), t.Location()) |
| 277 |
} |