protected override void After_all_tests()
        {
            base.After_all_tests();

            Runner.Dispose();
            Runner = null;
        }
Example #2
0
 public WishModel()
 {
     _runspace = RunspaceFactory.CreateRunspace();
     _runspace.Open();
     _runner = new Powershell(_runspace);
     _repl = new Repl(_runner);
 }
Example #3
0
		public XmlResultWriter (IRunner runner, string fileName)
			: base (runner, fileName)
		{
			writer = XmlWriter.Create (
				CreateWriterFor (fileName),
				new XmlWriterSettings { Indent = true, CloseOutput = true, CheckCharacters = false });
		}
        private static void FillSectionMap(IRunner runner)
        {
            SectionMap = new Dictionary<string, Section>();

            // We may later read the current directory for dlls to load
            // 3rd party section handler modules but right now
            // there is not such a requirement

            // get types inherited from Section
            var types =
                typeof(Section).Assembly.
                GetTypes().
                Where(t => typeof(Section).IsAssignableFrom(t)).
                ToArray();

            foreach (var type in types)
            {
                var heading = type.GetCustomAttributes(
                        typeof(SectionHeaderAttribute),
                        inherit: false).
                    OfType<SectionHeaderAttribute>().
                    FirstOrDefault();

                // only accept Sections types which have SectionHeader attribute
                if (heading != null)
                {
                    var instance = Activator.CreateInstance(type) as Section;
                    instance.Runner = runner;
                    // cache the concrete section handler
                    SectionMap.Add("[" + heading.Header.ToLower() + "]", instance);
                }
            }
        }
 public RunController(IDbContext context, ICompiler compiler, IRunner runner, Participant participant = null)
 {
     _context = context;
     _compiler = compiler;
     _runner = runner;
     _participant = participant == null ? GetCurrentParticipant() : participant;
 }
 public ScoresController(IDbContext context, ICompiler compiler, IRunner runner, Participant participant = null)
 {
     _context = context;
     _compiler = compiler;
     _runner = runner;
     _participant = participant ?? GetCurrentParticipant();
 }
		public TextResultWriter (IRunner runner, string fileName)
			: base (runner, fileName)
		{
			if ((fileName == null) || (fileName.Length == 0)) {
				writer = System.Console.Out;

				string color_override = Environment.GetEnvironmentVariable ("GENDARME_COLOR") ?? "dark";
				switch (color_override.ToLowerInvariant ()) {
				case "none":
					color_scheme = ColorScheme.None;
					break;
				case "light":
					color_scheme = ColorScheme.Light;
					break;
				case "dark":
				default:
					color_scheme = ColorScheme.Dark;
					break;
				}
			} else {
				color_scheme = ColorScheme.None;
				writer = new StreamWriter (fileName);
				need_closing = true;
			}
		}
Example #8
0
		public IgnoreFileList (IRunner runner, string fileName)
			: base (runner)
		{
			if (!String.IsNullOrEmpty (fileName) && File.Exists (fileName)) {
				Parse (fileName);
			}
		}
		public XmlResultWriter (IRunner runner, string fileName)
			: base (runner, fileName)
		{
			if ((fileName == null) || (fileName.Length == 0))
				writer = new XmlTextWriter (System.Console.Out);
			else
				writer = new XmlTextWriter (fileName, Encoding.UTF8);
		}
Example #10
0
 public RunnerFactory(ICategoryFinderService categoryFinderService,
     IResultsParser resultsParser,
     IRunner runner)
 {
     _categoryFinderService = categoryFinderService;
     _resultsParser = resultsParser;
     _runner = runner;
 }
 /// <summary>
 /// Constructor for the updater
 /// </summary>
 /// <param name="index"></param>
 /// <param name="createDate"></param>
 /// <param name="description"></param>
 /// <param name="createBy"></param>
 /// <param name="runner"></param>
 public UpdatesMetadata(double index, string createDate, string description, string createBy, IRunner runner)
 {
     _index = index;
     _createDate = createDate;
     _description = description;
     _createBy = createBy;
     _runner = runner;
 }
Example #12
0
 public ProgramTests()
 {
     _mockArgParser = new MockArgumentParser();
       _mockRunner = new MockRunner();
       _mockSqlResult = new MockSqlResult();
       ((MockSqlResult)_mockSqlResult).ExpectedTextOutput = "formatted text";
       _testProgram = new Program(_mockArgParser, _mockRunner);
 }
Example #13
0
        public ServiceRunner(ISettingsRunnable settings, IRunner runner, string threadName, bool autoStart = false)
        {
            _settings = settings;
            _runnableObject = runner;
            _threadName = threadName;

            if (autoStart)
                Start();
        }
		public override void Initialize (IRunner runner)
		{
			base.Initialize (runner);

			//check if this is a Boo assembly using macros
			Runner.AnalyzeAssembly += delegate (object o, RunnerEventArgs e) {
				IsBooAssemblyUsingMacro = (e.CurrentAssembly.MainModule.HasTypeReference (BooMacroStatement));
			};
		}
