GrpcEnvironment.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. #region Copyright notice and license
  2. // Copyright 2015, Google Inc.
  3. // All rights reserved.
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. #endregion
  31. using System;
  32. using System.Runtime.InteropServices;
  33. using System.Threading.Tasks;
  34. using Grpc.Core.Internal;
  35. using Grpc.Core.Logging;
  36. using Grpc.Core.Utils;
  37. namespace Grpc.Core
  38. {
  39. /// <summary>
  40. /// Encapsulates initialization and shutdown of gRPC library.
  41. /// </summary>
  42. public class GrpcEnvironment
  43. {
  44. const int THREAD_POOL_SIZE = 4;
  45. [DllImport("grpc_csharp_ext.dll")]
  46. static extern void grpcsharp_init();
  47. [DllImport("grpc_csharp_ext.dll")]
  48. static extern void grpcsharp_shutdown();
  49. [DllImport("grpc_csharp_ext.dll")]
  50. static extern IntPtr grpcsharp_version_string(); // returns not-owned const char*
  51. static object staticLock = new object();
  52. static GrpcEnvironment instance;
  53. static int refCount;
  54. static ILogger logger = new ConsoleLogger();
  55. readonly GrpcThreadPool threadPool;
  56. readonly CompletionRegistry completionRegistry;
  57. readonly DebugStats debugStats = new DebugStats();
  58. bool isClosed;
  59. /// <summary>
  60. /// Returns a reference-counted instance of initialized gRPC environment.
  61. /// Subsequent invocations return the same instance unless reference count has dropped to zero previously.
  62. /// </summary>
  63. internal static GrpcEnvironment AddRef()
  64. {
  65. lock (staticLock)
  66. {
  67. refCount++;
  68. if (instance == null)
  69. {
  70. instance = new GrpcEnvironment();
  71. }
  72. return instance;
  73. }
  74. }
  75. /// <summary>
  76. /// Decrements the reference count for currently active environment and shuts down the gRPC environment if reference count drops to zero.
  77. /// (and blocks until the environment has been fully shutdown).
  78. /// </summary>
  79. internal static void Release()
  80. {
  81. lock (staticLock)
  82. {
  83. Preconditions.CheckState(refCount > 0);
  84. refCount--;
  85. if (refCount == 0)
  86. {
  87. instance.Close();
  88. instance = null;
  89. }
  90. }
  91. }
  92. internal static int GetRefCount()
  93. {
  94. lock (staticLock)
  95. {
  96. return refCount;
  97. }
  98. }
  99. /// <summary>
  100. /// Gets application-wide logger used by gRPC.
  101. /// </summary>
  102. /// <value>The logger.</value>
  103. public static ILogger Logger
  104. {
  105. get
  106. {
  107. return logger;
  108. }
  109. }
  110. /// <summary>
  111. /// Sets the application-wide logger that should be used by gRPC.
  112. /// </summary>
  113. public static void SetLogger(ILogger customLogger)
  114. {
  115. Preconditions.CheckNotNull(customLogger, "customLogger");
  116. logger = customLogger;
  117. }
  118. /// <summary>
  119. /// Creates gRPC environment.
  120. /// </summary>
  121. private GrpcEnvironment()
  122. {
  123. NativeLogRedirector.Redirect();
  124. GrpcNativeInit();
  125. completionRegistry = new CompletionRegistry(this);
  126. threadPool = new GrpcThreadPool(this, THREAD_POOL_SIZE);
  127. threadPool.Start();
  128. }
  129. /// <summary>
  130. /// Gets the completion registry used by this gRPC environment.
  131. /// </summary>
  132. internal CompletionRegistry CompletionRegistry
  133. {
  134. get
  135. {
  136. return this.completionRegistry;
  137. }
  138. }
  139. /// <summary>
  140. /// Gets the completion queue used by this gRPC environment.
  141. /// </summary>
  142. internal CompletionQueueSafeHandle CompletionQueue
  143. {
  144. get
  145. {
  146. return this.threadPool.CompletionQueue;
  147. }
  148. }
  149. /// <summary>
  150. /// Gets the completion queue used by this gRPC environment.
  151. /// </summary>
  152. internal DebugStats DebugStats
  153. {
  154. get
  155. {
  156. return this.debugStats;
  157. }
  158. }
  159. /// <summary>
  160. /// Gets version of gRPC C core.
  161. /// </summary>
  162. internal static string GetCoreVersionString()
  163. {
  164. var ptr = grpcsharp_version_string(); // the pointer is not owned
  165. return Marshal.PtrToStringAnsi(ptr);
  166. }
  167. internal static void GrpcNativeInit()
  168. {
  169. grpcsharp_init();
  170. }
  171. internal static void GrpcNativeShutdown()
  172. {
  173. grpcsharp_shutdown();
  174. }
  175. /// <summary>
  176. /// Shuts down this environment.
  177. /// </summary>
  178. private void Close()
  179. {
  180. if (isClosed)
  181. {
  182. throw new InvalidOperationException("Close has already been called");
  183. }
  184. threadPool.Stop();
  185. GrpcNativeShutdown();
  186. isClosed = true;
  187. debugStats.CheckOK();
  188. }
  189. }
  190. }