|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +import Foundation |
| 14 | +import RegexBuilder |
| 15 | + |
| 16 | +#if os(Windows) |
| 17 | +import WinSDK |
| 18 | +#endif |
| 19 | + |
| 20 | +#if !canImport(os) || SOURCEKITLSP_FORCE_NON_DARWIN_LOGGER |
| 21 | +fileprivate struct FailedToCreateFileError: Error, CustomStringConvertible { |
| 22 | + let logFile: URL |
| 23 | + |
| 24 | + var description: String { |
| 25 | + return "Failed to create log file at \(logFile)" |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +/// The number of log file handles that have been created by this process. |
| 30 | +/// |
| 31 | +/// See comment on `logFileHandle`. |
| 32 | +@LogHandlerActor |
| 33 | +fileprivate var logRotateIndex = 0 |
| 34 | + |
| 35 | +/// The file handle to the current log file. When the file managed by this handle reaches its maximum size, we increment |
| 36 | +/// the `logRotateIndex` by 1 and set the `logFileHandle` to `nil`. This causes a new log file handle with index |
| 37 | +/// `logRotateIndex % logRotateCount` to be created on the next log call. |
| 38 | +@LogHandlerActor |
| 39 | +fileprivate var logFileHandle: FileHandle? |
| 40 | + |
| 41 | +@LogHandlerActor |
| 42 | +func getOrCreateLogFileHandle(logDirectory: URL, logRotateCount: Int) -> FileHandle { |
| 43 | + if let logFileHandle { |
| 44 | + return logFileHandle |
| 45 | + } |
| 46 | + |
| 47 | + // Name must match the regex in `cleanOldLogFiles` and the prefix in `DiagnoseCommand.addNonDarwinLogs`. |
| 48 | + let logFileUrl = logDirectory.appendingPathComponent( |
| 49 | + "sourcekit-lsp-\(ProcessInfo.processInfo.processIdentifier).\(logRotateIndex % logRotateCount).log" |
| 50 | + ) |
| 51 | + |
| 52 | + do { |
| 53 | + try FileManager.default.createDirectory(at: logDirectory, withIntermediateDirectories: true) |
| 54 | + if !FileManager.default.fileExists(atPath: logFileUrl.path) { |
| 55 | + guard FileManager.default.createFile(atPath: logFileUrl.path, contents: nil) else { |
| 56 | + throw FailedToCreateFileError(logFile: logFileUrl) |
| 57 | + } |
| 58 | + } |
| 59 | + let newFileHandle = try FileHandle(forWritingTo: logFileUrl) |
| 60 | + logFileHandle = newFileHandle |
| 61 | + try newFileHandle.truncate(atOffset: 0) |
| 62 | + return newFileHandle |
| 63 | + } catch { |
| 64 | + // If we fail to create a file handle for the log file, log one message about it to stderr and then log to stderr. |
| 65 | + // We will try creating a log file again once this section of the log reaches `maxLogFileSize` but that means that |
| 66 | + // we'll only log this error every `maxLogFileSize` bytes, which is a lot less spammy than logging it on every log |
| 67 | + // call. |
| 68 | + fputs("Failed to open file handle for log file at \(logFileUrl.path): \(error)", stderr) |
| 69 | + logFileHandle = FileHandle.standardError |
| 70 | + return FileHandle.standardError |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +/// Log the given message to a log file in the given log directory. |
| 75 | +/// |
| 76 | +/// The name of the log file includes the PID of the current process to make sure it is exclusively writing to the file. |
| 77 | +/// When a log file reaches `logFileMaxBytes`, it will be rotated, with at most `logRotateCount` different log files |
| 78 | +/// being created. |
| 79 | +@LogHandlerActor |
| 80 | +private func logToFile(message: String, logDirectory: URL, logFileMaxBytes: Int, logRotateCount: Int) throws { |
| 81 | + |
| 82 | + guard let data = message.data(using: .utf8) else { |
| 83 | + fputs( |
| 84 | + """ |
| 85 | + Failed to convert log message to UTF-8 data |
| 86 | + \(message) |
| 87 | +
|
| 88 | + """, |
| 89 | + stderr |
| 90 | + ) |
| 91 | + return |
| 92 | + } |
| 93 | + let logFileHandleUnwrapped = getOrCreateLogFileHandle(logDirectory: logDirectory, logRotateCount: logRotateCount) |
| 94 | + try logFileHandleUnwrapped.write(contentsOf: data) |
| 95 | + |
| 96 | + // If this log file has exceeded the maximum size, start writing to a new log file. |
| 97 | + if try logFileHandleUnwrapped.offset() > logFileMaxBytes { |
| 98 | + logRotateIndex += 1 |
| 99 | + // Resetting `logFileHandle` will cause a new logFileHandle to be created on the next log call. |
| 100 | + logFileHandle = nil |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +/// If the file at the given path is writable, redirect log messages handled by `NonDarwinLogHandler` to the given file. |
| 105 | +/// |
| 106 | +/// Occasionally checks that the log does not exceed `targetLogSize` (in bytes) and truncates the beginning of the log |
| 107 | +/// when it does. |
| 108 | +@LogHandlerActor |
| 109 | +private func setUpGlobalLogFileHandlerImpl(logFileDirectory: URL, logFileMaxBytes: Int, logRotateCount: Int) { |
| 110 | + logHandler = { @LogHandlerActor message in |
| 111 | + do { |
| 112 | + try logToFile( |
| 113 | + message: message, |
| 114 | + logDirectory: logFileDirectory, |
| 115 | + logFileMaxBytes: logFileMaxBytes, |
| 116 | + logRotateCount: logRotateCount |
| 117 | + ) |
| 118 | + } catch { |
| 119 | + fputs( |
| 120 | + """ |
| 121 | + Failed to write message to log file: \(error) |
| 122 | + \(message) |
| 123 | +
|
| 124 | + """, |
| 125 | + stderr |
| 126 | + ) |
| 127 | + } |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +/// Returns `true` if a process with the given PID still exists and is alive. |
| 132 | +private func isProcessAlive(pid: Int32) -> Bool { |
| 133 | + #if os(Windows) |
| 134 | + if let handle = OpenProcess(UInt32(PROCESS_QUERY_INFORMATION), /*bInheritHandle=*/ false, UInt32(pid)) { |
| 135 | + CloseHandle(handle) |
| 136 | + return true |
| 137 | + } |
| 138 | + return false |
| 139 | + #else |
| 140 | + return kill(pid, 0) == 0 |
| 141 | + #endif |
| 142 | +} |
| 143 | + |
| 144 | +private func cleanOldLogFilesImpl(logFileDirectory: URL, maxAge: TimeInterval) { |
| 145 | + let enumerator = FileManager.default.enumerator(at: logFileDirectory, includingPropertiesForKeys: nil) |
| 146 | + while let url = enumerator?.nextObject() as? URL { |
| 147 | + let name = url.lastPathComponent |
| 148 | + let regex = Regex { |
| 149 | + "sourcekit-lsp-" |
| 150 | + Capture(ZeroOrMore(.digit)) |
| 151 | + "." |
| 152 | + ZeroOrMore(.digit) |
| 153 | + ".log" |
| 154 | + } |
| 155 | + guard let match = name.matches(of: regex).only, let pid = Int32(match.1) else { |
| 156 | + continue |
| 157 | + } |
| 158 | + if isProcessAlive(pid: pid) { |
| 159 | + // Process that owns this log file is still alive. Don't delete it. |
| 160 | + continue |
| 161 | + } |
| 162 | + guard |
| 163 | + let modificationDate = orLog( |
| 164 | + "Getting mtime of old log file", |
| 165 | + { try FileManager.default.attributesOfItem(atPath: url.path)[.modificationDate] } |
| 166 | + ) as? Date, |
| 167 | + Date().timeIntervalSince(modificationDate) > maxAge |
| 168 | + else { |
| 169 | + // File has been modified in the last hour. Don't delete it because it's useful to diagnose issues after |
| 170 | + // sourcekit-lsp has exited. |
| 171 | + continue |
| 172 | + } |
| 173 | + orLog("Deleting old log file") { try FileManager.default.removeItem(at: url) } |
| 174 | + } |
| 175 | +} |
| 176 | +#endif |
| 177 | + |
| 178 | +/// If the file at the given path is writable, redirect log messages handled by `NonDarwinLogHandler` to the given file. |
| 179 | +/// |
| 180 | +/// Occasionally checks that the log does not exceed `targetLogSize` (in bytes) and truncates the beginning of the log |
| 181 | +/// when it does. |
| 182 | +/// |
| 183 | +/// No-op when using OSLog. |
| 184 | +public func setUpGlobalLogFileHandler(logFileDirectory: URL, logFileMaxBytes: Int, logRotateCount: Int) async { |
| 185 | + #if !canImport(os) || SOURCEKITLSP_FORCE_NON_DARWIN_LOGGER |
| 186 | + await setUpGlobalLogFileHandlerImpl( |
| 187 | + logFileDirectory: logFileDirectory, |
| 188 | + logFileMaxBytes: logFileMaxBytes, |
| 189 | + logRotateCount: logRotateCount |
| 190 | + ) |
| 191 | + #endif |
| 192 | +} |
| 193 | + |
| 194 | +/// Deletes all sourcekit-lsp log files in `logFilesDirectory` that are not associated with a running process and that |
| 195 | +/// haven't been modified within the last hour. |
| 196 | +/// |
| 197 | +/// No-op when using OSLog. |
| 198 | +public func cleanOldLogFiles(logFileDirectory: URL, maxAge: TimeInterval) { |
| 199 | + #if !canImport(os) || SOURCEKITLSP_FORCE_NON_DARWIN_LOGGER |
| 200 | + cleanOldLogFilesImpl(logFileDirectory: logFileDirectory, maxAge: maxAge) |
| 201 | + #endif |
| 202 | +} |
0 commit comments