Example #15
0
		internal PausableTask(IEnumerator enumerator, IRunner runner)
		{
            if (enumerator is SingleTask || enumerator is PausableTask || enumerator is AsyncTask)
				throw new ArgumentException("Use of incompatible Enumerator, cannot be SingleTask/PausableTask/AsyncTask");

            _enumerator = enumerator;
			
			_runner = runner;
		}
		public override void Initialize (IRunner runner)
		{
			base.Initialize (runner);

			// Nullable cannot be used if the assembly target runtime is earlier than 2.0
			Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
				Active = (e.CurrentModule.Runtime >= TargetRuntime.Net_2_0);
			};
		}
        public PausableTask(IEnumerator enumerator, IRunner runner)
        {
            if (enumerator is SingleTask || enumerator is PausableTask || enumerator is AsyncTask)
                throw new ArgumentException("Internal task used outside the framework scope");

            _enumerator = enumerator;

            _runner = runner;
        }
        public void SetUp()
        {
            _contextMock = new Mock<IDbContext>();

            _compiler = new TestCompiler();
            _runner = new TestRunner();
            _participant = new Participant { Email = "", Id = 12 };
            _controller = new RunController(_contextMock.Object, _compiler, _runner, _participant);
        }
		public override void Initialize (IRunner runner)
		{
			base.Initialize (runner);

			// avoid checking all methods unless the type has some properties
			Runner.AnalyzeType += delegate (object o, RunnerEventArgs e) {
				Active = e.CurrentType.HasProperties;
			};
		}
		public override void Initialize (IRunner runner)
		{
			base.Initialize (runner);

			Runner.AnalyzeType += (object sender, RunnerEventArgs e) =>
			{
				Active = e.CurrentType.Implements ("Gendarme.Framework", "IRule");
			};
		}
		public override void Initialize (IRunner runner)
		{
			base.Initialize (runner);

			Runner.AnalyzeModule += (object o, RunnerEventArgs e) => {
				Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
				e.CurrentModule.HasTypeReference ("System.ArgIterator"));
			};
		}
Example #22
0
File: Profile.cs Project: neiz/Wish
 public Profile(IRunner runner)
 {
     _runner = runner;
     _home = Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%");
     if (string.IsNullOrEmpty(_home)) return;
     _profile = Path.Combine(_home, RcFile);
     var fi = new FileInfo(_profile);
     Exists = fi.Exists;
 }
		public override void Initialize (IRunner runner)
		{
			base.Initialize (runner);
			// extension methods are only available in FX3.5
			// check runtime >= NET2_0 (fast) then check if [ExtensionAttribute] is referenced
			Runner.AnalyzeModule += (object o, RunnerEventArgs e) => {
				Active = e.CurrentModule.Runtime >= TargetRuntime.Net_2_0 &&
					e.CurrentModule.HasTypeReference ("System.Runtime.CompilerServices.ExtensionAttribute");
			};
		}
Example #24
0
        private string GetSubject(Mapping map, BuildData build, IRunner runner)
        {
            string errorMessage = "Success: ";
            if (runner.ErrorOccured)
            {
                errorMessage = "Failed: ";
            }

            return string.Format("{0} TfsDeployer Ran Script {1} on Machine {2} for {3}/{4}/{5}",errorMessage, map.Script, map.Computer, build.TeamProject, build.BuildType, build.BuildNumber);
        }
		public override void Initialize (IRunner runner)
		{
			base.Initialize (runner);

			// Static type exists only since 2.0 so there's no point to execute this
			// rule on every type if the assembly target runtime is earlier than 2.0
			Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
				Active = (e.CurrentModule.Runtime >= TargetRuntime.Net_2_0);
			};
		}
		public override void Initialize (IRunner runner)
		{
			base.Initialize (runner);

			// we only want to run this on assemblies that use 2.0 or later
			// since String.IsNullOrEmpty did not exist before that
			Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
				Active = (e.CurrentModule.Runtime >= TargetRuntime.Net_2_0);
			};
		}
		public override void Initialize (IRunner runner)
		{
			base.Initialize (runner);

			// we only want to run this on assemblies that use 2.0 or later
			// since generics were not available before
			Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
				Active = (e.CurrentModule.Runtime >= TargetRuntime.Net_2_0);
			};
		}
		public override void Initialize (IRunner runner)
		{
			base.Initialize (runner);

			// if the module does not reference System.BitConverter then no
			// method inside it will be calling any BitConverter.Int64BitsToDouble method
			Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
				Active = (e.CurrentAssembly.Name.Name == "mscorlib") ||
					e.CurrentModule.HasTypeReference (BitConverter);
			};
		}
