Ejemplo n.º 1
0
        public void Collect(Server server)
        {
            if (!IsValid(server))
            {
                return;
            }

            _shellService = new PowerShellService(server.Name, server.Credential.Username, server.Credential.Password);

            _shellService.Invoke(shell =>
            {
                var username         = server.GetAdditional <string>(AdditionalConstant.MongoUsername);
                var password         = server.GetAdditional <string>(AdditionalConstant.MongoPassword);
                var database         = server.GetAdditional <string>(AdditionalConstant.MongoDatabase);
                var authenticationDb = server.GetAdditional <string>(AdditionalConstant.MongoAuthenticationDatabase);
                var cmd = string.Format(@"(mongo.exe --quiet -eval 'db.runCommand( {{ serverStatus: 1, repl: 0, metrics: 0, locks: 0 }} )' -u '{0}' -p '{1}' -authenticationDatabase '{2}' {3}/{4})", username, password, authenticationDb, server.Name, database);

                shell.AddScript(cmd);

                var result = shell.Invoke();
                if (result != null && result.Any())
                {
                    var resultString = string.Join("\n", result.Select(x => x.ToString()));
                    var resultObj    = BsonSerializer.Deserialize <MongoInfo>(resultString);
                    if (resultObj != null)
                    {
                        resultObj.Reference = server.Name;
                        server.CollectedData.AddOrUpdate(DataCollector.MongoDbInfo, resultObj);
                        _mongoInfoRepository.Save(resultObj);
                    }
                }
            });
        }
Ejemplo n.º 2
0
        public void Collect(Server server)
        {
            _shellService = new PowerShellService(server.Name, server.Credential.Username, server.Credential.Password);

            var files = new List <string>
            {
                "SystemInfo.ps1"
            };

            _shellService.Invoke(shell =>
            {
                _shellService.LoadFilesIntoShell(shell, files);
                var results = shell.Invoke();

                var convertedResult = _shellService.ConvertResult(results.ToList(), obj =>
                {
                    return(JsonConvert.DeserializeObject <ServerInfo>(obj.ToString()));
                });

                var result = convertedResult != null ? convertedResult.FirstOrDefault() : null;
                if (result != null)
                {
                    result.Reference = server.Name;
                    server.CollectedData.AddOrUpdate(DataCollector.SystemInfo, result);
                    _serverInfoRepository.Save(result);
                }
            }, AppConfiguration.Configuration.AppState == AppState.Release);
        }
        public ReportItem CureIssue(Server server, string input, ReportItem context)
        {
            _shellService = new PowerShellService(server.Name, server.Credential.Username,
                                                  server.Credential.Password);

            _shellService.Invoke(shell =>
            {
                shell.AddScript(string.Format(CommandTemplate, input));

                var result = shell.Invoke();
                if (shell.HadErrors)
                {
                    context.State       = ReportItemState.Failure;
                    context.Header      = FailedMessage;
                    context.Elaboration = string.Join("\n", _shellService.GetErrorsFromShell(shell));
                }
                else
                {
                    context.State  = ReportItemState.Warning;
                    context.Header = SuccessMessage;
                }
            }, AppConfiguration.Configuration.AppState == AppState.Release);

            return(context);
        }
Ejemplo n.º 4
0
        public void Collect(Server server)
        {
            if (IsValidRedisServer(server))
            {
                _shellService = new PowerShellService(server.Name, server.Credential.Username, server.Credential.Password);

                _shellService.Invoke(shell =>
                {
                    var name     = server.Name;
                    var port     = server.GetAdditional <int>(Constants.AdditionalConstant.RedisPort);
                    var password = server.GetAdditional <string>(Constants.AdditionalConstant.RedisPassword);
                    shell.AddScript(string.Format("redis-cli.exe -h {0} -p {1} -a {2} INFO",
                                                  name,
                                                  port,
                                                  password));
                    var results = shell.Invoke();
                    var info    = ConvertInfoFromRaw(results.ToList());

                    shell.Commands.Clear();
                    shell.AddScript(string.Format("redis-cli.exe -h {0} -p {1} -a {2} CLIENT LIST",
                                                  name,
                                                  port,
                                                  password));
                    results = shell.Invoke();
                    ConvertClientList(results.ToList(), info);

                    if (info != null)
                    {
                        info.Reference = server.Name;
                        _redisInfoRepository.Save(info);
                        server.CollectedData.AddOrUpdate(Enums.DataCollector.RedisInfo, info);
                    }
                });
            }
        }
