VsockSocketTests.swift 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright 2022, 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 EchoImplementation
  17. import EchoModel
  18. import GRPC
  19. import NIOPosix
  20. import XCTest
  21. class VsockSocketTests: GRPCTestCase {
  22. func testVsockSocket() throws {
  23. try XCTSkipUnless(self.vsockAvailable(), "Vsock unavailable")
  24. let group = NIOPosix.MultiThreadedEventLoopGroup(numberOfThreads: 1)
  25. defer {
  26. XCTAssertNoThrow(try group.syncShutdownGracefully())
  27. }
  28. // Setup a server.
  29. let server = try Server.insecure(group: group)
  30. .withServiceProviders([EchoProvider()])
  31. .withLogger(self.serverLogger)
  32. .bind(vsockAddress: .init(cid: .any, port: 31234))
  33. .wait()
  34. defer {
  35. XCTAssertNoThrow(try server.close().wait())
  36. }
  37. let channel = try GRPCChannelPool.with(
  38. target: .vsockAddress(.init(cid: .local, port: 31234)),
  39. transportSecurity: .plaintext,
  40. eventLoopGroup: group
  41. )
  42. defer {
  43. XCTAssertNoThrow(try channel.close().wait())
  44. }
  45. let client = Echo_EchoNIOClient(channel: channel)
  46. let resp = try client.get(Echo_EchoRequest(text: "Hello")).response.wait()
  47. XCTAssertEqual(resp.text, "Swift echo get: Hello")
  48. }
  49. private func vsockAvailable() -> Bool {
  50. let fd: CInt
  51. #if os(Linux)
  52. fd = socket(AF_VSOCK, CInt(SOCK_STREAM.rawValue), 0)
  53. #elseif canImport(Darwin)
  54. fd = socket(AF_VSOCK, SOCK_STREAM, 0)
  55. #else
  56. fd = -1
  57. #endif
  58. if fd == -1 { return false }
  59. precondition(close(fd) == 0)
  60. return true
  61. }
  62. }