ServerStats.swift 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  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. import Dispatch
  17. import NIOCore
  18. import NIOFileSystem
  19. #if canImport(Darwin)
  20. import Darwin
  21. #elseif canImport(Musl)
  22. import Musl
  23. #elseif canImport(Glibc)
  24. import Glibc
  25. #else
  26. let badOS = { fatalError("unsupported OS") }()
  27. #endif
  28. #if canImport(Darwin)
  29. private let OUR_RUSAGE_SELF: Int32 = RUSAGE_SELF
  30. #elseif canImport(Musl) || canImport(Glibc)
  31. private let OUR_RUSAGE_SELF: Int32 = RUSAGE_SELF.rawValue
  32. #endif
  33. /// Current server stats.
  34. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
  35. internal struct ServerStats: Sendable {
  36. var time: Double
  37. var userTime: Double
  38. var systemTime: Double
  39. var totalCPUTime: UInt64
  40. var idleCPUTime: UInt64
  41. init(
  42. time: Double,
  43. userTime: Double,
  44. systemTime: Double,
  45. totalCPUTime: UInt64,
  46. idleCPUTime: UInt64
  47. ) {
  48. self.time = time
  49. self.userTime = userTime
  50. self.systemTime = systemTime
  51. self.totalCPUTime = totalCPUTime
  52. self.idleCPUTime = idleCPUTime
  53. }
  54. init() async throws {
  55. self.time = Double(DispatchTime.now().uptimeNanoseconds) * 1e-9
  56. var usage = rusage()
  57. if getrusage(OUR_RUSAGE_SELF, &usage) == 0 {
  58. // Adding the seconds with the microseconds transformed into seconds to get the
  59. // real number of seconds as a `Double`.
  60. self.userTime = Double(usage.ru_utime.tv_sec) + Double(usage.ru_utime.tv_usec) * 1e-6
  61. self.systemTime = Double(usage.ru_stime.tv_sec) + Double(usage.ru_stime.tv_usec) * 1e-6
  62. } else {
  63. self.userTime = 0
  64. self.systemTime = 0
  65. }
  66. let (totalCPUTime, idleCPUTime) = try await ServerStats.getTotalAndIdleCPUTime()
  67. self.totalCPUTime = totalCPUTime
  68. self.idleCPUTime = idleCPUTime
  69. }
  70. internal func difference(to stats: ServerStats) -> ServerStats {
  71. return ServerStats(
  72. time: self.time - stats.time,
  73. userTime: self.userTime - stats.userTime,
  74. systemTime: self.systemTime - stats.systemTime,
  75. totalCPUTime: self.totalCPUTime - stats.totalCPUTime,
  76. idleCPUTime: self.idleCPUTime - stats.idleCPUTime
  77. )
  78. }
  79. /// Computes the total and idle CPU time after extracting stats from the first line of '/proc/stat'.
  80. ///
  81. /// The first line in '/proc/stat' file looks as follows:
  82. /// CPU [user] [nice] [system] [idle] [iowait] [irq] [softirq]
  83. /// The totalCPUTime is computed as follows:
  84. /// total = user + nice + system + idle
  85. private static func getTotalAndIdleCPUTime() async throws -> (
  86. totalCPUTime: UInt64, idleCPUTime: UInt64
  87. ) {
  88. #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Linux) || os(Android)
  89. let contents: ByteBuffer
  90. do {
  91. contents = try await ByteBuffer(
  92. contentsOf: "/proc/stat",
  93. maximumSizeAllowed: .kilobytes(20)
  94. )
  95. } catch {
  96. return (0, 0)
  97. }
  98. let view = contents.readableBytesView
  99. guard let firstNewLineIndex = view.firstIndex(of: UInt8(ascii: "\n")) else {
  100. return (0, 0)
  101. }
  102. let firstLine = String(buffer: ByteBuffer(view[0 ... firstNewLineIndex]))
  103. let lineComponents = firstLine.components(separatedBy: " ")
  104. if lineComponents.count < 5 || lineComponents[0] != "CPU" {
  105. return (0, 0)
  106. }
  107. let CPUTime: [UInt64] = lineComponents[1 ... 4].compactMap { UInt64($0) }
  108. if CPUTime.count < 4 {
  109. return (0, 0)
  110. }
  111. let totalCPUTime = CPUTime.reduce(0, +)
  112. return (totalCPUTime, CPUTime[3])
  113. #else
  114. return (0, 0)
  115. #endif
  116. }
  117. }