Example #29
0
 private string GetBody(Mapping map, BuildData build, IRunner runner)
 {
     StringBuilder builder = new StringBuilder();
     builder.AppendLine(string.Format("Team Project/Build: {0} to {1}",build.TeamProject,build.BuildType));
     builder.AppendLine(string.Format("Quality Change: {0} to {1}",map.OriginalQuality,map.NewQuality));
     builder.AppendLine(string.Format("Drop Location: {0}", build.DropLocation));
     builder.AppendLine(string.Format("Build Uri: {0}", build.BuildUri));
     builder.AppendLine(string.Format("Script: {0}", runner.ScriptRun));
     builder.AppendLine(string.Format("Output: {0}", runner.Output));
     return builder.ToString();
 }
		public override void Initialize (IRunner runner)
		{
			base.Initialize (runner);

			Runner.AnalyzeModule += (object o, RunnerEventArgs e) => {
				Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
					e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
						return tr.IsNamed ("System", "ArgIterator");
					}));
			};
		}
 public RunManager(
     IScheduleReader <TIdentifier> scheduleReader,
     ITaskDefinitionReader <TIdentifier> taskDefinitionReader,
     IRunner <TIdentifier> runner,
     IHistoryWriter <TIdentifier> historyWriter,
     IScheduleWriter <TIdentifier> scheduleWriter,
     IPreconditionReader <TIdentifier> preconditionReader,
     IDueTasksFilter <TIdentifier> dueTasksFilter,
     IHistoryReader <TIdentifier> historyReader,
     IServiceScopeFactory serviceScopeFactory,
     ILogger <RunManager <TIdentifier> > logger,
     IInbuiltTaskPreconditionsProvider <TIdentifier> inbuiltTaskPreconditionsProvider,
     ITaskDefinitionStateReader <TIdentifier> taskDefinitionStateReader,
     ITaskDefinitionStateWriter <TIdentifier> taskDefinitionStateWriter,
     IFaultHandler <TIdentifier> faultHandler,
     IFaultReporter <TIdentifier> faultReporter,
     IOnDemandQueueManager <TIdentifier> onDemandQueueManager,
     ITaskRunnerLogger taskRunnerLogger)
 {
     this.scheduleReader       = scheduleReader;
     this.taskDefinitionReader = taskDefinitionReader;
     this.runner              = runner;
     this.historyWriter       = historyWriter;
     this.scheduleWriter      = scheduleWriter;
     this.preconditionReader  = preconditionReader;
     this.dueTasksFilter      = dueTasksFilter;
     this.historyReader       = historyReader;
     this.serviceScopeFactory = serviceScopeFactory;
     Logger = logger;
     this.inbuiltTaskPreconditionsProvider = inbuiltTaskPreconditionsProvider;
     this.taskDefinitionStateReader        = taskDefinitionStateReader;
     this.taskDefinitionStateWriter        = taskDefinitionStateWriter;
     this.faultHandler         = faultHandler;
     this.faultReporter        = faultReporter;
     this.onDemandQueueManager = onDemandQueueManager;
     this.taskRunnerLogger     = taskRunnerLogger;
 }
Example #32
0
        public NullDerefFrame(int maxStackDepth, int numLocals, int numArgs, bool entry, [NonNull] IRunner runner)
        {
            int i;

            stackDepth = 0;
            stack      = new Nullity[maxStackDepth];
            locals     = new Nullity[numLocals];
            args       = new Nullity[numArgs];
            for (i = 0; i < maxStackDepth; i++)
            {
                stack[i] = Nullity.Unused;
            }

            if (entry)
            {
                for (i = 0; i < numLocals; i++)
                {
                    locals[i] = Nullity.Null;
                }
                for (i = 0; i < numArgs; i++)
                {
                    args[i] = Nullity.Unknown;
                }
            }
            else
            {
                for (i = 0; i < numLocals; i++)
                {
                    locals[i] = Nullity.Unused;
                }
                for (i = 0; i < numArgs; i++)
                {
                    args[i] = Nullity.Unused;
                }
            }
            this.runner = runner;
        }