Ejemplo n.º 5
0
        public ReportItem Run(Server server, ReportItem context)
        {
            context.Header = Name;

            if (GetTestInput(server) == null || !GetTestInput(server).Any())
            {
                context.Delete = true;
                return(context);
            }

            var shellService = new PowerShellService(server.Name, server.Credential.Username, server.Credential.Password);

            shellService.Invoke(shell =>
            {
                foreach (var input in GetTestInput(server))
                {
                    try
                    {
                        var executableScript = ConvertToExecutableScript.Invoke(input);
                        shellService.LoadFilesIntoShell(shell, ScriptFiles);
                        if (!string.IsNullOrEmpty(executableScript))
                        {
                            shell.AddScript(executableScript);
                        }
                        var results = shell.Invoke().ToList();

                        var convertedResult = shellService.ConvertResult(results, obj => Converter.Invoke(obj));
                        var state           = convertedResult.FirstOrDefault();
                        var message         = context.Create(string.Format(MessageTemplate, input, state));
                        message.State       = EvaluateResult(state) ? ReportItemState.Success : ReportItemState.Failure;
                        if (shell.HadErrors)
                        {
                            message.Elaboration = string.Join("\n", shellService.GetErrorsFromShell(shell));
                        }

                        if (message.State == ReportItemState.Failure && AppConfiguration.Configuration.CureTestIssues &&
                            _cure != null)
                        {
                            var cureContext = message.Create();
                            _cure.CureIssue(server, input, cureContext);
                            cureContext.Update();
                        }
                        message.Update();
                    }
                    catch (Exception e)
                    {
                        var message         = context.Create(string.Format(MessageTemplate, input, ""));
                        message.Elaboration = e.Message;
                        message.State       = ReportItemState.Failure;
                        message.Update();
                    }
                }
                context.Update();
            }, AppConfiguration.Configuration.AppState == AppState.Release);

            return(context);
        }
Ejemplo n.º 6
0
 public void Stop()
 {
     foreach (var worker in _workers)
     {
         try
         {
             worker.Stop();
         }
         catch { }
     }
     PowerShellService.Dispose();
 }
Ejemplo n.º 7
0
        public HttpResponseMessage GetExecuteScript(String script = "")
        {
            PowerShellService ctrl = new PowerShellService();

            // 스크립트 실행 및 리턴값 받아오기
            JObject returnJObj = ctrl.powerShellScript(script);

            var response = Request.CreateResponse(HttpStatusCode.OK, returnJObj);

            response.Headers.Add("Content", "Application/json");

            log.Debug("powershell/execute 호출");
            return(response);
        }
        public void ShouldExecuteAsync()
        {
            var fi = new FileInfo(".\\TestFile1.ps1");

            var mre = new ManualResetEvent(false);

            _debugger.DebuggingFinished += (sender, args) => mre.Set();

            PowerShellService srv = new PowerShellService();

            srv.Engine = new TestExecutionEngine(_debugger);

            srv.ExecutePowerShellCommandAsync(string.Format(". \"{0}\"", fi.FullName));

            Assert.IsTrue(mre.WaitOne(5000));

            var var1 = PowerShellDebuggingService.Runspace.SessionStateProxy.GetVariable("var1");
            var var2 = PowerShellDebuggingService.Runspace.SessionStateProxy.GetVariable("var2");

            Assert.AreEqual("execution", var1);
            Assert.AreEqual("engine", var2);
        }
        public void ShouldOuputWithCustomOutputAction()
        {
            var fi = new FileInfo(".\\TestFile1.ps1");

            var mre = new ManualResetEvent(false);

            _debugger.DebuggingFinished += (sender, args) => mre.Set();

            string            outputString = null;
            PowerShellService srv          = new PowerShellService();

            srv.Engine = new TestExecutionEngine(_debugger);

            srv.ExecutePowerShellCommand(string.Format(". \"{0}\"", fi.FullName), x =>
            {
                outputString += x;
            });

            Assert.IsTrue(mre.WaitOne(5000));

            Assert.AreEqual("Hey\n\r\n", outputString);
        }
