Exemplo n.º 1
0
 public static void GetGrpcMethods(string serviceName, Type serviceType, IGrpcMarshallerFactory marshallerFactory)
 {
     foreach (GrpcMethodHandlerInfo handler in GrpcReflection.EnumerateServiceMethods(serviceName, serviceType, marshallerFactory))
     {
         Handers.AddOrUpdate(handler.GetHashString(), handler);
         InnerLogger.Log(LoggerLevel.Debug, handler.GetHashString());
     }
 }
Exemplo n.º 2
0
        public static IApplicationBuilder UseGrpcMonitorProtoFileEnable(this IApplicationBuilder app)
        {
            DirectoryMonitor monitor = new DirectoryMonitor(GrpcServiceMethodFactory.ProtoPath, "*.proto");

            monitor.Change += (string filePath) =>
            {
                InnerLogger.Log(LoggerLevel.Debug, filePath);
                GrpcServiceMethodFactory.ProtoQueue.Enqueue(filePath);
            };
            monitor.Start();
            return(app);
        }
Exemplo n.º 3
0
        public static Server StartAndRegisterConsul(this Server server)
        {
            server.Start();
            var ports    = server.Ports;
            var srvNames = server.Services.GetServicesName();

            try
            {
                var client = new ConsulClient(p =>
                {
                    p.Address = new Uri("http://127.0.0.1:8500");
                });
                client.Agent.ServiceRegister(new AgentServiceRegistration {
                    Address = "127.0.0.1",
                    Port    = ports.First().BoundPort,
                    Name    = srvNames.First(),
                    Tags    = srvNames.ToArray(),
                    Check   = new AgentServiceCheck {
                        //TTL=TimeSpan.FromSeconds(5),
                        Status   = HealthStatus.Passing,
                        TCP      = "127.0.0.1:50051",
                        Interval = TimeSpan.FromSeconds(5)
                    }
                }).Wait();

                //client.Agent.CheckRegister(new AgentCheckRegistration
                //{
                //    DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1),
                //    TTL = TimeSpan.FromSeconds(ServiceConfig.TCPInterval),
                //    Status = HealthStatus.Passing,
                //    ID = ServiceConfig.GetConsulServiceId() + ":ttlcheck",
                //    ServiceID = ServiceConfig.GetConsulServiceId(),
                //    Name = "ttlcheck"
                //}).Wait();

                client.Dispose();
            }
            catch (Exception ex)
            {
                InnerLogger.Log(LoggerLevel.Error, $"consul Register failed {Environment.NewLine}{ex.ToString()}");
            }


            return(server);
        }
Exemplo n.º 4
0
        public static bool Build(string csPath, string assemblyName)
        {
            var dllFiles = Directory.GetFiles(csPath, "*.cs");

            if (dllFiles.Length == 0)
            {
                return(false);
            }
            List <SyntaxTree> trees = new List <SyntaxTree>();

            foreach (var file in dllFiles)
            {
                // https://www.cnblogs.com/wolf-sun/p/6136482.html
                var csStr = File.ReadAllText(file, encoding: Encoding.GetEncoding("GB2312"));
                trees.Add(CSharpSyntaxTree.ParseText(csStr, encoding: Encoding.UTF8));
            }
            var references2 = new[] {
                MetadataReference.CreateFromFile(Assembly.Load("netstandard, Version=2.0.0.0").Location),
                MetadataReference.CreateFromFile(Assembly.Load("System.Runtime, Version=0.0.0.0").Location),
                MetadataReference.CreateFromFile(Assembly.Load("System.IO, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").Location),
                MetadataReference.CreateFromFile(Assembly.Load("System.Threading.Tasks, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").Location),
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Google.Protobuf.ProtoPreconditions).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(grpc.Channel).Assembly.Location),
            };
            var options     = new CSharpCompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release);
            var compilation = CSharpCompilation.Create(assemblyName, trees, references2, options);
            var result2     = compilation.Emit(Path.Combine(csPath, $"{assemblyName}.dll"), xmlDocumentationPath: Path.Combine(csPath, $"{assemblyName}.xml"));

            //, xmlDocPath: Path.Combine(csPath, $"{assemblyName}.xml")
            //var classSymbol = compilation.GlobalNamespace.GetTypeMembers("C").Single();
            //var docComment = classSymbol.GetDocumentationCommentXml();
            //Console.WriteLine(docComment);

            InnerLogger.Log(
                result2.Success ? LoggerLevel.Debug : LoggerLevel.Error,
                string.Join(",", result2.Diagnostics.Select(d => string.Format("[{0}]:{1}({2})", d.Id, d.GetMessage(), d.Location.GetLineSpan().StartLinePosition)))
                );
            Thread.Sleep(100);
            return(result2.Success);
        }