Example #33
0
        protected override void OnStart(string[] args)
        {
            _logger.InfoFormat("Starting {0} service.", ApplicationParameters.name);
            try
            {
                InitializeIOC(args);
                IRunner runner = infrastructure.containers.Container.get_an_instance_of <IRunner>();
                runner.run_the_application();

                _logger.InfoFormat("{0} service is now actively monitoring.", ApplicationParameters.name);

                if ((args.Length > 0) && (Array.IndexOf(args, "/console") != -1))
                {
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey();
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorFormat("{0} service had an error on {1} (with user {2}):{3}{4}", ApplicationParameters.name,
                                    Environment.MachineName, Environment.UserName,
                                    Environment.NewLine, ex.ToString());
            }
        }
        public override void Initialize(IRunner runner)
        {
            base.Initialize(runner);

            Runner.AnalyzeModule += delegate(object o, RunnerEventArgs e)
            {
                string assembly_name       = e.CurrentAssembly.Name.Name;
                bool   usingRegexClass     = (assembly_name == "System");
                bool   usingValidatorClass = (e.CurrentModule.Runtime >= TargetRuntime.Net_2_0) && (assembly_name == "System.Configuration");
                // if we're not analyzing System.dll or System.Configuration.dll then check if we're using them
                if (!usingRegexClass && !usingValidatorClass)
                {
                    Active = e.CurrentModule.AnyTypeReference((TypeReference tr) =>
                    {
                        return(tr.IsNamed("System.Text.RegularExpressions", "Regex") ||
                               tr.IsNamed("System.Configuration", "RegexStringValidator"));
                    });
                }
                else
                {
                    Active = true;
                }
            };
        }
        public StrategyResultsStatsViewModel(IStrategy strategy, IRunner runner)
        {
            _runner    = runner;
            _strategy  = strategy;
            HasResults = true;

            TradeCount           = $"{strategy.Stats.TradeCount}";
            Wins                 = $"{strategy.Stats.Wins}";
            Loses                = $"{strategy.Stats.Loses}";
            LongestWinningStreak = $"{strategy.Stats.LongestWinningStreak}";
            LongestLosingStreak  = $"{strategy.Stats.LongestLosingStreak}";
            PointsProfit         = $"{strategy.Stats.PointsTotal:N1}";
            CashProfit           = $"{strategy.Stats.CashProfit:N1}";
            BiggestWin           = $"{strategy.Stats.BiggestCashWin:N1}";

            AverageLoss = double.IsNaN(strategy.Stats.AveragePointsLoss)
                ? "---"
                : $"{strategy.Stats.AveragePointsLoss:N1}";

            AverageWin = double.IsNaN(strategy.Stats.AverageCashWin)
                ? "---"
                : $"{strategy.Stats.AverageCashWin:N1}";

            WinProbability = double.IsNaN(strategy.Stats.WinProbability)
                ? "---"
                : $"{strategy.Stats.WinProbability:P}";

            ProfitFactor = double.IsNaN(strategy.Stats.ProfitFactor) ||
                           double.IsInfinity(strategy.Stats.ProfitFactor)
                ? "---"
                : $"{strategy.Stats.ProfitFactor:N1}";

            Expectancy = double.IsNaN(strategy.Stats.Expectancy)
                ? "---"
                : $"{strategy.Stats.Expectancy:N1}";
        }
Example #36
0
 public Experiment(MLContext context,
                   TaskKind task,
                   OptimizingMetricInfo metricInfo,
                   IProgress <TRunDetail> progressCallback,
                   ExperimentSettings experimentSettings,
                   IMetricsAgent <TMetrics> metricsAgent,
                   IEnumerable <TrainerName> trainerAllowList,
                   DatasetColumnInfo[] datasetColumnInfo,
                   IRunner <TRunDetail> runner,
                   IChannel logger)
 {
     _context = context;
     _history = new List <SuggestedPipelineRunDetail>();
     _optimizingMetricInfo = metricInfo;
     _task               = task;
     _progressCallback   = progressCallback;
     _experimentSettings = experimentSettings;
     _metricsAgent       = metricsAgent;
     _trainerAllowList   = trainerAllowList;
     _modelDirectory     = GetModelDirectory(_experimentSettings.CacheDirectory);
     _datasetColumnInfo  = datasetColumnInfo;
     _runner             = runner;
     _logger             = logger;
 }
        internal override async Task <ExceptionDispatchInfo?> InvokeAsync(IRunner runner, CancellationToken cancellationToken)
        {
            ExceptionDispatchInfo?info = null;

            await runner.RunAsync(() =>
            {
                try
                {
                    if (this._serviceProvider is null)
                    {
                        throw new ArgumentNullException(nameof(this._serviceProvider), $"The provided service provider was null by the time this {nameof(PulumiFn)} was invoked.");
                    }

                    return(this._serviceProvider.GetService(this._stackType) as Pulumi.Stack
                           ?? throw new ApplicationException(
                               $"Failed to resolve instance of type {this._stackType.FullName} from service provider. Register the type with the service provider before this {nameof(PulumiFn)} is invoked."));
                }
                // because we are newing a generic, reflection comes in to
                // construct the instance. And if there is an exception in
                // the constructor of the user-provided TStack, it will be wrapped
                // in TargetInvocationException - which is not the exception
                // we want to throw to the consumer.
                catch (TargetInvocationException ex) when(ex.InnerException != null)
                {
                    info = ExceptionDispatchInfo.Capture(ex.InnerException);
                    throw;
                }
                catch (Exception ex)
                {
                    info = ExceptionDispatchInfo.Capture(ex);
                    throw;
                }
            }).ConfigureAwait(false);

            return(info);
        }
Example #38
0
        static void Main(string[] args)
        {
            // error -- IRunner i1 = new IRunner();

            IRunner i1 = new SportMan("dudi");


            Sofa s = new Sofa();

            PaintFurn(s);
            Fence f = new Fence();

            // error: PaintFurn(f);
            PaintIPaint(f);

            Circle c = new Circle();

            Draw3D(c);
            Person p = new Person();
            // Draw3D(p);

            SportMan sportMan = new SportMan("nahum");

            sportMan.Run();
            sportMan.GetName();
            sportMan.ToString();

            IRunner runner = sportMan;

            // object
            // Run (IRunner)
            runner.Run();

            object sp_obj     = sportMan;
            object circle_obj = c;
        }
        public override void Initialize(IRunner runner)
        {
            base.Initialize(runner);

            // get the specified or latest definition file available locally *or*
            // download it if none is present or if gendarme is more recent than the file
            LoadDefinitions(SelectDefinitionsFile());

            // rule is active only if we have, at least one of, the MoMA files
            Active = ((NotImplemented != null) || (Missing != null) || (ToDo != null));

            // MoMA does not support all frameworks, e.g. Silverlight
            Runner.AnalyzeModule += delegate(object o, RunnerEventArgs e) {
                foreach (AssemblyNameReference anr in e.CurrentModule.AssemblyReferences)
                {
                    if (Filter(anr))
                    {
                        Active = true;
                        return;
                    }
                }
                Active = false;
            };
        }
Example #40
0
        public void BuildWithPriorityFunction(IRunnerBuilder builder, IRunner runner, IStageComponentProvider provider, Exception e)
        {
            "Given a runner builder"
            .x(() => builder = new RunnerBuilder());

            "And a stage component provider"
            .x(() => provider = _mockProvider.Object);

            "When building the runner"
            .x(() => e = Record.Exception(() => runner = builder.FindStageRunners(provider).SetStageRunnerPriority(r => (r.Stages & Stages.Discover) == Stages.Discover ? 100 : 10).Build()));

            "Then the build method should succeed"
            .x(() => e.Should().BeNull());

            "And there should be 4 stage runners found in config with correct priorities"
            .x(() =>
            {
                runner.RunState.Should().NotBeNull();
                runner.RunState.Configuration.Should().NotBeNull();
                runner.RunState.Configuration.StageRunners.Should().NotBeNull().And.Subject.Should().HaveCount(4);
                runner.RunState.Configuration.StageRunners.Where(r => r.Priority == 100 && (r.Stages & Stages.Discover) == Stages.Discover).Should().HaveCount(1);
                runner.RunState.Configuration.StageRunners.Where(r => r.Priority == 10 && (r.Stages & Stages.Discover) != Stages.Discover).Should().HaveCount(3);
            });
        }
Example #41
0
        public void BuildWithSkipFunction(IRunnerBuilder builder, IRunner runner, IStageComponentProvider provider, Exception e)
        {
            "Given a runner builder"
            .x(() => builder = new RunnerBuilder());

            "And a stage component provider"
            .x(() => provider = _mockProvider.Object);

            "When building the runner"
            .x(() => e = Record.Exception(() => runner = builder.FindStageRunners(provider).SkipStageRunner(r => (r.Stages & Stages.Discover) == Stages.Discover ? true : false).Build()));

            "Then the build method should succeed"
            .x(() => e.Should().BeNull());

            "And the Discover stage runner only should be set to skip execution"
            .x(() =>
            {
                runner.RunState.Should().NotBeNull();
                runner.RunState.Configuration.Should().NotBeNull();
                runner.RunState.Configuration.StageRunners.Should().NotBeNull().And.Subject.Should().HaveCount(4);
                runner.RunState.Configuration.StageRunners.Where(r => r.Skip && (r.Stages & Stages.Discover) == Stages.Discover).Should().HaveCount(1);
                runner.RunState.Configuration.StageRunners.Where(r => !r.Skip && (r.Stages & Stages.Discover) != Stages.Discover).Should().HaveCount(3);
            });
        }
Example #42
0
 public void Setup()
 {
     runner   = new DefaultAPIRunner();
     reporter = new ConsoleReporter();
 }
Example #43
0
        // Return code definition: (this will be used by service host to determine whether it will re-launch Runner.Listener)
        // 0: Runner exit
        // 1: Terminate failure
        // 2: Retriable failure
        // 3: Exit for self update
        private async static Task <int> MainAsync(IHostContext context, string[] args)
        {
            Tracing trace = context.GetTrace(nameof(GitHub.Runner.Listener));

            trace.Info($"Runner is built for {Constants.Runner.Platform} ({Constants.Runner.PlatformArchitecture}) - {BuildConstants.RunnerPackage.PackageName}.");
            trace.Info($"RuntimeInformation: {RuntimeInformation.OSDescription}.");
            context.WritePerfCounter("RunnerProcessStarted");
            var terminal = context.GetService <ITerminal>();

            // Validate the binaries intended for one OS are not running on a different OS.
            switch (Constants.Runner.Platform)
            {
            case Constants.OSPlatform.Linux:
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    terminal.WriteLine("This runner version is built for Linux. Please install a correct build for your OS.");
                    return(Constants.Runner.ReturnCode.TerminatedError);
                }
                break;

            case Constants.OSPlatform.OSX:
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    terminal.WriteLine("This runner version is built for OSX. Please install a correct build for your OS.");
                    return(Constants.Runner.ReturnCode.TerminatedError);
                }
                break;

            case Constants.OSPlatform.Windows:
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    terminal.WriteLine("This runner version is built for Windows. Please install a correct build for your OS.");
                    return(Constants.Runner.ReturnCode.TerminatedError);
                }
                break;

            default:
                terminal.WriteLine($"Running the runner on this platform is not supported. The current platform is {RuntimeInformation.OSDescription} and it was built for {Constants.Runner.Platform.ToString()}.");
                return(Constants.Runner.ReturnCode.TerminatedError);
            }

            try
            {
                trace.Info($"Version: {BuildConstants.RunnerPackage.Version}");
                trace.Info($"Commit: {BuildConstants.Source.CommitHash}");
                trace.Info($"Culture: {CultureInfo.CurrentCulture.Name}");
                trace.Info($"UI Culture: {CultureInfo.CurrentUICulture.Name}");

                // Validate directory permissions.
                string runnerDirectory = context.GetDirectory(WellKnownDirectory.Root);
                trace.Info($"Validating directory permissions for: '{runnerDirectory}'");
                try
                {
                    IOUtil.ValidateExecutePermission(runnerDirectory);
                }
                catch (Exception e)
                {
                    terminal.WriteError($"An error occurred: {e.Message}");
                    trace.Error(e);
                    return(Constants.Runner.ReturnCode.TerminatedError);
                }

                // Parse the command line args.
                var command = new CommandSettings(context, args);
                trace.Info("Arguments parsed");

                // Up front validation, warn for unrecognized commandline args.
                var unknownCommandlines = command.Validate();
                if (unknownCommandlines.Count > 0)
                {
                    terminal.WriteError($"Unrecognized command-line input arguments: '{string.Join(", ", unknownCommandlines)}'. For usage refer to: .\\config.cmd --help or ./config.sh --help");
                }

                // Defer to the Runner class to execute the command.
                IRunner runner = context.GetService <IRunner>();
                try
                {
                    return(await runner.ExecuteCommand(command));
                }
                catch (OperationCanceledException) when(context.RunnerShutdownToken.IsCancellationRequested)
                {
                    trace.Info("Runner execution been cancelled.");
                    return(Constants.Runner.ReturnCode.Success);
                }
                catch (NonRetryableException e)
                {
                    terminal.WriteError($"An error occurred: {e.Message}");
                    trace.Error(e);
                    return(Constants.Runner.ReturnCode.TerminatedError);
                }
            }
            catch (Exception e)
            {
                terminal.WriteError($"An error occurred: {e.Message}");
                trace.Error(e);
                return(Constants.Runner.ReturnCode.RetryableError);
            }
        }
 public HtmlResultWriter(IRunner runner, string fileName)
     : base(runner, fileName)
 {
     temp_filename = Path.GetTempFileName();
 }
