File: SetGlobalLogFileHandler.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (202 lines) | stat: -rw-r--r-- 7,360 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import Foundation
import RegexBuilder

#if os(Windows)
import WinSDK
#endif

#if !canImport(os) || SOURCEKITLSP_FORCE_NON_DARWIN_LOGGER
fileprivate struct FailedToCreateFileError: Error, CustomStringConvertible {
  let logFile: URL

  var description: String {
    return "Failed to create log file at \(logFile)"
  }
}

/// The number of log file handles that have been created by this process.
///
/// See comment on `logFileHandle`.
@LogHandlerActor
fileprivate var logRotateIndex = 0

/// The file handle to the current log file. When the file managed by this handle reaches its maximum size, we increment
/// the `logRotateIndex` by 1 and set the `logFileHandle` to `nil`. This causes a new log file handle with index
/// `logRotateIndex % logRotateCount` to be created on the next log call.
@LogHandlerActor
fileprivate var logFileHandle: FileHandle?

@LogHandlerActor
func getOrCreateLogFileHandle(logDirectory: URL, logRotateCount: Int) -> FileHandle {
  if let logFileHandle {
    return logFileHandle
  }

  // Name must match the regex in `cleanOldLogFiles` and the prefix in `DiagnoseCommand.addNonDarwinLogs`.
  let logFileUrl = logDirectory.appendingPathComponent(
    "sourcekit-lsp-\(ProcessInfo.processInfo.processIdentifier).\(logRotateIndex % logRotateCount).log"
  )

  do {
    try FileManager.default.createDirectory(at: logDirectory, withIntermediateDirectories: true)
    if !FileManager.default.fileExists(atPath: logFileUrl.path) {
      guard FileManager.default.createFile(atPath: logFileUrl.path, contents: nil) else {
        throw FailedToCreateFileError(logFile: logFileUrl)
      }
    }
    let newFileHandle = try FileHandle(forWritingTo: logFileUrl)
    logFileHandle = newFileHandle
    try newFileHandle.truncate(atOffset: 0)
    return newFileHandle
  } catch {
    // If we fail to create a file handle for the log file, log one message about it to stderr and then log to stderr.
    // We will try creating a log file again once this section of the log reaches `maxLogFileSize` but that means that
    // we'll only log this error every `maxLogFileSize` bytes, which is a lot less spammy than logging it on every log
    // call.
    fputs("Failed to open file handle for log file at \(logFileUrl.path): \(error)", stderr)
    logFileHandle = FileHandle.standardError
    return FileHandle.standardError
  }
}

/// Log the given message to a log file in the given log directory.
///
/// The name of the log file includes the PID of the current process to make sure it is exclusively writing to the file.
/// When a log file reaches `logFileMaxBytes`, it will be rotated, with at most `logRotateCount` different log files
/// being created.
@LogHandlerActor
private func logToFile(message: String, logDirectory: URL, logFileMaxBytes: Int, logRotateCount: Int) throws {

  guard let data = message.data(using: .utf8) else {
    fputs(
      """
      Failed to convert log message to UTF-8 data
      \(message)

      """,
      stderr
    )
    return
  }
  let logFileHandleUnwrapped = getOrCreateLogFileHandle(logDirectory: logDirectory, logRotateCount: logRotateCount)
  try logFileHandleUnwrapped.write(contentsOf: data)

  // If this log file has exceeded the maximum size, start writing to a new log file.
  if try logFileHandleUnwrapped.offset() > logFileMaxBytes {
    logRotateIndex += 1
    // Resetting `logFileHandle` will cause a new logFileHandle to be created on the next log call.
    logFileHandle = nil
  }
}

/// If the file at the given path is writable, redirect log messages handled by `NonDarwinLogHandler` to the given file.
///
/// Occasionally checks that the log does not exceed `targetLogSize` (in bytes) and truncates the beginning of the log
/// when it does.
@LogHandlerActor
private func setUpGlobalLogFileHandlerImpl(logFileDirectory: URL, logFileMaxBytes: Int, logRotateCount: Int) {
  logHandler = { @LogHandlerActor message in
    do {
      try logToFile(
        message: message,
        logDirectory: logFileDirectory,
        logFileMaxBytes: logFileMaxBytes,
        logRotateCount: logRotateCount
      )
    } catch {
      fputs(
        """
        Failed to write message to log file: \(error)
        \(message)

        """,
        stderr
      )
    }
  }
}

/// Returns `true` if a process with the given PID still exists and is alive.
private func isProcessAlive(pid: Int32) -> Bool {
  #if os(Windows)
  if let handle = OpenProcess(UInt32(PROCESS_QUERY_INFORMATION), /*bInheritHandle=*/ false, UInt32(pid)) {
    CloseHandle(handle)
    return true
  }
  return false
  #else
  return kill(pid, 0) == 0
  #endif
}

private func cleanOldLogFilesImpl(logFileDirectory: URL, maxAge: TimeInterval) {
  let enumerator = FileManager.default.enumerator(at: logFileDirectory, includingPropertiesForKeys: nil)
  while let url = enumerator?.nextObject() as? URL {
    let name = url.lastPathComponent
    let regex = Regex {
      "sourcekit-lsp-"
      Capture(ZeroOrMore(.digit))
      "."
      ZeroOrMore(.digit)
      ".log"
    }
    guard let match = name.matches(of: regex).only, let pid = Int32(match.1) else {
      continue
    }
    if isProcessAlive(pid: pid) {
      // Process that owns this log file is still alive. Don't delete it.
      continue
    }
    guard
      let modificationDate = orLog(
        "Getting mtime of old log file",
        { try FileManager.default.attributesOfItem(atPath: url.path)[.modificationDate] }
      ) as? Date,
      Date().timeIntervalSince(modificationDate) > maxAge
    else {
      // File has been modified in the last hour. Don't delete it because it's useful to diagnose issues after
      // sourcekit-lsp has exited.
      continue
    }
    orLog("Deleting old log file") { try FileManager.default.removeItem(at: url) }
  }
}
#endif

/// If the file at the given path is writable, redirect log messages handled by `NonDarwinLogHandler` to the given file.
///
/// Occasionally checks that the log does not exceed `targetLogSize` (in bytes) and truncates the beginning of the log
/// when it does.
///
/// No-op when using OSLog.
public func setUpGlobalLogFileHandler(logFileDirectory: URL, logFileMaxBytes: Int, logRotateCount: Int) async {
  #if !canImport(os) || SOURCEKITLSP_FORCE_NON_DARWIN_LOGGER
  await setUpGlobalLogFileHandlerImpl(
    logFileDirectory: logFileDirectory,
    logFileMaxBytes: logFileMaxBytes,
    logRotateCount: logRotateCount
  )
  #endif
}

/// Deletes all sourcekit-lsp log files in `logFilesDirectory` that are not associated with a running process and that
/// haven't been modified within the last hour.
///
/// No-op when using OSLog.
public func cleanOldLogFiles(logFileDirectory: URL, maxAge: TimeInterval) {
  #if !canImport(os) || SOURCEKITLSP_FORCE_NON_DARWIN_LOGGER
  cleanOldLogFilesImpl(logFileDirectory: logFileDirectory, maxAge: maxAge)
  #endif
}