main.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. /*
  2. * Copyright 2019, 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 Foundation
  17. import GRPC
  18. import NIO
  19. import NIOSSL
  20. import Commander
  21. import EchoImplementation
  22. import EchoModel
  23. struct ConnectionFactory {
  24. var configuration: ClientConnection.Configuration
  25. func makeConnection() -> ClientConnection {
  26. return ClientConnection(configuration: self.configuration)
  27. }
  28. func makeEchoClient() -> Echo_EchoServiceClient {
  29. return Echo_EchoServiceClient(connection: self.makeConnection())
  30. }
  31. }
  32. protocol Benchmark: class {
  33. func setUp() throws
  34. func tearDown() throws
  35. func run() throws
  36. }
  37. /// Tests unary throughput by sending requests on a single connection.
  38. ///
  39. /// Requests are sent in batches of (up-to) 100 requests. This is due to
  40. /// https://github.com/apple/swift-nio-http2/issues/87#issuecomment-483542401.
  41. class UnaryThroughput: Benchmark {
  42. let factory: ConnectionFactory
  43. let requests: Int
  44. let requestLength: Int
  45. var client: Echo_EchoServiceClient!
  46. var request: String!
  47. init(factory: ConnectionFactory, requests: Int, requestLength: Int) {
  48. self.factory = factory
  49. self.requests = requests
  50. self.requestLength = requestLength
  51. }
  52. func setUp() throws {
  53. self.client = self.factory.makeEchoClient()
  54. self.request = String(repeating: "0", count: self.requestLength)
  55. }
  56. func run() throws {
  57. let batchSize = 100
  58. for lowerBound in stride(from: 0, to: self.requests, by: batchSize) {
  59. let upperBound = min(lowerBound + batchSize, self.requests)
  60. let requests = (lowerBound..<upperBound).map { _ in
  61. client.get(Echo_EchoRequest.with { $0.text = self.request }).response
  62. }
  63. try EventLoopFuture.andAllSucceed(requests, on: self.client.connection.eventLoop).wait()
  64. }
  65. }
  66. func tearDown() throws {
  67. try self.client.connection.close().wait()
  68. }
  69. }
  70. /// Tests bidirectional throughput by sending requests over a single stream.
  71. ///
  72. /// Requests are sent in batches of (up-to) 100 requests. This is due to
  73. /// https://github.com/apple/swift-nio-http2/issues/87#issuecomment-483542401.
  74. class BidirectionalThroughput: UnaryThroughput {
  75. override func run() throws {
  76. let update = self.client.update { _ in }
  77. for _ in 0..<self.requests {
  78. update.sendMessage(Echo_EchoRequest.with { $0.text = self.request }, promise: nil)
  79. }
  80. update.sendEnd(promise: nil)
  81. _ = try update.status.wait()
  82. }
  83. }
  84. /// Tests the number of connections that can be created.
  85. final class ConnectionCreationThroughput: Benchmark {
  86. let factory: ConnectionFactory
  87. let connections: Int
  88. var createdConnections: [ClientConnection] = []
  89. class ConnectionReadinessDelegate: ConnectivityStateDelegate {
  90. let promise: EventLoopPromise<Void>
  91. var ready: EventLoopFuture<Void> {
  92. return promise.futureResult
  93. }
  94. init(promise: EventLoopPromise<Void>) {
  95. self.promise = promise
  96. }
  97. func connectivityStateDidChange(from oldState: ConnectivityState, to newState: ConnectivityState) {
  98. switch newState {
  99. case .ready:
  100. promise.succeed(())
  101. case .shutdown:
  102. promise.fail(GRPCStatus(code: .unavailable, message: nil))
  103. default:
  104. break
  105. }
  106. }
  107. }
  108. init(factory: ConnectionFactory, connections: Int) {
  109. self.factory = factory
  110. self.connections = connections
  111. }
  112. func setUp() throws { }
  113. func run() throws {
  114. let connectionsAndDelegates: [(ClientConnection, ConnectionReadinessDelegate)] = (0..<connections).map { _ in
  115. let promise = self.factory.configuration.eventLoopGroup.next().makePromise(of: Void.self)
  116. var configuration = self.factory.configuration
  117. let delegate = ConnectionReadinessDelegate(promise: promise)
  118. configuration.connectivityStateDelegate = delegate
  119. return (ClientConnection(configuration: configuration), delegate)
  120. }
  121. self.createdConnections = connectionsAndDelegates.map { connection, _ in connection }
  122. let futures = connectionsAndDelegates.map { _, delegate in delegate.ready }
  123. try EventLoopFuture.andAllSucceed(
  124. futures,
  125. on: self.factory.configuration.eventLoopGroup.next()
  126. ).wait()
  127. }
  128. func tearDown() throws {
  129. let connectionClosures = self.createdConnections.map {
  130. $0.close()
  131. }
  132. try EventLoopFuture.andAllSucceed(
  133. connectionClosures,
  134. on: self.factory.configuration.eventLoopGroup.next()).wait()
  135. }
  136. }
  137. /// The results of a benchmark.
  138. struct BenchmarkResults {
  139. let benchmarkDescription: String
  140. let durations: [TimeInterval]
  141. /// Returns the results as a comma separated string.
  142. ///
  143. /// The format of the string is as such:
  144. /// <name>, <number of results> [, <duration>]
  145. var asCSV: String {
  146. let items = [self.benchmarkDescription, String(self.durations.count)] + self.durations.map { String($0) }
  147. return items.joined(separator: ", ")
  148. }
  149. }
  150. /// Runs the given benchmark multiple times, recording the wall time for each iteration.
  151. ///
  152. /// - Parameter description: A description of the benchmark.
  153. /// - Parameter benchmark: The benchmark to run.
  154. /// - Parameter repeats: The number of times to run the benchmark.
  155. func measure(description: String, benchmark: Benchmark, repeats: Int) -> BenchmarkResults {
  156. var durations: [TimeInterval] = []
  157. for _ in 0..<repeats {
  158. do {
  159. try benchmark.setUp()
  160. let start = Date()
  161. try benchmark.run()
  162. let end = Date()
  163. durations.append(end.timeIntervalSince(start))
  164. } catch {
  165. // If tearDown fails now then there's not a lot we can do!
  166. try? benchmark.tearDown()
  167. return BenchmarkResults(benchmarkDescription: description, durations: [])
  168. }
  169. do {
  170. try benchmark.tearDown()
  171. } catch {
  172. return BenchmarkResults(benchmarkDescription: description, durations: [])
  173. }
  174. }
  175. return BenchmarkResults(benchmarkDescription: description, durations: durations)
  176. }
  177. /// Makes an SSL context if one is required. Note that the CLI tool doesn't support optional values,
  178. /// so we use empty strings for the paths if we don't require SSL.
  179. ///
  180. /// This function will terminate the program if it is not possible to create an SSL context.
  181. ///
  182. /// - Parameter caCertificatePath: The path to the CA certificate PEM file.
  183. /// - Parameter certificatePath: The path to the certificate.
  184. /// - Parameter privateKeyPath: The path to the private key.
  185. /// - Parameter server: Whether this is for the server or not.
  186. private func makeServerTLSConfiguration(caCertificatePath: String, certificatePath: String, privateKeyPath: String) throws -> Server.Configuration.TLS? {
  187. // Commander doesn't have Optional options; we use empty strings to indicate no value.
  188. guard certificatePath.isEmpty == privateKeyPath.isEmpty &&
  189. privateKeyPath.isEmpty == caCertificatePath.isEmpty else {
  190. print("Paths for CA certificate, certificate and private key must be provided")
  191. exit(1)
  192. }
  193. // No need to check them all because of the guard statement above.
  194. if caCertificatePath.isEmpty {
  195. return nil
  196. }
  197. return .init(
  198. certificateChain: try NIOSSLCertificate.fromPEMFile(certificatePath).map { .certificate($0) },
  199. privateKey: .file(privateKeyPath),
  200. trustRoots: .file(caCertificatePath)
  201. )
  202. }
  203. private func makeClientTLSConfiguration(
  204. caCertificatePath: String,
  205. certificatePath: String,
  206. privateKeyPath: String
  207. ) throws -> ClientConnection.Configuration.TLS? {
  208. // Commander doesn't have Optional options; we use empty strings to indicate no value.
  209. guard certificatePath.isEmpty == privateKeyPath.isEmpty &&
  210. privateKeyPath.isEmpty == caCertificatePath.isEmpty else {
  211. print("Paths for CA certificate, certificate and private key must be provided")
  212. exit(1)
  213. }
  214. // No need to check them all because of the guard statement above.
  215. if caCertificatePath.isEmpty {
  216. return nil
  217. }
  218. return .init(
  219. certificateChain: try NIOSSLCertificate.fromPEMFile(certificatePath).map { .certificate($0) },
  220. privateKey: .file(privateKeyPath),
  221. trustRoots: .file(caCertificatePath)
  222. )
  223. }
  224. enum Benchmarks: String, CaseIterable {
  225. case unaryThroughputSmallRequests = "unary_throughput_small"
  226. case unaryThroughputLargeRequests = "unary_throughput_large"
  227. case bidirectionalThroughputSmallRequests = "bidi_throughput_small"
  228. case bidirectionalThroughputLargeRequests = "bidi_throughput_large"
  229. case connectionThroughput = "connection_throughput"
  230. static let smallRequest = 8
  231. static let largeRequest = 1 << 16
  232. var description: String {
  233. switch self {
  234. case .unaryThroughputSmallRequests:
  235. return "10k unary requests of size \(Benchmarks.smallRequest)"
  236. case .unaryThroughputLargeRequests:
  237. return "10k unary requests of size \(Benchmarks.largeRequest)"
  238. case .bidirectionalThroughputSmallRequests:
  239. return "20k bidirectional messages of size \(Benchmarks.smallRequest)"
  240. case .bidirectionalThroughputLargeRequests:
  241. return "10k bidirectional messages of size \(Benchmarks.largeRequest)"
  242. case .connectionThroughput:
  243. return "100 connections created"
  244. }
  245. }
  246. func makeBenchmark(factory: ConnectionFactory) -> Benchmark {
  247. switch self {
  248. case .unaryThroughputSmallRequests:
  249. return UnaryThroughput(factory: factory, requests: 10_000, requestLength: Benchmarks.smallRequest)
  250. case .unaryThroughputLargeRequests:
  251. return UnaryThroughput(factory: factory, requests: 10_000, requestLength: Benchmarks.largeRequest)
  252. case .bidirectionalThroughputSmallRequests:
  253. return BidirectionalThroughput(factory: factory, requests: 20_000, requestLength: Benchmarks.smallRequest)
  254. case .bidirectionalThroughputLargeRequests:
  255. return BidirectionalThroughput(factory: factory, requests: 10_000, requestLength: Benchmarks.largeRequest)
  256. case .connectionThroughput:
  257. return ConnectionCreationThroughput(factory: factory, connections: 100)
  258. }
  259. }
  260. func run(using factory: ConnectionFactory, repeats: Int = 10) -> BenchmarkResults {
  261. let benchmark = self.makeBenchmark(factory: factory)
  262. return measure(description: self.description, benchmark: benchmark, repeats: repeats)
  263. }
  264. }
  265. let hostOption = Option(
  266. "host",
  267. // Use IPv4 to avoid the happy eyeballs delay, this is important when we test the
  268. // connection throughput.
  269. default: "127.0.0.1",
  270. description: "The host to connect to.")
  271. let portOption = Option(
  272. "port",
  273. default: 8080,
  274. description: "The port on the host to connect to.")
  275. let benchmarkOption = Option(
  276. "benchmarks",
  277. default: Benchmarks.allCases.map { $0.rawValue }.joined(separator: ","),
  278. description: "A comma separated list of benchmarks to run. Defaults to all benchmarks.")
  279. let caCertificateOption = Option(
  280. "ca_certificate",
  281. default: "",
  282. description: "The path to the CA certificate to use.")
  283. let certificateOption = Option(
  284. "certificate",
  285. default: "",
  286. description: "The path to the certificate to use.")
  287. let privateKeyOption = Option(
  288. "private_key",
  289. default: "",
  290. description: "The path to the private key to use.")
  291. let hostOverrideOption = Option(
  292. "hostname_override",
  293. default: "",
  294. description: "The expected name of the server to use for TLS.")
  295. Group { group in
  296. group.command(
  297. "run_benchmarks",
  298. benchmarkOption,
  299. hostOption,
  300. portOption,
  301. caCertificateOption,
  302. certificateOption,
  303. privateKeyOption,
  304. hostOverrideOption
  305. ) { benchmarkNames, host, port, caCertificatePath, certificatePath, privateKeyPath, hostOverride in
  306. let tlsConfiguration = try makeClientTLSConfiguration(
  307. caCertificatePath: caCertificatePath,
  308. certificatePath: certificatePath,
  309. privateKeyPath: privateKeyPath)
  310. let configuration = ClientConnection.Configuration(
  311. target: .hostAndPort(host, port),
  312. eventLoopGroup: MultiThreadedEventLoopGroup(numberOfThreads: 1),
  313. tls: tlsConfiguration)
  314. let factory = ConnectionFactory(configuration: configuration)
  315. let names = benchmarkNames.components(separatedBy: ",")
  316. // validate the benchmarks exist before running any
  317. let benchmarks = names.map { name -> Benchmarks in
  318. guard let benchnark = Benchmarks(rawValue: name) else {
  319. print("unknown benchmark: \(name)")
  320. exit(1)
  321. }
  322. return benchnark
  323. }
  324. benchmarks.forEach { benchmark in
  325. let results = benchmark.run(using: factory)
  326. print(results.asCSV)
  327. }
  328. }
  329. group.command(
  330. "start_server",
  331. hostOption,
  332. portOption,
  333. caCertificateOption,
  334. certificateOption,
  335. privateKeyOption
  336. ) { host, port, caCertificatePath, certificatePath, privateKeyPath in
  337. let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
  338. let tlsConfiguration = try makeServerTLSConfiguration(
  339. caCertificatePath: caCertificatePath,
  340. certificatePath: certificatePath,
  341. privateKeyPath: privateKeyPath)
  342. let configuration = Server.Configuration(
  343. target: .hostAndPort(host, port),
  344. eventLoopGroup: group,
  345. serviceProviders: [EchoProvider()],
  346. tls: tlsConfiguration)
  347. let server: Server
  348. do {
  349. server = try Server.start(configuration: configuration).wait()
  350. } catch {
  351. print("unable to start server: \(error)")
  352. exit(1)
  353. }
  354. print("server started on port: \(server.channel.localAddress?.port ?? port)")
  355. // Stop the program from exiting.
  356. try? server.onClose.wait()
  357. }
  358. }.run()