Example #45
0
 public Deployer()
 {
     _reader  = new TfsConfigReader();
     _runner  = null;
     _alerter = new EmailAlerter();
 }
Example #46
0
        protected async Task StartRunners(IConfigProvider configProvider)
        {
            IInitConfig        initConfig        = configProvider.GetConfig <IInitConfig>();
            IJsonRpcConfig     jsonRpcConfig     = configProvider.GetConfig <IJsonRpcConfig>();
            var                metricsParams     = configProvider.GetConfig <IMetricsConfig>();
            var                logManager        = new NLogManager(initConfig.LogFileName, initConfig.LogDirectory);
            IRpcModuleProvider rpcModuleProvider = jsonRpcConfig.Enabled
                ? new RpcModuleProvider(configProvider.GetConfig <IJsonRpcConfig>(), logManager)
                : (IRpcModuleProvider)NullModuleProvider.Instance;
            var jsonSerializer    = new EthereumJsonSerializer();
            var webSocketsManager = new WebSocketsManager();

            INdmDataPublisher          ndmDataPublisher          = null;
            INdmConsumerChannelManager ndmConsumerChannelManager = null;
            INdmInitializer            ndmInitializer            = null;
            var ndmConfig  = configProvider.GetConfig <INdmConfig>();
            var ndmEnabled = ndmConfig.Enabled;

            if (ndmEnabled)
            {
                ndmDataPublisher          = new NdmDataPublisher();
                ndmConsumerChannelManager = new NdmConsumerChannelManager();
                var initializerName = ndmConfig.InitializerName;
                if (Logger.IsInfo)
                {
                    Logger.Info($"NDM initializer: {initializerName}");
                }
                var ndmInitializerType = AppDomain.CurrentDomain.GetAssemblies()
                                         .SelectMany(a => a.GetTypes())
                                         .FirstOrDefault(t =>
                                                         t.GetCustomAttribute <NdmInitializerAttribute>()?.Name == initializerName);
                var ndmModule          = new NdmModule();
                var ndmConsumersModule = new NdmConsumersModule();
                ndmInitializer = new NdmInitializerFactory(ndmInitializerType, ndmModule, ndmConsumersModule,
                                                           logManager).CreateOrFail();
            }

            var        grpcConfig = configProvider.GetConfig <IGrpcConfig>();
            GrpcServer grpcServer = null;

            if (grpcConfig.Enabled)
            {
                grpcServer = new GrpcServer(jsonSerializer, logManager);
                if (ndmEnabled)
                {
                    ndmConsumerChannelManager.Add(new GrpcNdmConsumerChannel(grpcServer));
                }

                _grpcRunner = new GrpcRunner(grpcServer, grpcConfig, logManager);
                await _grpcRunner.Start().ContinueWith(x =>
                {
                    if (x.IsFaulted && Logger.IsError)
                    {
                        Logger.Error("Error during GRPC runner start", x.Exception);
                    }
                });
            }

            if (initConfig.WebSocketsEnabled)
            {
                if (ndmEnabled)
                {
                    webSocketsManager.AddModule(new NdmWebSocketsModule(ndmConsumerChannelManager, ndmDataPublisher,
                                                                        jsonSerializer));
                }
            }

            _ethereumRunner = new EthereumRunner(rpcModuleProvider, configProvider, logManager, grpcServer,
                                                 ndmConsumerChannelManager, ndmDataPublisher, ndmInitializer, webSocketsManager, jsonSerializer);
            await _ethereumRunner.Start().ContinueWith(x =>
            {
                if (x.IsFaulted && Logger.IsError)
                {
                    Logger.Error("Error during ethereum runner start", x.Exception);
                }
            });

            if (jsonRpcConfig.Enabled)
            {
                rpcModuleProvider.Register(new SingletonModulePool <IWeb3Module>(new Web3Module(logManager)));
                var jsonRpcService   = new JsonRpcService(rpcModuleProvider, logManager);
                var jsonRpcProcessor = new JsonRpcProcessor(jsonRpcService, jsonSerializer, logManager);
                if (initConfig.WebSocketsEnabled)
                {
                    webSocketsManager.AddModule(new JsonRpcWebSocketsModule(jsonRpcProcessor, jsonSerializer));
                }

                Bootstrap.Instance.JsonRpcService = jsonRpcService;
                Bootstrap.Instance.LogManager     = logManager;
                Bootstrap.Instance.JsonSerializer = jsonSerializer;
                _jsonRpcRunner = new JsonRpcRunner(configProvider, rpcModuleProvider, logManager, jsonRpcProcessor,
                                                   webSocketsManager);
                await _jsonRpcRunner.Start().ContinueWith(x =>
                {
                    if (x.IsFaulted && Logger.IsError)
                    {
                        Logger.Error("Error during jsonRpc runner start", x.Exception);
                    }
                });
            }
            else
            {
                if (Logger.IsInfo)
                {
                    Logger.Info("Json RPC is disabled");
                }
            }

            if (metricsParams.Enabled)
            {
                var intervalSeconds = metricsParams.IntervalSeconds;
                _monitoringService = new MonitoringService(new MetricsUpdater(intervalSeconds),
                                                           metricsParams.PushGatewayUrl, ClientVersion.Description,
                                                           metricsParams.NodeName, intervalSeconds, logManager);
                await _monitoringService.StartAsync().ContinueWith(x =>
                {
                    if (x.IsFaulted && Logger.IsError)
                    {
                        Logger.Error("Error during starting a monitoring.", x.Exception);
                    }
                });
            }
            else
            {
                if (Logger.IsInfo)
                {
                    Logger.Info("Monitoring is disabled");
                }
            }
        }