Ejemplo n.º 10
0
        public void Collect(Server server)
        {
            _shellService = new PowerShellService(server.Name, server.Credential.Username, server.Credential.Password);

            _shellService.Invoke(shell =>
            {
                ServerUtilization result = null;
                try
                {
                    _shellService.LoadFilesIntoShell(shell, new List <string>
                    {
                        "Get-Server-Utilization.ps1"
                    });

                    var cmdResult = shell.Invoke();
                    result        = JsonConvert.DeserializeObject <ServerUtilization>(cmdResult.First().ToString());
                }
                catch
                {
                    result = new ServerUtilization
                    {
                        NetworkUtilization = new NetworkUtilization()
                    };
                }

                if (result != null)
                {
                    if (result.NetworkUtilization == null)
                    {
                        shell.Commands.Clear();
                        shell.AddScript("Restart-Service winmgmt -Force");
                        shell.Invoke();
                    }
                    result.Reference = server.Name;
                    _repository.Save(result);
                }
            });
        }
Ejemplo n.º 11
0
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            await base.InitializeAsync(cancellationToken, progress);

            // When initialized asynchronously, we *may* be on a background thread at this point.
            // Do any initialization that requires the UI thread after switching to the UI thread.
            // Otherwise, remove the switch to the UI thread if you don't need it.
            await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            this.AddService(typeof(IStatusBarService), async(container, token, type) =>
            {
                await JoinableTaskFactory.SwitchToMainThreadAsync(token);

                if (!(await GetServiceAsync(typeof(SVsStatusbar)) is IVsStatusbar statusBar))
                {
                    return(null);
                }

                var service = new StatusBarService(statusBar);
                return(await Task.FromResult(service));
            });

            this.AddService(typeof(ILogger), async(container, token, type) =>
            {
                await JoinableTaskFactory.SwitchToMainThreadAsync(token);
                if (!(await GetServiceAsync(typeof(SVsOutputWindow)) is IVsOutputWindow outputWindow))
                {
                    return(null);
                }

                if (!(await GetServiceAsync(typeof(DTE)) is DTE2 dte))
                {
                    return(null);
                }

                var eventSource = nameof(PowerClean);
                try
                {
                    // searching the source throws a security exception ONLY if not exists!
                    if (EventLog.SourceExists(eventSource))
                    { // no exception until yet means the user as admin privilege
                        EventLog.CreateEventSource(eventSource, "Application");
                    }
                }
                catch (SecurityException)
                {
                    eventSource = "Application";
                }

                var loggerConfig = new LoggerConfiguration()
                                   .MinimumLevel.Information()
                                   .WriteTo.VisualStudio(outputWindow)          //TODO make config so it only logs some things in verbose
                                   .WriteTo.EventLog(eventSource, Application); //TODO remember to handle outputTemplate

                #region Config
                //var solutionFolder = dte.Solution.GetRootFolder();

                //var powerCleanConfig = $"{dte.Solution.FileName}.powerclean.json";

                //var powerCleanConfigFile = Path.Combine(solutionFolder, powerCleanConfig);

                //EnsureCreatedConfig(powerCleanConfigFile);

                //if (File.Exists(powerCleanConfigFile))
                //{
                //  var configuration = new ConfigurationBuilder()
                //      .SetBasePath(solutionFolder)
                //      .AddJsonFile(powerCleanConfig)
                //      .Build();
                //  loggerConfig.ReadFrom.Configuration(configuration);
                //}
                #endregion

                return(await Task.FromResult(Log.Logger = loggerConfig.CreateLogger()));
            });

            this.AddService(typeof(IPowerShellService), async(container, token, type) =>
            {
                await JoinableTaskFactory.SwitchToMainThreadAsync(token);

                if (!(await GetServiceAsync(typeof(SVsOutputWindow)) is IVsOutputWindow outputWindow))
                {
                    return(null);
                }

                if (!(await GetServiceAsync(typeof(DTE)) is DTE2 dte))
                {
                    return(null);
                }
                Assumes.Present(dte);
                if (!(await GetServiceAsync(typeof(IStatusBarService)) is IStatusBarService statusBarService))
                {
                    return(null);
                }
                if (!(await GetServiceAsync(typeof(ILogger)) is ILogger logger))
                {
                    return(null);
                }
                var service = new PowerShellService(dte, statusBarService, outputWindow, logger);
                return(await Task.FromResult(service));
            });

            await PowerCleanSolutionCommand.InitializeAsync(this);

            await PowerCleanProjectCommand.InitializeAsync(this);

            Log.Logger.Here();
        }