Exemplo n.º 5
0
        public static bool Generate(string baseDirectory, string protoFile)
        {
            var architecture = RuntimeInformation.OSArchitecture.ToString().ToLower();// 系统架构,x86 x64
            var bin          = string.Empty;
            var os           = string.Empty;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                os  = "windows";
                bin = ".exe";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                os = "linux";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                os = "macosx";
            }
            else
            {
                InnerLogger.Log(LoggerLevel.Error, "该平台不支持.");
                return(false);
            }
            var protocBinPath = Path.Combine(baseDirectory, $"tools/{os}_{architecture}/protoc{bin}");
            var pluginBinPath = Path.Combine(baseDirectory, $"tools/{os}_{architecture}/grpc_csharp_plugin{bin}");
            var csharp_out    = Path.Combine(baseDirectory, $"plugins/.{Path.GetFileNameWithoutExtension(protoFile)}");

            // 创建文件夹
            if (!Directory.Exists(csharp_out))
            {
                Directory.CreateDirectory(csharp_out);
            }
            //protoFile.GetMD5();

            var proto_path  = Path.Combine(baseDirectory, "protos");
            var protoc_args = $" --proto_path={proto_path} --csharp_out {csharp_out} {Path.GetFileName(protoFile)} --grpc_out {csharp_out} --plugin=protoc-gen-grpc={pluginBinPath}";

            Console.WriteLine(protocBinPath + "     " + protoc_args);
            var psi = new ProcessStartInfo(protocBinPath, protoc_args)
            {
                RedirectStandardOutput = true
            };

            //启动
            using (var proc = System.Diagnostics.Process.Start(psi))
            {
                if (proc == null)
                {
                    InnerLogger.Log(LoggerLevel.Debug, "-------------Can not exec.--------------");
                    return(false);
                }
                else
                {
                    var output = proc.StandardOutput.ReadToEnd();

                    InnerLogger.Log(LoggerLevel.Debug, "-------------Start read standard output--------------");
                    InnerLogger.Log(LoggerLevel.Debug, "-------------" + output + "--------------");
                    ////开始读取
                    //using (var sr = proc.StandardOutput)
                    //{
                    //    while (!sr.EndOfStream)
                    //    {
                    //        InnerLogger.Log(LoggerLevel.Debug, sr.ReadLine());
                    //    }

                    //    if (!proc.HasExited)
                    //    {
                    //        proc.Kill();
                    //    }
                    //}
                    InnerLogger.Log(LoggerLevel.Debug, "---------------Read end------------------");
                    InnerLogger.Log(LoggerLevel.Debug, $"Exited Code : {proc.ExitCode}");
                }
                Thread.Sleep(100);
            }
            return(true);
        }
 /// <summary>
 /// The point of stamping the event and hand-over to <see cref="InnerLogger"/>
 /// </summary>
 /// <param name="loggingEvent">event to stamp and pass</param>
 protected override void CallAppenders(LoggingEvent loggingEvent)
 {
     Call(loggingEvent);
     InnerLogger.Log(loggingEvent);
 }