Example #47
0
 public RunnerEventArgs(IRunner runner)
 {
     Runner = runner;
 }
Example #48
0
        protected async Task StartRunners(IConfigProvider configProvider)
        {
            IInitConfig        initConfig        = configProvider.GetConfig <IInitConfig>();
            IJsonRpcConfig     jsonRpcConfig     = configProvider.GetConfig <IJsonRpcConfig>();
            IMetricsConfig     metricsConfig     = configProvider.GetConfig <IMetricsConfig>();
            NLogManager        logManager        = new NLogManager(initConfig.LogFileName, initConfig.LogDirectory);
            IRpcModuleProvider rpcModuleProvider = jsonRpcConfig.Enabled
                ? new RpcModuleProvider(configProvider.GetConfig <IJsonRpcConfig>(), logManager)
                : (IRpcModuleProvider)NullModuleProvider.Instance;
            EthereumJsonSerializer jsonSerializer    = new EthereumJsonSerializer();
            WebSocketsManager      webSocketsManager = new WebSocketsManager();

            if (!string.IsNullOrEmpty(metricsConfig.NodeName))
            {
                logManager.SetGlobalVariable("nodeName", metricsConfig.NodeName);
            }

            if (metricsConfig.Enabled)
            {
                Metrics.Version = VersionToMetrics.ConvertToNumber(ClientVersion.Version);
                MetricsUpdater metricsUpdater = new MetricsUpdater(metricsConfig);
                _monitoringService = new MonitoringService(metricsUpdater, metricsConfig, logManager);
                _monitoringService.RegisterMetrics(typeof(Nethermind.Blockchain.Metrics));
                _monitoringService.RegisterMetrics(typeof(Nethermind.Db.Metrics));
                _monitoringService.RegisterMetrics(typeof(Nethermind.Evm.Metrics));
                _monitoringService.RegisterMetrics(typeof(Nethermind.JsonRpc.Metrics));
                _monitoringService.RegisterMetrics(typeof(Nethermind.Trie.Metrics));
                _monitoringService.RegisterMetrics(typeof(Nethermind.Network.Metrics));
                _monitoringService.RegisterMetrics(typeof(Nethermind.Synchronization.Metrics));
                _monitoringService.RegisterMetrics(typeof(Nethermind.TxPool.Metrics));
                _monitoringService.RegisterMetrics(typeof(Metrics));

                await _monitoringService.StartAsync().ContinueWith(x =>
                {
                    if (x.IsFaulted && (_logger?.IsError ?? false))
                    {
                        _logger !.Error("Error during starting a monitoring.", x.Exception);
                    }
                });
            }
            else
            {
                if (_logger?.IsInfo ?? false)
                {
                    _logger !.Info("Grafana / Prometheus metrics are disabled in configuration");
                }
            }

            IGrpcConfig grpcConfig = configProvider.GetConfig <IGrpcConfig>();
            GrpcServer? grpcServer = null;

            if (grpcConfig.Enabled)
            {
                grpcServer  = new GrpcServer(jsonSerializer, logManager);
                _grpcRunner = new GrpcRunner(grpcServer, grpcConfig, logManager);
                await _grpcRunner.Start().ContinueWith(x =>
                {
                    if (x.IsFaulted && (_logger?.IsError ?? false))
                    {
                        _logger !.Error("Error during GRPC runner start", x.Exception);
                    }
                });
            }

            INdmDataPublisher?         ndmDataPublisher          = null;
            INdmConsumerChannelManager?ndmConsumerChannelManager = null;
            INdmInitializer?           ndmInitializer            = null;
            INdmConfig ndmConfig  = configProvider.GetConfig <INdmConfig>();
            bool       ndmEnabled = ndmConfig.Enabled;

            if (ndmEnabled)
            {
                ndmDataPublisher          = new NdmDataPublisher();
                ndmConsumerChannelManager = new NdmConsumerChannelManager();
                string initializerName = ndmConfig.InitializerName;
                if (_logger?.IsInfo ?? false)
                {
                    _logger !.Info($"NDM initializer: {initializerName}");
                }
                Type ndmInitializerType = AppDomain.CurrentDomain.GetAssemblies()
                                          .SelectMany(a => a.GetTypes())
                                          .FirstOrDefault(t =>
                                                          t.GetCustomAttribute <NdmInitializerAttribute>()?.Name == initializerName);
                NdmModule          ndmModule          = new NdmModule();
                NdmConsumersModule ndmConsumersModule = new NdmConsumersModule();
                ndmInitializer = new NdmInitializerFactory(ndmInitializerType, ndmModule, ndmConsumersModule, logManager).CreateOrFail();

                if (grpcServer != null)
                {
                    ndmConsumerChannelManager.Add(new GrpcNdmConsumerChannel(grpcServer));
                }

                webSocketsManager.AddModule(new NdmWebSocketsModule(ndmConsumerChannelManager, ndmDataPublisher, jsonSerializer));
            }

            _ethereumRunner = new EthereumRunner(
                rpcModuleProvider,
                configProvider,
                logManager,
                grpcServer,
                ndmConsumerChannelManager,
                ndmDataPublisher,
                ndmInitializer,
                webSocketsManager,
                jsonSerializer,
                _monitoringService);

            await _ethereumRunner.Start().ContinueWith(x =>
            {
                if (x.IsFaulted && (_logger?.IsError ?? false))
                {
                    _logger !.Error("Error during ethereum runner start", x.Exception);
                }
            });

            if (jsonRpcConfig.Enabled)
            {
                rpcModuleProvider.Register(new SingletonModulePool <IWeb3Module>(new Web3Module(logManager), true));
                JsonRpcService   jsonRpcService   = new JsonRpcService(rpcModuleProvider, logManager);
                JsonRpcProcessor jsonRpcProcessor = new JsonRpcProcessor(jsonRpcService, jsonSerializer, jsonRpcConfig, new FileSystem(), logManager);
                if (initConfig.WebSocketsEnabled)
                {
                    webSocketsManager.AddModule(new JsonRpcWebSocketsModule(jsonRpcProcessor, jsonSerializer), true);
                }

                Bootstrap.Instance.JsonRpcService = jsonRpcService;
                Bootstrap.Instance.LogManager     = logManager;
                Bootstrap.Instance.JsonSerializer = jsonSerializer;
                _jsonRpcRunner = new JsonRpcRunner(configProvider, rpcModuleProvider, logManager, jsonRpcProcessor, webSocketsManager);
                await _jsonRpcRunner.Start().ContinueWith(x =>
                {
                    if (x.IsFaulted && (_logger?.IsError ?? false))
                    {
                        _logger !.Error("Error during jsonRpc runner start", x.Exception);
                    }
                });
            }
            else
            {
                if (_logger?.IsInfo ?? false)
                {
                    _logger !.Info("Json RPC is disabled");
                }
            }
        }
