/// <summary> /// 清除路由,清理连接 /// </summary> /// <param name="serverName">serverName</param> /// <param name="router">router</param> public static void ClearRouter(string serverName, string router) { string path = getRouterPath(serverName) + $"/[{router}]"; logger.LogInformation($"服务退出,清理路由:{path}"); try { var existPath = currentZookeeper.existsAsync(path, false); existPath.Wait(); if (existPath.Result != null) { Delete(path); } if (currentZookeeper != null) { var rst = currentZookeeper.closeAsync(); rst.Wait(); currentZookeeper = null; } } catch (Exception e) { LogTextWriter.Write(e); // 这里吞掉算了 ,服务要退出了,不管了··· } }
static void EnableFileLogging( ) { if (Path.DirectorySeparatorChar != '\\') { return; } // On Windows log all output to a log file string configPath = PropertyService.ConfigPath; if (!Directory.Exists(configPath)) { Directory.CreateDirectory(configPath); } string file = Path.Combine(configPath, "log.txt"); try { logFile = new StreamWriter(file); logFile.AutoFlush = true; LogTextWriter tw = new LogTextWriter(); tw.ChainWriter(logFile); tw.ChainWriter(Console.Out); Console.SetOut(tw); tw = new LogTextWriter(); tw.ChainWriter(logFile); tw.ChainWriter(Console.Error); Console.SetError(tw); } catch { } }
static void Main(string[] args) { // Set log mode LogTextWriter.InitLogMode(); // Start listener var srv = new OTcpServer(1010); // Create server instance var impl = new ServerLogicImplementation(); // Register server implementation srv.RegisterImplementation(impl); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"The {Process.GetCurrentProcess().ProcessName} start"); Console.WriteLine("Write message nad press Enter key to send notifications"); Console.ResetColor(); while (true) { var msg = Console.ReadLine(); foreach (var client in impl.Subscribes) { client.Notify(msg); } Console.WriteLine($"{impl.Subscribes.Count} notification{(impl.Subscribes.Count > 1 ? "s" : "")}"); } }
/// <summary> /// Executes a file and reports events related to the execution to the 'monitor' passed in the parameters. /// </summary> public static int ExecuteCommand( string command, string args, string baseDirectory, IProgressMonitor monitor, out string errorOutput, out string programOutput) { errorOutput = string.Empty; int exitCode = -1; var swError = new StringWriter(); var swOutput = new StringWriter(); var chainedError = new LogTextWriter(); chainedError.ChainWriter(monitor.Log); chainedError.ChainWriter(swError); var chainedOutput = new LogTextWriter(); chainedOutput.ChainWriter(monitor.Log); chainedOutput.ChainWriter(swOutput); monitor.Log.WriteLine("{0} {1}", command, args); var operationMonitor = new AggregatedOperationMonitor(monitor); var p = Runtime.ProcessService.StartProcess(command, args, baseDirectory, chainedOutput, chainedError, null); operationMonitor.AddOperation(p); //handles cancellation p.WaitForOutput(); errorOutput = swError.ToString(); programOutput = swOutput.ToString(); exitCode = p.ExitCode; p.Dispose(); if (monitor.IsCancelRequested) { monitor.Log.WriteLine(GettextCatalog.GetString("Build cancelled")); monitor.ReportError(GettextCatalog.GetString("Build cancelled"), null); if (exitCode == 0) { exitCode = -1; } } { chainedError.Close(); swError.Close(); operationMonitor.Dispose(); } return(exitCode); }
public ProgressMonitor(SynchronizationContext context, CancellationTokenSource cancellationTokenSource) { this.cancellationTokenSource = cancellationTokenSource; this.context = context; logWriter = new LogTextWriter(context); logWriter.TextWritten += DoWriteLog; errorLogWriter = new LogTextWriter(context); errorLogWriter.TextWritten += DoWriteErrorLog; }
public static void Initialize(bool withAppDomains) { if (withAppDomains) { // if we're using app domains, set up logging for this domain Console.SetOut(LogTextWriter.Create()); Console.SetError(LogTextWriter.Create()); // hook unhandled exception handler AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; } else { // we're not using app domains, so game initialization code will set up logging } }
/// <summary> /// 枚举转为 StatusCode /// </summary> /// <typeparam name="TEnumClass">枚举类型</typeparam> /// <param name="enumValue">枚举值</param> /// <returns>状态码</returns> public static StatusCode ToCode <TEnumClass>(this TEnumClass enumValue) where TEnumClass : struct { var cd = GetEnumCodeDescription(enumValue); var code = (int)(object)enumValue; if (cd == null) { LogTextWriter.Write($"枚举值{enumValue} 没有定义属性[CodeDescAttribute]"); // return StatusCode.ErrorCodeUndefined; return(new StatusCode(code, StatusCode.ErrorCodeUndefined.ToString())); } return(new StatusCode(code, cd.Description)); }
static void CompileToAssembly(IProgressMonitor monitor, DotNetProjectConfiguration configuration, JavaCompilerParameters compilerparameters, ProjectItemCollection projectItems, TextWriter output, TextWriter error) { monitor.Log.WriteLine(GettextCatalog.GetString("Generating assembly ...")); LogTextWriter chainedError = new LogTextWriter(); chainedError.ChainWriter(monitor.Log); chainedError.ChainWriter(error); LogTextWriter chainedOutput = new LogTextWriter(); chainedOutput.ChainWriter(monitor.Log); chainedOutput.ChainWriter(output); string outdir = configuration.OutputDirectory; string outclass = Path.Combine(outdir, configuration.OutputAssembly + ".class"); string asm = Path.GetFileNameWithoutExtension(outclass); StringBuilder args = new StringBuilder("*.class "); args.Append("-assembly:"); args.Append(asm); args.Append(" -target:"); args.Append(TargetToString(configuration.CompileTarget)); if (configuration.DebugMode) { args.Append(" -debug"); } args.Append(" -srcpath:"); args.Append(configuration.ParentItem.BaseDirectory); foreach (ProjectReference lib in projectItems.GetAll <ProjectReference> ()) { foreach (string fileName in lib.GetReferencedFileNames(configuration.Selector)) { args.Append(" -r:"); args.Append(fileName); } } foreach (string fileName in new ProjectReference(ReferenceType.Gac, "mscorlib").GetReferencedFileNames(configuration.Selector)) { args.Append(" -r:"); args.Append(fileName); } monitor.Log.WriteLine("ikvmc " + args); Process process = Runtime.ProcessService.StartProcess("ikvmc", args.ToString(), configuration.OutputDirectory, chainedOutput, chainedError, null); process.WaitForExit(); }
//copied from MoonlightBuildExtension public static int ExecuteCommand(IProgressMonitor monitor, System.Diagnostics.ProcessStartInfo startInfo, out string errorOutput) { startInfo.UseShellExecute = false; startInfo.RedirectStandardError = true; startInfo.RedirectStandardOutput = true; errorOutput = string.Empty; int exitCode = -1; var swError = new StringWriter(); var chainedError = new LogTextWriter(); chainedError.ChainWriter(monitor.Log); chainedError.ChainWriter(swError); var operationMonitor = new AggregatedOperationMonitor(monitor); try { var p = Runtime.ProcessService.StartProcess(startInfo, monitor.Log, chainedError, null); operationMonitor.AddOperation(p); //handles cancellation p.WaitForOutput(); errorOutput = swError.ToString(); exitCode = p.ExitCode; p.Dispose(); if (monitor.IsCancelRequested) { monitor.Log.WriteLine(GettextCatalog.GetString("Build cancelled")); monitor.ReportError(GettextCatalog.GetString("Build cancelled"), null); if (exitCode == 0) { exitCode = -1; } } } finally { chainedError.Close(); swError.Close(); operationMonitor.Dispose(); } return(exitCode); }
void CreateEvaluator() { logTextWriter = new LogTextWriter(); logTextWriter.TextWritten += LogTextWriterTextWritten; var settings = new CompilerSettings(); var printer = new ConsoleViewReportPrinter(logTextWriter); var context = new CompilerContext(settings, printer); evaluator = new Evaluator(context); evaluator.DescribeTypeExpressions = true; evaluator.WaitOnTask = true; evaluator.InteractiveBaseClass = typeof(CSharpInteractiveBase); CSharpInteractiveBase.Output = logTextWriter; CSharpInteractiveBase.Error = logTextWriter; CSharpInteractiveBase.Evaluator = evaluator; CSharpInteractiveBase.OnClear = OnClear; CSharpInteractiveBase.OnInspect = OnInspect; }
static bool Compile(IProgressMonitor monitor, string compiler, string args, DotNetProjectConfiguration configuration, JavaCompilerParameters compilerparameters, TextWriter output, TextWriter error) { LogTextWriter chainedError = new LogTextWriter(); chainedError.ChainWriter(monitor.Log); chainedError.ChainWriter(error); LogTextWriter chainedOutput = new LogTextWriter(); chainedOutput.ChainWriter(monitor.Log); chainedOutput.ChainWriter(output); monitor.Log.WriteLine(GettextCatalog.GetString("Compiling Java source code ...")); monitor.Log.WriteLine(compiler + " " + args); Process process = Runtime.ProcessService.StartProcess(compiler, args, null, chainedOutput, chainedError, null); process.WaitForExit(); return(process.ExitCode == 0); }
protected override Task <TargetEvaluationResult> OnRunTarget(ProgressMonitor monitor, string target, ConfigurationSelector configuration, TargetEvaluationContext context) { if (target == ProjectService.BuildTarget) { target = "all"; } else if (target == ProjectService.CleanTarget) { target = "clean"; } DotNetProjectConfiguration conf = (DotNetProjectConfiguration)Project.GetConfiguration(configuration); return(Task <TargetEvaluationResult> .Factory.StartNew(delegate { using (var output = new StringWriter()) { using (var tw = new LogTextWriter()) { tw.ChainWriter(output); tw.ChainWriter(monitor.Log); using (ProcessWrapper proc = Runtime.ProcessService.StartProcess("make", "PROFILE=" + conf.Id + " " + target, conf.OutputDirectory, monitor.Log, tw, null)) proc.WaitForOutput(); tw.UnchainWriter(output); tw.UnchainWriter(monitor.Log); CompilerResults cr = new CompilerResults(null); string[] lines = output.ToString().Split('\n'); foreach (string line in lines) { CompilerError err = CreateErrorFromString(line); if (err != null) { cr.Errors.Add(err); } } return new TargetEvaluationResult(new BuildResult(cr, output.ToString())); } } })); }
public BuildResult RunTarget(MonoDevelop.Core.IProgressMonitor monitor, string target, ConfigurationSelector configuration) { if (target == ProjectService.BuildTarget) { target = "all"; } else if (target == ProjectService.CleanTarget) { target = "clean"; } DotNetProjectConfiguration conf = (DotNetProjectConfiguration)project.GetConfiguration(configuration); using (var output = new StringWriter()) { using (var tw = new LogTextWriter()) { tw.ChainWriter(output); tw.ChainWriter(monitor.Log); using (ProcessWrapper proc = Runtime.ProcessService.StartProcess("make", "PROFILE=" + conf.Id + " " + target, conf.OutputDirectory, monitor.Log, tw, null)) proc.WaitForOutput(); tw.UnchainWriter(output); tw.UnchainWriter(monitor.Log); var result = new BuildResult(output.ToString(), 1, 0); string[] lines = result.CompilerOutput.Split('\n'); foreach (string line in lines) { var err = CreateErrorFromString(line); if (err != null) { result.Append(err); } } return(result); } } }
public BuildResult RunTarget(MonoDevelop.Core.IProgressMonitor monitor, string target, ConfigurationSelector configuration) { if (target == ProjectService.BuildTarget) { target = "all"; } else if (target == ProjectService.CleanTarget) { target = "clean"; } DotNetProjectConfiguration conf = (DotNetProjectConfiguration)project.GetConfiguration(configuration); StringWriter output = new StringWriter(); LogTextWriter tw = new LogTextWriter(); tw.ChainWriter(output); tw.ChainWriter(monitor.Log); ProcessWrapper proc = Runtime.ProcessService.StartProcess("make", "PROFILE=" + conf.Id + " " + target, conf.OutputDirectory, monitor.Log, tw, null); proc.WaitForOutput(); CompilerResults cr = new CompilerResults(null); string[] lines = output.ToString().Split('\n'); foreach (string line in lines) { CompilerError err = CreateErrorFromString(line); if (err != null) { cr.Errors.Add(err); } } return(new BuildResult(cr, output.ToString())); }
private static void checkTimeOut() { while (true) { try { Thread.Sleep(60 * 1000); // 每1分钟检查一次 if (dicConnections.Count < 1) { continue; } string[] keys = dicConnections.Keys.ToArray(); Random r = new Random(DateTime.Now.Millisecond); var k = keys[r.Next(0, keys.Length)]; var indxValue = dicConnections[k]; // 随机检查 var keyValuePairs = indxValue.Where(x => DateTime.Now.Subtract(x.V1).TotalMilliseconds > 2 * 60 * 1000)?.ToArray(); // 找到2分钟没有被用的连接,释放掉 if (keyValuePairs == null || keyValuePairs.Length < 1) { continue; } lock (root) { for (int i = 0; i < keyValuePairs.Length; i++) { keyValuePairs[i].V2?.Close(); indxValue.Remove(keyValuePairs[i]); keyValuePairs[i].V2 = null; } } } catch (Exception e) { LogTextWriter.Write(e); } } }
static void EnableFileLogging( ) { if (Path.DirectorySeparatorChar != '\\') { return; } // On Windows log all output to a log file string configPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); configPath = Path.Combine(configPath, "MonoDevelop"); if (!Directory.Exists(configPath)) { Directory.CreateDirectory(configPath); } string file = Path.Combine(configPath, "log.txt"); try { logFile = new StreamWriter(file); logFile.AutoFlush = true; LogTextWriter tw = new LogTextWriter(); tw.ChainWriter(logFile); tw.ChainWriter(Console.Out); Console.SetOut(tw); tw = new LogTextWriter(); tw.ChainWriter(logFile); tw.ChainWriter(Console.Error); Console.SetError(tw); } catch { } }
int ExecuteCommand(string command, string args, string baseDirectory, ProgressMonitor monitor, out string errorOutput) { errorOutput = string.Empty; int exitCode = -1; using (var swError = new StringWriter()) { using (var chainedError = new LogTextWriter()) { chainedError.ChainWriter(monitor.Log); chainedError.ChainWriter(swError); monitor.Log.WriteLine("{0} {1}", command, args); using (ProcessWrapper p = Runtime.ProcessService.StartProcess(command, args, baseDirectory, monitor.Log, chainedError, null)) using (monitor.CancellationToken.Register(p.Cancel)) { p.WaitForOutput(); chainedError.UnchainWriter(monitor.Log); chainedError.UnchainWriter(swError); errorOutput = swError.ToString(); exitCode = p.ExitCode; if (monitor.CancellationToken.IsCancellationRequested) { monitor.Log.WriteLine(GettextCatalog.GetString("Build cancelled")); monitor.ReportError(GettextCatalog.GetString("Build cancelled"), null); if (exitCode == 0) { exitCode = -1; } } } } } return(exitCode); }
public BaseProgressMonitor() { progressTracker = new ProgressTracker(); logger = new LogTextWriter(); logger.TextWritten += new LogTextEventHandler(WriteLogInternal); }
//FIXME: Check whether autogen.sh is required or not protected override BuildResult Build(IProgressMonitor monitor, SolutionEntityItem entry, ConfigurationSelector configuration) { Project project = entry as Project; if (project == null) { return(base.Build(monitor, entry, configuration)); } MakefileData data = project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData; if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty(data.BuildTargetName)) { return(base.Build(monitor, entry, configuration)); } //FIXME: Gen autofoo ? autoreconf? string output = String.Empty; int exitCode = 0; monitor.BeginTask(GettextCatalog.GetString("Building {0}", project.Name), 1); try { string baseDir = project.BaseDirectory; string args = string.Format("-j {0} {1}", data.ParallelProcesses, data.BuildTargetName); StringWriter swOutput = new StringWriter(); LogTextWriter chainedOutput = new LogTextWriter(); chainedOutput.ChainWriter(monitor.Log); chainedOutput.ChainWriter(swOutput); ProcessWrapper process = Runtime.ProcessService.StartProcess("make", args, baseDir, chainedOutput, chainedOutput, null); process.WaitForOutput(); exitCode = process.ExitCode; output = swOutput.ToString(); chainedOutput.Close(); swOutput.Close(); monitor.Step(1); } catch (Exception e) { monitor.ReportError(GettextCatalog.GetString("Project could not be built: "), e); return(null); } finally { monitor.EndTask(); } TempFileCollection tf = new TempFileCollection(); Regex regexError = data.GetErrorRegex(false); Regex regexWarning = data.GetWarningRegex(false); BuildResult cr = ParseOutput(tf, output, project.BaseDirectory, regexError, regexWarning); if (exitCode != 0 && cr.FailedBuildCount == 0) { cr.AddError(GettextCatalog.GetString("Build failed. See Build Output panel.")); } return(cr); }
/// <summary> /// 查找所有的 GrantRpcBaseServer 继承类 /// </summary> /// <returns>所有的 GrantRpcBaseServer 继承类</returns> public List <ClassInfo> GetAllInterfaceClass() { //string lang = string.Empty; //if (string.IsNullOrEmpty(lang)) //{ // lang = "zh_cn"; //} //var key = lang + "_f"; //if (sAllApiInfo.ContainsKey(key)) //{ // return sAllApiInfo[key]; //} //if (this.assembly == null) //{ // return new List<ClassInfo>(); //} // var ts = this.assembly.GetTypes(); var list = GetAllInterface(); // ts.Where(this.IsGrantRpcBaseServerChildClass).ToList(); var sum = list.Count; if (sum <= 0) { return(new List <ClassInfo>()); } var infos = new ClassInfo[sum]; Stopwatch sw = new Stopwatch(); sw.Start(); var rangesize = (int)(sum / Environment.ProcessorCount) + 1; Parallel.ForEach(Partitioner.Create(1, sum + 1, rangesize), range => { for (int i = range.Item1; i < range.Item2; i++) { var x = list[i - 1]; try { var t = this.GetInterfaceParam(x); var info = this.GetInterfaceInfo(x, t.args, ""); // var arg = new ParseTypeInfo(this.assembly, t.args); // var infoArgs = arg.Parse(); var infoArgs = new ClassInfo(this.assembly.FullName); var json = this.ToJson(t.args, false); var apiInfo = GetApiInfoByType(t.args); infoArgs.JsonDesc = json.json; infoArgs.LimitDesc = json.replaceJson; infoArgs.ApiClassInfo = apiInfo; // var rtn = new ParseTypeInfo(this.assembly, t.result); // var infoResult = rtn.Parse(); var infoResult = new ClassInfo(this.assembly.FullName); apiInfo = GetApiInfoByType(t.result); json = this.ToJson(t.result, false); infoResult.JsonDesc = json.json; infoResult.LimitDesc = json.replaceJson; infoResult.ApiClassInfo = apiInfo; info.PropertyInfo.Add(infoArgs); info.PropertyInfo.Add(infoResult); infos[i - 1] = info; } catch (Exception ex) { LogTextWriter.Write($"{x.FullName}:{ex.Message}"); var infoArgs = new ClassInfo(this.assembly.FullName); infoArgs.Name = x.Name; infoArgs.FullName = x.FullName; infoArgs.Desc = $"Parse Error:{ex.Message}"; infos[i - 1] = infoArgs; } } }); sw.Stop(); Trace.WriteLine($"Parallel.foreach {sw.ElapsedMilliseconds} ms"); return(infos.ToList()); }
protected override void OnStart(string[] args) { Parameters = args.Where(p => p.StartsWith("/")) .Select(p => p.TrimStart('/')) .Select(p => new { Parameter = p.Trim(), Separator = p.Trim().IndexOf(':') }) .ToDictionary(p => p.Separator == -1 ? p.Parameter.ToLower() : p.Parameter.Substring(0, p.Separator).ToLower(), p => p.Separator == -1 ? null : p.Parameter.Substring(p.Separator + 1)); // Handle parameters if (Parameters.ContainsKey("log")) LogFile = new FileInfo(Parameters["log"]); else LogFile = new FileInfo(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "FlowTomator.Service.log")); // Redirect logging LogTextWriter textWriter = new LogTextWriter(); textWriter.NewLine += TextWriter_Updated; Console.SetOut(textWriter); Console.SetError(textWriter); // Start service Log.Info(Environment.NewLine); Log.Info("Starting FlowTomator service"); base.OnStart(args); // Share service via .NET remoting Log.Debug("Enabling remote monitoring"); BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider(); serverProvider.TypeFilterLevel = TypeFilterLevel.Full; IChannel channel = new IpcServerChannel("FlowTomator", "FlowTomator.Service", serverProvider); ChannelServices.RegisterChannel(channel); serviceRef = RemotingServices.Marshal(this, nameof(FlowTomatorService)); Log.Info("Service started"); // Autostart startup flows if (Settings.Default.StartupFlows != null) foreach (string startupFlow in Settings.Default.StartupFlows) { string path = startupFlow; if (!Path.IsPathRooted(path)) path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), path); FlowEnvironment flow = Load(path); flow.Start(); } Flows.CollectionChanged += Flows_CollectionChanged; }
/// <summary> /// Executes a file and reports events related to the execution to the 'monitor' passed in the parameters. /// </summary> public static int ExecuteCommand( string command, string args, string baseDirectory, IProgressMonitor monitor, out string errorOutput, out string programOutput) { bool useMonitor = monitor != null; errorOutput = string.Empty; int exitCode = -1; var swError = new StringWriter(); var swOutput = new StringWriter(); var chainedError = new LogTextWriter(); chainedError.ChainWriter(swError); var chainedOutput = new LogTextWriter(); chainedOutput.ChainWriter(swOutput); if (useMonitor) { chainedError.ChainWriter(monitor.Log); chainedOutput.ChainWriter(monitor.Log); monitor.Log.WriteLine("{0} {1}", command, args); } // Workaround for not handling %PATH% env var expansion properly if (!command.Contains(Path.DirectorySeparatorChar)) { command = TryExpandPathEnvVariable(command, baseDirectory); } TryHandleSheBang(ref command, ref args); var operationMonitor = useMonitor ? new AggregatedOperationMonitor(monitor) : null; var p = Runtime.ProcessService.StartProcess(command, args, baseDirectory, chainedOutput, chainedError, null); if (useMonitor) { operationMonitor.AddOperation(p); //handles cancellation } p.WaitForOutput(); swError.Flush(); swOutput.Flush(); errorOutput = swError.ToString(); programOutput = swOutput.ToString(); exitCode = p.ExitCode; p.Dispose(); if (useMonitor) { if (monitor.IsCancelRequested) { monitor.Log.WriteLine(GettextCatalog.GetString("Build cancelled")); monitor.ReportError(GettextCatalog.GetString("Build cancelled"), null); if (exitCode == 0) { exitCode = -1; } } operationMonitor.Dispose(); } chainedError.Close(); swOutput.Close(); swError.Close(); return(exitCode); }
//FIXME: Check whether autogen.sh is required or not protected async override Task <BuildResult> OnBuild(ProgressMonitor monitor, ConfigurationSelector configuration, OperationContext operationContext) { if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty(data.BuildTargetName)) { return(await base.OnBuild(monitor, configuration, operationContext)); } //FIXME: Gen autofoo ? autoreconf? string output = String.Empty; int exitCode = 0; monitor.BeginTask(GettextCatalog.GetString("Building {0}", Project.Name), 1); try { string baseDir = Project.BaseDirectory; string args = string.Format("-j {0} {1}", data.ParallelProcesses, data.BuildTargetName); using (var swOutput = new StringWriter()) { using (var chainedOutput = new LogTextWriter()) { chainedOutput.ChainWriter(monitor.Log); chainedOutput.ChainWriter(swOutput); using (ProcessWrapper process = Runtime.ProcessService.StartProcess("make", args, baseDir, chainedOutput, chainedOutput, null)) { await process.Task; chainedOutput.UnchainWriter(monitor.Log); chainedOutput.UnchainWriter(swOutput); exitCode = process.ExitCode; output = swOutput.ToString(); monitor.Step(1); } } } } catch (Exception e) { monitor.ReportError(GettextCatalog.GetString("Project could not be built: "), e); return(null); } finally { monitor.EndTask(); } TempFileCollection tf = new TempFileCollection(); Regex regexError = data.GetErrorRegex(false); Regex regexWarning = data.GetWarningRegex(false); BuildResult cr = ParseOutput(tf, output, Project.BaseDirectory, regexError, regexWarning); if (exitCode != 0 && cr.FailedBuildCount == 0) { cr.AddError(GettextCatalog.GetString("Build failed. See Build Output panel.")); } return(cr); }
/// <summary>Executes a build command, writing output to the monitor.</summary> /// <returns>Whether the command executed successfully.</returns> /// <param name='monitor'>Progress monitor for writing output and handling cancellation.</param> /// <param name='startInfo'>Process start info. Redirection will be enabled if necessary.</param> /// <param name='stdout'>Text writer for stdout. May be null.</param> /// <param name='stderr'>Text writer for stderr. May be null.</param> public static int ExecuteBuildCommand(IProgressMonitor monitor, ProcessStartInfo startInfo, TextWriter stdout, TextWriter stderr) { monitor.Log.WriteLine(startInfo.FileName + " " + startInfo.Arguments); startInfo.UseShellExecute = false; startInfo.RedirectStandardError = true; startInfo.RedirectStandardOutput = true; int exitCode = -1; TextWriter outWriter = monitor.Log, errWriter = monitor.Log; LogTextWriter chainedOut = null, chainedErr = null; if (stdout != null) { chainedOut = new LogTextWriter(); chainedOut.ChainWriter(outWriter); chainedOut.ChainWriter(stdout); outWriter = chainedOut; } if (stderr != null) { chainedErr = new LogTextWriter(); chainedErr.ChainWriter(errWriter); chainedErr.ChainWriter(stderr); errWriter = chainedErr; } var operationMonitor = new AggregatedOperationMonitor(monitor); IProcessAsyncOperation p = null; try { p = Runtime.ProcessService.StartProcess(startInfo, outWriter, errWriter, null); operationMonitor.AddOperation(p); //handles cancellation p.WaitForCompleted(); exitCode = p.ExitCode; } finally { if (chainedErr != null) { chainedErr.Dispose(); } if (chainedOut != null) { chainedOut.Dispose(); } if (p != null) { p.Dispose(); } operationMonitor.Dispose(); } if (exitCode != 0) { monitor.Log.WriteLine("{0} exited with code {1}", Path.GetFileName(startInfo.FileName), exitCode); } return(exitCode); }
public bool Deploy(DeployContext ctx, Solution solution, string defaultConf, string targetDir, bool generateFiles, IProgressMonitor monitor) { if (generateFiles) { if (!GenerateFiles(ctx, solution, defaultConf, monitor)) { return(false); } } monitor.BeginTask(GettextCatalog.GetString("Deploying Solution to Tarball"), 3); try { string baseDir = Path.GetDirectoryName(solution.FileName); ProcessWrapper ag_process = Runtime.ProcessService.StartProcess("sh", generateAutotools ? "autogen.sh" : "configure", baseDir, monitor.Log, monitor.Log, null); ag_process.WaitForOutput(); if (ag_process.ExitCode > 0) { throw new Exception(GettextCatalog.GetString("An unspecified error occurred while running '{0}'", generateAutotools ? "autogen.sh" : "configure")); } monitor.Step(1); StringWriter sw = new StringWriter(); LogTextWriter chainedOutput = new LogTextWriter(); chainedOutput.ChainWriter(monitor.Log); chainedOutput.ChainWriter(sw); ProcessWrapper process = Runtime.ProcessService.StartProcess("make", "dist", baseDir, chainedOutput, monitor.Log, null); process.WaitForOutput(); if (process.ExitCode > 0) { throw new Exception(GettextCatalog.GetString("An unspecified error occurred while running '{0}'", "make dist")); } monitor.Step(1); // FIXME: hackish way to get the created tarball's filename string output = sw.ToString(); int targz = output.LastIndexOf("tar.gz"); int begin = output.LastIndexOf('>', targz); string filename = output.Substring(begin + 1, (targz - begin) + 5).Trim(); FileService.CopyFile(Path.Combine(baseDir, filename), Path.Combine(targetDir, filename)); monitor.Step(1); } catch (Exception e) { monitor.ReportError(GettextCatalog.GetString("Solution could not be deployed: "), e); return(false); } finally { monitor.EndTask(); } monitor.ReportSuccess(GettextCatalog.GetString("Solution was successfully deployed.")); return(true); }
/// <summary> /// 初始化服务配置(本地super.json中必须指明读取的配置源) /// </summary> /// <returns></returns> private static void InitConfiguration() { var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); if (string.IsNullOrEmpty(env)) // 不配置就走config.json { configFile = string.Format(configFile, ""); } else { env = env.ToLower().Trim(); //switch (env) //{ // case "dev": // configFile = string.Format(configFile, ".dev"); // break; // case "test": // configFile = string.Format(configFile, ".test"); // break; // case "prod": // configFile = string.Format(configFile, ".prod"); // break; // default: // configFile = string.Format(configFile, ""); // break; //} configFile = string.Format(configFile, "." + env); } var configJson = Path.Combine(AppContext.BaseDirectory, configFile); // 在NLog配置没有初始化之前,只能靠Console输出日志 LogTextWriter.Write($"当前的环境变量是:{env},加载的指向配置文件是:{configJson}\r\n"); if (!File.Exists(configJson)) { throw new Exception($"在当前服务运行目录中找不到配置文件{configFile}"); } //配置源优先从服务本地根目录下的config.json获取, IConfiguration configSource = new ConfigurationBuilder().SetBasePath(AppContext.BaseDirectory) .AddJsonFile(configFile, optional: true, reloadOnChange: false).Build(); ServerSetting.configCenter = configSource.GetSection("ServerConfig:ConfigCenter").Get <ConfigCenter>(); //如未获取到,则配置源默认为ConfigType.Local if (ServerSetting.configCenter == null) { ServerSetting.configCenter = new ConfigCenter() { ConfigType = ConfigType.Local }; } var settingConfigBuilder = new ConfigurationBuilder(); string configPath = string.Empty; switch (ServerSetting.configCenter.ConfigType) { //配置源为ConfigType.Local时,优先读取内部config.json文件,不存在则读取上级目录Conf下的config.json case ConfigType.Local: configPath = Path.Combine(AppContext.BaseDirectory, configFile); if (File.Exists(configPath)) { settingConfigBuilder.SetBasePath(AppContext.BaseDirectory).AddJsonFile(configFile, optional: false, reloadOnChange: false); } else { var dirInfo = new DirectoryInfo(AppContext.BaseDirectory); var conf = Path.Combine(dirInfo.Parent.Parent.FullName, "conf"); bool isExist = false; if (Directory.Exists(conf)) { configPath = Path.Combine(conf, configFile); if (File.Exists(configPath)) { settingConfigBuilder.SetBasePath(conf).AddJsonFile(configFile, optional: false, reloadOnChange: false); isExist = true; } } if (!isExist) { throw new Exception($"请检查配置文件的路径是否存在{conf}/{configFile}"); } } break; case ConfigType.HttpFile: settingConfigBuilder.Sources.Add(new RemoteJsonFileConfigurationSource() { Uri = ServerSetting.configCenter.Ip, Optional = false }); configPath = ServerSetting.configCenter.Ip; break; default: throw new Exception($"The setting 'ConfigCenter.ConfigType':'{(int)ServerSetting.configCenter.ConfigType}' not support now!"); } LogTextWriter.Write($"最终的配置类型是:{ServerSetting.configCenter.ConfigType}, 最终的配置文件路径是:{configPath}\r\n"); var settingsConfig = settingConfigBuilder.Build(); //加载Nlog配置 NLog.LogManager.Configuration = new NLogLoggingConfiguration(settingsConfig.GetSection("NLog")); logger = LogFactory.CreateLogger <ServerSetting>(); //加载服务配置项 ServerSetting.config = settingsConfig.Get <Configuration>(); ServerSetting.configCenter = config.ServerConfig.ConfigCenter; if (config.ServerConfig.RpcService == null) { string msg = "请检查配置中super.json的配置是否正确,保证子节点RpcService的配置完整...."; logger.LogCritical(msg); Thread.Sleep(1000); throw new Exception(msg); } config.ConfigPath = ServerSetting.configCenter.Ip; getLocalIp(); }