private void CounterMem(Object st) { MonitorTheadStarter info = (MonitorTheadStarter)st; Zabbix zbx = new Zabbix(info.config.Host, info.config.Port); //String tmp = zbx.GetItem(info.key); //new Thread(new ParameterizedThreadStart(CounterMem)).Start(new MonitorTheadStarter(cfg, "vm.memory.size[total]", i)); //new Thread(new ParameterizedThreadStart(CounterMem)).Start(new MonitorTheadStarter(cfg, "vm.memory.size[available]", i)); while (_running) { try { double total = double.Parse(zbx.GetItem("vm.memory.size[total]")); double available = double.Parse(zbx.GetItem("vm.memory.size[available]")); double used = total - available; _queue[info.index].Add(new ZabbixQueueItem(DateTime.Now, info.config.Host, "vm.memory", (Int64)total, (Int64)used)); } catch { } Thread.Sleep(10000); } }
private void CounterProc(Object st) { MonitorTheadStarter info = (MonitorTheadStarter)st; Zabbix zbx = new Zabbix(info.config.Host, info.config.Port); //String tmp = zbx.GetItem(info.key); while (_running) { switch (info.key.ToLower()) { case "system.cpu.util[,,avg1]": try { String tmp3 = zbx.GetItem(info.key).Replace(".", ","); double tmp = double.Parse(tmp3); _queue[info.index].Add(new ZabbixQueueItem(DateTime.Now, info.config.Host, info.key, 100, (Int64)tmp)); } catch { } break; case "system.cpu.load[percpu,avg1]": try { String tmp3 = zbx.GetItem(info.key).Replace(".", ","); double tmp = double.Parse(tmp3) * 100F; _queue[info.index].Add(new ZabbixQueueItem(DateTime.Now, info.config.Host, info.key, 100, (Int64)tmp)); } catch { } break; default: try { Int64 tmp = Int64.Parse(zbx.GetItem(info.key)); _queue[info.index].Add(new ZabbixQueueItem(DateTime.Now, info.config.Host, info.key, 0, tmp)); } catch { } break; } Thread.Sleep(10000); } }
static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly(); WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator); if (!hasAdministrativeRight) { string parameter = string.Concat(args); RunElevated(asm.Location, parameter); Process.GetCurrentProcess().Kill(); } Console.WriteLine("[+] Checking initial configuration..."); Int16 levels = 3; Int16.TryParse(ConfigurationManager.AppSettings["levels"], out levels); Int16 connCount = 30; Int16.TryParse(ConfigurationManager.AppSettings["count"], out connCount); Int16 duration = 300; Int16.TryParse(ConfigurationManager.AppSettings["duration"], out duration); if (duration < 180) { duration = 180; } if (duration > 3600) { duration = 3600; } ClientType type = ClientType.VU; try { switch (ConfigurationManager.AppSettings["type"].ToLower()) { case "sbu": type = ClientType.SBU; break; default: type = ClientType.VU; break; } } catch { } Uri site = null; try { site = new Uri(ConfigurationManager.AppSettings["uri"]); } catch (Exception ex) { Console.WriteLine("URI not valid"); return; } Dictionary <String, String> headers = new Dictionary <string, string>(); if (!String.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["Cookie"])) { try { CookieContainer tmp = new CookieContainer(); tmp.SetCookies(site, ConfigurationManager.AppSettings["Cookie"]); headers.Add("Cookie", ConfigurationManager.AppSettings["Cookie"]); } catch (Exception ex) { Console.WriteLine("Error parsing cookie"); return; } } try { if (!String.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["User-Agent"])) { headers.Add("User-Agent", ConfigurationManager.AppSettings["User-Agent"]); } } catch (Exception ex) { Console.WriteLine("Error parsing User-Agent"); return; } Console.WriteLine("[+] Checking zabbix agents..."); Console.WriteLine("[+] Checking date and time from NTP servers..."); try { DateTime ntpdate = NTP.GetNetworkUTCTime(); Console.WriteLine(" NTP UTC data: " + ntpdate.ToString(Thread.CurrentThread.CurrentCulture)); TimeSpan ts = ntpdate - DateTime.UtcNow; if (Math.Abs(ts.TotalSeconds) > 60) { Console.WriteLine(" Updating local time"); Console.WriteLine(" Old time: " + DateTime.Now.ToString(Thread.CurrentThread.CurrentCulture)); NTP.SetSystemTime(ntpdate); Console.WriteLine(" New time: " + DateTime.Now.ToString(Thread.CurrentThread.CurrentCulture)); } else { Console.WriteLine(" Local time is up to date"); } } catch (Exception ex) { Console.WriteLine("[!] Error updating local time: " + ex.Message); } List <ZabbixConfig> zbxConfig = new List <ZabbixConfig>(); ZabbixConfigSection ZabbixManagers = (ZabbixConfigSection)ConfigurationManager.GetSection("zabbixMonitors"); if (ZabbixManagers != null) { foreach (ZabbixConfigElement zbxHost in ZabbixManagers.ZabbixConfigElements) { //Realiza teste de conex'ao em cada um dos zabbix listados try { Console.Write("[*] Zabbix agent on " + zbxHost.Host + ":" + zbxHost.Port); using (Zabbix zbx = new Zabbix(zbxHost.Host, zbxHost.Port)) { String tst = zbx.GetItem("system.hostname"); } zbxConfig.Add(new ZabbixConfig(zbxHost.Name, zbxHost.Host, zbxHost.Port)); Console.WriteLine("\t\tOK"); } catch { Console.WriteLine("\t\tError"); Console.WriteLine("Error Getting information from Zabbix " + zbxHost.Name + " (" + zbxHost.Host + ":" + zbxHost.Port + ")"); return; } } } Profile prof = null; /* * if (args.Length > 4) * { * try * { * FileInfo profileFile = new FileInfo(args[4]); * if (profileFile.Extension == ".prof") * { * prof = new Profile(); * prof.LoadProfile(profileFile.FullName); * * if ((prof.BaseUri == null) || (prof.Uris.Count == 0)) * prof = null; * } * } * catch(Exception ex) { * prof = null; * } * }*/ IPEndPoint proxy = null;// new IPEndPoint(IPAddress.Parse("10.0.10.1"), 80); if (!String.IsNullOrEmpty((string)ConfigurationManager.AppSettings["proxy"])) { Uri tProxy = null; try { tProxy = new Uri(ConfigurationManager.AppSettings["proxy"]); proxy = new IPEndPoint(IPAddress.Parse(tProxy.Host), tProxy.Port); } catch (Exception ex) { Console.WriteLine("Proxy not valid. Proxy should be an IP URI. Ex: http://10.10.10.10:3389"); return; } } Int32 sleepTime = 0; try { Int32.TryParse((string)ConfigurationManager.AppSettings["sleeptime"], out sleepTime); } catch { } TestBuilder builder = new TestBuilder(); /* * if (prof != null) * builder.Fetch(prof); * else * builder.Fetch( * site, * proxy, * 1); */ // Console.WriteLine("[+] Building test environment..."); builder.Fetch( site, proxy, levels, headers); TestEnvironment env = builder.Build(proxy, type, 5); env.HTTPHeaders = headers; env.ZabbixMonitors = zbxConfig; env.SleepTime = sleepTime; env.VirtualUsers = connCount; env.ConnectionString = new DbConnectionString(ConfigurationManager.ConnectionStrings["LoadTest"]); env.Start(); Console.WriteLine("[+] Starting test..."); Console.WriteLine("[+] System started (" + (prof != null ? "prof" : "scan") + ")!"); Console.WriteLine("[+] Total test duration: " + duration + " seconds"); Console.WriteLine("[!] Press CTRL + C to finish the teste and generate report"); _running = true; _tmpEnd = new Timer(new TimerCallback(tmpEnd), null, duration * 1000, duration * 1000); Console.CancelKeyPress += new ConsoleCancelEventHandler(myHandler); Console.WriteLine(""); DateTime dStart = DateTime.Now; while (_running) { System.Threading.Thread.Sleep(500); TimeSpan ts = DateTime.Now - dStart; Console.Write("\r"); Console.Write("Test Duration: {0}", ts.ToString(@"hh\:mm\:ss")); } ClearCurrentConsoleLine(); Console.WriteLine(""); env.Stop(); /* * TestEnvironment env = new TestEnvironment(); * env.LoadConfig("temp.env");*/ //Gera o relatório Console.WriteLine("[+] Building report..."); env.BuildReports(); //env.DropDatabase(); }
private void CounterProcNet(Object st) { MonitorTheadStarter info = (MonitorTheadStarter)st; Zabbix zbx = new Zabbix(info.config.Host, info.config.Port); //String tmp = zbx.GetItem(info.key); // ZabbixQueueItem lastIn = null; ZabbixQueueItem lastOut = null; while (_running) { try { if (lastIn == null) { lastIn = new ZabbixQueueItem(DateTime.Now, info.config.Host, info.key, 0, Int64.Parse(zbx.GetItem("net.if.in[" + info.key + "]"))); } if (lastOut == null) { lastOut = new ZabbixQueueItem(DateTime.Now, info.config.Host, info.key, 0, Int64.Parse(zbx.GetItem("net.if.out[" + info.key + "]"))); } ZabbixQueueItem actualIn = new ZabbixQueueItem(DateTime.Now, info.config.Host, info.key, 0, Int64.Parse(zbx.GetItem("net.if.in[" + info.key + "]"))); ZabbixQueueItem actualOut = new ZabbixQueueItem(DateTime.Now, info.config.Host, info.key, 0, Int64.Parse(zbx.GetItem("net.if.out[" + info.key + "]"))); try { double lapIn = ((TimeSpan)(actualIn.date - lastIn.date)).TotalSeconds; double lapIn2 = double.Parse(actualIn.value.ToString()) - double.Parse(lastIn.value.ToString()); double valueIn = (lapIn2 / lapIn); if (double.IsNaN(valueIn) || double.IsInfinity(valueIn)) { valueIn = 0; } if (valueIn < 0) { valueIn = 0; } double lapOut = ((TimeSpan)(actualOut.date - lastOut.date)).TotalSeconds; double lapOut2 = double.Parse(actualOut.value.ToString()) - double.Parse(lastOut.value.ToString()); double valueOut = (lapOut2 / lapOut); if (double.IsNaN(valueOut) || double.IsInfinity(valueOut)) { valueOut = 0; } if (valueOut < 0) { valueOut = 0; } _queue[info.index].Add(new ZabbixQueueNetworkItem(actualIn.date, actualIn.host, info.key, ((Int64)valueIn), ((Int64)valueOut))); lastIn = actualIn; lastOut = actualOut; } catch { } } catch { } finally { Thread.Sleep(10000); } } }
//Métodos privados private void StartConn() { try { _running = true; Int32 queueCount = (Int32)environment.ZabbixMonitors.Count; queueCount = 3; if (queueCount <= 0) { queueCount = 1; } _queue = new DBQueue[queueCount]; //Inicia as theads de monitoramento Int32 i = 0; foreach (ZabbixConfig cfg in environment.ZabbixMonitors) { //ChangeDB(i); //Console.WriteLine(text); #if DEBUG Console.WriteLine("procQueue.Start(i); " + i); #endif _queue[i] = new DBQueue(); Thread procQueue = new Thread(new ParameterizedThreadStart(ProcQueue)); procQueue.Start(i); new Thread(new ParameterizedThreadStart(CounterProc)).Start(new MonitorTheadStarter(cfg, "system.cpu.util[,,avg1]", i)); new Thread(new ParameterizedThreadStart(CounterProc)).Start(new MonitorTheadStarter(cfg, "system.cpu.load[percpu,avg1]", i)); new Thread(new ParameterizedThreadStart(CounterMem)).Start(new MonitorTheadStarter(cfg, "", i)); //Busca as interfaces de rede using (Zabbix zbx = new Zabbix(cfg.Host, cfg.Port)) { List <String> exclusionList = new List <string>(); exclusionList.Add("Bluetooth"); exclusionList.Add("TAP-Windows"); exclusionList.Add("WFP"); exclusionList.Add("QoS"); exclusionList.Add("Diebold"); exclusionList.Add("Microsoft Kernel Debug"); exclusionList.Add("WAN Miniport"); exclusionList.Add("Loopback"); exclusionList.Add("Wi-Fi Direct Virtual"); exclusionList.Add("Filter Driver"); exclusionList.Add("Pseudo-Interface"); String netIfs = zbx.GetItem("net.if.discovery"); IfRet interfaces = JSON.Deserialize2 <IfRet>(netIfs); if ((interfaces != null) && (interfaces.data != null)) { foreach (Dictionary <String, String> dic in interfaces.data) { if (dic != null) { foreach (String val in dic.Values) { if (!String.IsNullOrWhiteSpace(val)) { Boolean monitor = true; foreach (String e in exclusionList) { if (val.IndexOf(e, StringComparison.CurrentCultureIgnoreCase) >= 0) { monitor = false; } } if (monitor) { new Thread(new ParameterizedThreadStart(CounterProcNet)).Start(new MonitorTheadStarter(cfg, val, i)); // new Thread(new ParameterizedThreadStart(CounterProcNet)).Start(new MonitorTheadStarter(cfg, val, i)); } } } } } } } i++; } } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); SendText("StartConn Error:", ex.Message); } }
public void Start() { if (Uris.Count == 0) { throw new Exception("Listagem de URLs está vazia"); } LoadTestDatabase db = null; try { if (this.ConnectionString == null) { throw new Exception("ConnectionStrings is null"); } db = new LoadTestDatabase(this.ConnectionString); new AutomaticUpdater().Run(db, UpdateScriptRepository.GetScriptsBySqlProviderName(this.ConnectionString)); } catch (Exception ex) { throw new Exception("Erro on load/update database", ex); } try { this.TestName = DateTime.Now.ToString("yyyyMMddHHmmssffff"); db = new LoadTestDatabase(this.ConnectionString); //db.CreateDatabase(this.TestName); } catch (Exception ex) { throw new Exception("Falha ao conectar a base de dados: " + ex.Message); } dStart = DateTime.Now; //Verifica a limitação de utilização free if (this.VirtualUsers > 5000) { db.insertMessages(this.TestName, "0. Licenciamento safetrend.com.br", "A versão free deste aplicativo permite no máximo 5000 VU/SBU"); this.VirtualUsers = 5000; } JavaScriptSerializer ser = new JavaScriptSerializer(); if (this.ZabbixMonitors != null) { foreach (ZabbixConfig zbxHost in this.ZabbixMonitors) { //Realiza teste de conex'ao em cada um dos zabbix listados try { using (Zabbix zbx = new Zabbix(zbxHost.Host, zbxHost.Port)) { StringBuilder hostInfo = new StringBuilder(); String hostname = zbx.GetItem("system.hostname"); hostInfo.AppendLine("<strong>Config name:</strong> " + zbxHost.Name); hostInfo.AppendLine("<strong>Config ip:</strong> " + zbxHost.Host + ":" + zbxHost.Port); hostInfo.AppendLine("<strong>Hostname:</strong> " + hostname); String memory = zbx.GetItem("vm.memory.size[total]"); try { Double m = Double.Parse(memory); ; hostInfo.AppendLine("<strong>Memória total:</strong> " + FileResources.formatData(m, ChartDataType.Bytes)); } catch { } String cpus = zbx.GetItem("system.cpu.discovery"); try { Dictionary <String, Object[]> values = ser.Deserialize <Dictionary <String, Object[]> >(cpus); //List<Dictionary<String, String>> values = ser.Deserialize<List<Dictionary<String, String>>>(cpus); hostInfo.AppendLine("<strong>Quantidade de vCPU:</strong> " + values["data"].Length); } catch { } String disk = zbx.GetItem("vfs.fs.discovery"); try { Dictionary <String, Object[]> values = ser.Deserialize <Dictionary <String, Object[]> >(disk); //List<Dictionary<String, String>> values = ser.Deserialize<List<Dictionary<String, String>>>(cpus); Int32 cnt = 1; foreach (Object o in values["data"]) { String name = ""; String type = ""; if (o is Dictionary <String, Object> ) { Dictionary <String, Object> tO = (Dictionary <String, Object>)o; name = tO["{#FSNAME}"].ToString(); type = tO["{#FSTYPE}"].ToString(); if (!String.IsNullOrEmpty(name)) { switch (type.ToLower()) { case "rootfs": case "sysfs": case "proc": case "devtmpfs": case "devpts": case "tmpfs": case "fusectl": case "debugfs": case "securityfs": case "pstore": case "cgroup": case "rpc_pipefs": case "unknown": case "usbfs": case "binfmt_misc": case "autofs": break; default: hostInfo.AppendLine("<strong>Disco " + cnt + ":</strong> " + name + " --> " + type); cnt++; break; } } } } } catch { } String netIfs = zbx.GetItem("net.if.discovery"); try { List <String> exclusionList = new List <string>(); exclusionList.Add("Bluetooth"); exclusionList.Add("TAP-Windows"); exclusionList.Add("WFP"); exclusionList.Add("QoS"); exclusionList.Add("Diebold"); exclusionList.Add("Microsoft Kernel Debug"); exclusionList.Add("WAN Miniport"); exclusionList.Add("Loopback"); exclusionList.Add("Wi-Fi Direct Virtual"); exclusionList.Add("Filter Driver"); exclusionList.Add("Pseudo-Interface"); Dictionary <String, Object[]> values = ser.Deserialize <Dictionary <String, Object[]> >(netIfs); Int32 cnt = 1; foreach (Object o in values["data"]) { String ifName = ""; if (o is Dictionary <String, Object> ) { Dictionary <String, Object> tO = (Dictionary <String, Object>)o; ifName = tO["{#IFNAME}"].ToString(); if (!String.IsNullOrEmpty(ifName)) { Boolean insert = true; foreach (String e in exclusionList) { if (ifName.IndexOf(e, StringComparison.CurrentCultureIgnoreCase) >= 0) { insert = false; } } if (insert) { hostInfo.AppendLine("<strong>Interface de rede " + cnt + ":</strong> " + ifName); cnt++; } } } } } catch { } db.insertMessages(this.TestName, "1. Zabbix Monitor", hostInfo.ToString()); } } catch { db.insertMessages(this.TestName, "0. Zabbix Monitor", "Erro ao resgatar informação do Host Zabbix " + zbxHost.Name + " (" + zbxHost.Host + ":" + zbxHost.Port + ")"); } } } //Antes de iniciar o stress test realiza a análise de conteúdo this.ContentAnalizer(); if (this.SleepTime < 0) { this.SleepTime = 0; } Int16 factor = 300; if (this.Type == ClientType.VU) { factor = (Int16)(factor * 2); } if (this.VirtualUsers < 0) { this.VirtualUsers = 1; } //Inicia servi;co de monitoramento e SNMP Trap using (TestEnvironment tmp = (TestEnvironment)this.Clone()) { StartApplication("ZabbixGet.exe", tmp); StartApplication("snmptrapreceiver.exe", tmp); } using (TestEnvironment tmp = (TestEnvironment)this.Clone()) { Int16 r = this.VirtualUsers; if (r > factor) { r = factor; } tmp.VirtualUsers = r; FileInfo tFile = new FileInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())); tmp.SaveToFile(tFile.FullName); Console.WriteLine("Para iniciar mais conexões utilize o comando abaixo, cada cliente iniciará {0} usuários virtuais", tmp.VirtualUsers); Console.WriteLine("\"{0}\\{1}\" \"{2}\"", Environment.CurrentDirectory, "client.exe", tFile.FullName); Console.WriteLine(""); } Int16 restConn = this.VirtualUsers; while (restConn > factor) { using (TestEnvironment tmp = (TestEnvironment)this.Clone()) { tmp.VirtualUsers = factor; StartApplication("client.exe", tmp); restConn -= factor; } } if (restConn > 0) { using (TestEnvironment tmp = (TestEnvironment)this.Clone()) { tmp.VirtualUsers = restConn; StartApplication("client.exe", tmp); } } }