Example #49
0
 /// <inheritdoc/>
 internal override Task <int> InvokeAsync(IRunner runner, CancellationToken cancellationToken)
 => runner.RunAsync(this._stackFactory);
 public ArtistQuery(IRunner runner)
 {
     _runner = runner;
 }
Example #51
0
 public void Start()
 {
     mRunner = ServiceLocator.GetService <IRunner> ();
 }
Example #52
0
 public IEnumerator ThreadSafeRunOnSchedule(IRunner runner, IEnumerator task)
 {
     return(_taskPool.RetrieveTaskFromPool().SetScheduler(runner).SetEnumerator(task).ThreadSafeStart());
 }
Example #53
0
 public Cmd(IRunner runner = null)
 {
     Runner = runner ?? Shell.Default;
     Runner.EnvironmentVariables = new Dictionary <string, string>();
 }
Example #54
0
 internal TaskRoutinePool(IRunner runner)
 {
     _runner = runner;
 }
Example #55
0
 public IEnumerator ThreadSafeRunOnSchedule(IRunner runner, Func <IEnumerator> taskGenerator)
 {
     return(_taskPool.RetrieveTaskFromPool().SetScheduler(runner).SetEnumeratorProvider(taskGenerator).ThreadSafeStart());
 }
Example #56
0
 public CmdCommandoTests()
 {
     _runner = Substitute.For <IRunner>();
     _runner.GetCommand().Returns(new CmdCommando(_runner));
     cmd = new Cmd(_runner);
 }
Example #57
0
 /// <summary>
 /// Public Contructor of Deployer
 /// </summary>
 /// <param name="runnerToUser"></param>
 /// <param name="reader"></param>
 public Deployer(IRunner runnerToUser, IConfigurationReader reader)
 {
     _runner = runnerToUser;
     _reader = reader;
 }
Example #58
0
 /// <inheritdoc/>
 internal override Task <int> InvokeAsync(IRunner runner, CancellationToken cancellationToken)
 => runner.RunAsync(() => this._program(cancellationToken), null);
 public EngineController(IRunner runner)
 {
     Runner  = runner;
     engines = new Dictionary <string, Engine> ();
 }
Example #60
0
 void OnRunnerConnected(IRunner runnerClient)
 {
     this.Runners.Add(runnerClient);
 }