using log4net;
using SnmpSharpNet;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using SNMP_TRAP_SEND;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace SNMP_TRAP_SEND
{
class Program
{
// 로거 ILog 필드
//log4net.Config.XmlConfigurator.Configure();
private static ILog log = LogManager.GetLogger("Program");
public static string _IP_ADDRESS_SENDER ="192.168.0.46";
public static string _IP_ADDRESS_RECEIVER = "192.168.0.55";
static PerformanceCounter cpu = new PerformanceCounter("Processor","% Processor Time","_Total");
static PerformanceCounter usedRamPercent = new PerformanceCounter("Memory","% Committed Bytes In Use");
static PerformanceCounter cRam = new PerformanceCounter("Memory", "Committed Bytes");
static PerformanceCounter aRam = new PerformanceCounter("Memory","Available MBytes");
static Double diskSize = 0;
static Double diskValue = 0;
private static UdpClient client;
private static string masterServer = ConfigurationSettings.AppSettings["Master"];
private DataSet InsertResorecesMonitor(string date_Time,string server_ip,string cpu,string total_ram,string used_ram,string total_disk,string used_disk)
{
//string query = "select * from beecloud.ag_select_web_config_db('CM','CONFIG')";
//string query = "select * from beecloud.server";
StringBuilder strb = new StringBuilder();
// string query = "";
strb.Append("insert into beecloud.resources_monitor(date_time,server_ip,server_name ,used_CPU_PERC ,total_CPU_PERC ,used_RAM_MB ,total_RAM_MB ,used_DISK_MB ,total_DISK_MB )");
strb.AppendFormat("values('{0}','{1}','',{2},100,{3},{4},{5},{6})", date_Time,server_ip,cpu,total_ram,used_ram,total_disk,used_disk);
DataSet result = SQLController.GetDataSet(strb.ToString());
return result;
}
public void Send()
{
// using (file)
// {
VbCollection col = new VbCollection();
Vb c = new Vb();
Vb b = new Vb();
while (true)
{
col.Clear();
TrapAgent agent = new TrapAgent();
//if (args.LongLength > 0)
//{
// _IP_ADDRESS_RECEIVER = args[0];s
//}
//if (args.Length > 1)
//{
// _IP_ADDRESS_RECEIVER = args[1];
//}
string cpuValue = cpu.NextValue().ToString();
string ramPer = usedRamPercent.NextValue().ToString();
string aRamValue = aRam.NextValue().ToString();
string cRamValue = cRam.NextValue().ToString();
string usedRam = "";
string totalDisk = "";
string usedDisk = "";
//단위 : MB
string totalRamValue = ((Convert.ToDouble(aRamValue)+Convert.ToDouble(cRamValue))/1024/1024).ToString();
string now;
now = string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
DriveInfo[] allDrives = DriveInfo.GetDrives();
for (int i = 0; i < allDrives.Length; i++)
{
DriveInfo a = allDrives[i];
if (a.Name.Equals("C:\\"))
{
diskSize = a.TotalSize - a.TotalFreeSpace;
diskValue = diskSize / a.TotalSize * 100;
totalDisk = (a.TotalSize / 1024 / 1024).ToString();
usedDisk = (diskSize / 1024 / 1024).ToString();
}
}
string line = string.Format("{0} {1}% {2}%({3}GB) {4}%({5}GB)"
, now
, Math.Round(Convert.ToDouble(cpuValue), 2)
, Math.Round(Convert.ToDouble(ramPer), 2)
, Math.Round(Convert.ToDouble(cRamValue) / 1024 / 1024 / 1024, 2) //RAM GB
, Math.Round(diskValue, 2)
, Math.Round(diskSize / 1024 / 1024 / 1024, 2)
);
usedRam = (Convert.ToDouble(cRamValue) / 1024 / 1024).ToString();
string diskValueTemp = string.Format("{0} DISK Used:{1}%({2}MB)"
, now
, Math.Round(diskValue, 2)
, Math.Round(diskSize / 1024 / 1024 / 1024, 2));
//cpuValue = string.Format("{0} CPU Used:{1}%"
// , now
// , Math.Round(Convert.ToDouble(cpuValue), 2));
//ramValue = string.Format("{0} RAM Used:{1}%({2}MB)"
// , now
// , Math.Round(Convert.ToDouble(totalRamValue), 2)
// , Math.Round(Convert.ToDouble(ramValue) / 1024 / 1024 / 1024, 2));
col.Add(new Oid("TIME"),new OctetString(now));
col.Add(new Oid("USED_CPU"), new OctetString(cpuValue));
col.Add(new Oid("TOTAL_RAM"), new OctetString(totalRamValue));
col.Add(new Oid("USED_RAM"), new OctetString(usedRam));
col.Add(new Oid("TOTAL_DISK"), new OctetString(totalDisk));
col.Add(new Oid("USED_DISK"), new OctetString(usedDisk));
SnmpV1TrapPacket packet = new SnmpV1TrapPacket();
packet.Pdu.VbList.Add(col);
agent.SendV1Trap(new IpAddress(_IP_ADDRESS_RECEIVER), 162, "public", new Oid("1.3.6.1.2.1.1.1.0"), new IpAddress(_IP_ADDRESS_SENDER), SnmpConstants.LinkUp, 0, 13432, col);
Console.WriteLine(line);
log.Info(line);
System.Threading.Thread.Sleep(3000);
}
}
private void ReceiveCallback(IAsyncResult res)
{
IPHostEntry host = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName());
string myip = host.AddressList[host.AddressList.Length - 1].ToString();
IPEndPoint e = new IPEndPoint(IPAddress.Parse(myip), 0);
byte[] received = client.EndReceive(res, ref e);
int ver = SnmpPacket.GetProtocolVersion(received, received.Length);
if (ver == (int)SnmpVersion.Ver1)
{
SnmpV1TrapPacket pkt = new SnmpV1TrapPacket("public");
pkt.decode(received, received.Length);
if (pkt.Pdu.VbList.Count >= 3)
{
string[] temp = pkt.Pdu.VbList[1].Value.ToString().Split(':');
//CPU
//model.CPU = pkt.Pdu.VbList[0].Value.ToString().Split(':')[3]
Console.WriteLine("[RECV] "+pkt.Pdu.VbList[0].Value.ToString() + " "+pkt.Pdu.AgentAddress.ToString() + " CPU:" + pkt.Pdu.VbList[1].Value.ToString());
//RAM
// model.RAM = pkt.Pdu.VbList[1].Value.ToString().Split(':')[4];
Console.WriteLine("[RECV] " + pkt.Pdu.VbList[0].Value.ToString() + " "+pkt.Pdu.AgentAddress.ToString() + " RAM:" + pkt.Pdu.VbList[2].Value.ToString()+"MB "+ pkt.Pdu.VbList[3].Value.ToString()+"MB");
//DISK
//model.DISK = pkt.Pdu.VbList[2].Value.ToString().Split(':')[4];
Console.WriteLine("[RECV] " + pkt.Pdu.VbList[0].Value.ToString() + " "+pkt.Pdu.AgentAddress.ToString() + " DISK:" + pkt.Pdu.VbList[4].Value.ToString() + "MB " + pkt.Pdu.VbList[5].Value.ToString() + "MB");
//col.Add(new Oid("TIME"), new OctetString(now));
//col.Add(new Oid("USED_CPU"), new OctetString(cpuValue));
//col.Add(new Oid("TOTAL_RAM"), new OctetString(totalRamValue));
//col.Add(new Oid("USED_RAM"), new OctetString(usedRam));
//col.Add(new Oid("TOTAL_DISK"), new OctetString(totalDisk));
//col.Add(new Oid("USED_DISK"), new OctetString(usedDisk));
this.InsertResorecesMonitor(pkt.Pdu.VbList[0].Value.ToString()
,pkt.Pdu.AgentAddress.ToString()
, pkt.Pdu.VbList[1].Value.ToString()
, pkt.Pdu.VbList[2].Value.ToString()
, pkt.Pdu.VbList[3].Value.ToString()
, pkt.Pdu.VbList[4].Value.ToString()
, pkt.Pdu.VbList[5].Value.ToString());
}
}
client.BeginReceive(new AsyncCallback(ReceiveCallback), null);
}
static void Main(string[] args)
{
//// StreamWriter file = null;
Program program = new Program();
try
{
string dateString =string.Format("{0:yyyyMMdd}",DateTime.Now);
string path = @"C:\WebSite\beeCloudPro\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
IPHostEntry host = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName());
string myip = host.AddressList[host.AddressList.Length - 1].ToString();
_IP_ADDRESS_SENDER = myip;
_IP_ADDRESS_RECEIVER = masterServer;
// 비동기 수신을 위함. (Master Server 일 경우에만 수신오픈)
if (_IP_ADDRESS_SENDER.Equals(masterServer))
{
client= new UdpClient(162);
client.EnableBroadcast = true;
client.BeginReceive(new AsyncCallback(program.ReceiveCallback),null);
DataSet set = new DataSet();
SQLController.DefaultBinding(out set);
}
program.Send();
}
catch(Exception e) { Console.WriteLine(e.Message); }
}
}
}
2017년 9월 10일 일요일
2017년 9월 8일 금요일
[SNMP] SNMP Sender Using SnmpSharpNet and Using Log4net
using log4net;
using SnmpSharpNet;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace SNMP_TRAP_SEND
{
class Program
{
// 로거 ILog 필드
//log4net.Config.XmlConfigurator.Configure();
private static ILog log = LogManager.GetLogger("Program");
public static string _IP_ADDRESS_SENDER ="192.168.0.46";
public static string _IP_ADDRESS = "192.168.0.55";
static PerformanceCounter cpu = new PerformanceCounter("Processor","% Processor Time","_Total");
static PerformanceCounter totalRAM = new PerformanceCounter("Memory","% Committed Bytes In Use");
static PerformanceCounter ram = new PerformanceCounter("Memory", "Committed Bytes");
static Double diskSize = 0;
static Double diskValue = 0;
static void Main(string[] args)
{
StreamWriter file = null;
try
{
string dateString =string.Format("{0:yyyyMMdd}",DateTime.Now);
string path = @"C:\WebSite\beeCloudPro\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
IPHostEntry host = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName());
string myip = host.AddressList[host.AddressList.Length - 1].ToString();
_IP_ADDRESS_SENDER = myip;
using (file)
{
VbCollection col = new VbCollection();
Vb c = new Vb();
Vb b = new Vb();
while (true)
{
col.Clear();
TrapAgent agent = new TrapAgent();
if (args.LongLength > 0)
{
// _IP_ADDRESS_SENDER = args[0];
_IP_ADDRESS= args[0];
}
if (args.Length > 1)
{
_IP_ADDRESS = args[1];
}
string cpuValue = cpu.NextValue().ToString();
string totalRamValue = totalRAM.NextValue().ToString();
string ramValue = ram.NextValue().ToString();
string now;
now = string.Format("{0:yyyy-MM-dd HH:mm:ss}",DateTime.Now);
DriveInfo[] allDrives = DriveInfo.GetDrives();
for(int i=0;i<allDrives.Length;i++)
{
DriveInfo a = allDrives[i];
if (a.Name.Equals("C:\\"))
{
diskSize = a.TotalSize - a.TotalFreeSpace;
diskValue = diskSize / a.TotalSize * 100;
}
}
string line = string.Format("{0}|{1}%|{2}%({3}GB)|{4}%({5}GB)"
, now
, Math.Round(Convert.ToDouble(cpuValue), 2)
, Math.Round(Convert.ToDouble(totalRamValue), 2)
, Math.Round(Convert.ToDouble(ramValue)/1024 / 1024 / 1024, 2) //RAM GB
, Math.Round(diskValue, 2)
, Math.Round(diskSize / 1024 / 1024 / 1024, 2)
);
string diskValueTemp = string.Format("{0} DISK Used:{1}%({2}GB)"
,now
, Math.Round(diskValue, 2)
, Math.Round(diskSize / 1024 / 1024 / 1024, 2));
cpuValue = string.Format("{0} CPU Used:{1}%"
, now
, Math.Round(Convert.ToDouble(cpuValue), 2));
ramValue = string.Format("{0} DISK Used:{1}%({2}GB)"
, now
, Math.Round(Convert.ToDouble(totalRamValue), 2)
, Math.Round(Convert.ToDouble(ramValue) / 1024 / 1024 / 1024, 2));
col.Add(new Oid("CPU"), new OctetString(cpuValue));
col.Add(new Oid("RAM"), new OctetString(ramValue));
col.Add(new Oid("DISK"), new OctetString(diskValueTemp));
//file.WriteLineAsync(line);
//file.Flush();
SnmpV1TrapPacket packet = new SnmpV1TrapPacket();
packet.Pdu.VbList.Add(col);
agent.SendV1Trap(packet, new IpAddress(_IP_ADDRESS_SENDER),162);
// OR
agent.SendV1Trap(new IpAddress(_IP_ADDRESS), 162,"public", new Oid("1.3.6.1.2.1.1.1.0"),new IpAddress(_IP_ADDRESS_SENDER),SnmpConstants.LinkUp,0,13432,col);
Console.WriteLine(line);
log.Info(line);
System.Threading.Thread.Sleep(3000);
}
}
}
catch(Exception e) { Console.WriteLine(e.Message); }
}
}
}
using SnmpSharpNet;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace SNMP_TRAP_SEND
{
class Program
{
// 로거 ILog 필드
//log4net.Config.XmlConfigurator.Configure();
private static ILog log = LogManager.GetLogger("Program");
public static string _IP_ADDRESS_SENDER ="192.168.0.46";
public static string _IP_ADDRESS = "192.168.0.55";
static PerformanceCounter cpu = new PerformanceCounter("Processor","% Processor Time","_Total");
static PerformanceCounter totalRAM = new PerformanceCounter("Memory","% Committed Bytes In Use");
static PerformanceCounter ram = new PerformanceCounter("Memory", "Committed Bytes");
static Double diskSize = 0;
static Double diskValue = 0;
static void Main(string[] args)
{
StreamWriter file = null;
try
{
string dateString =string.Format("{0:yyyyMMdd}",DateTime.Now);
string path = @"C:\WebSite\beeCloudPro\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
IPHostEntry host = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName());
string myip = host.AddressList[host.AddressList.Length - 1].ToString();
_IP_ADDRESS_SENDER = myip;
using (file)
{
VbCollection col = new VbCollection();
Vb c = new Vb();
Vb b = new Vb();
while (true)
{
col.Clear();
TrapAgent agent = new TrapAgent();
if (args.LongLength > 0)
{
// _IP_ADDRESS_SENDER = args[0];
_IP_ADDRESS= args[0];
}
if (args.Length > 1)
{
_IP_ADDRESS = args[1];
}
string cpuValue = cpu.NextValue().ToString();
string totalRamValue = totalRAM.NextValue().ToString();
string ramValue = ram.NextValue().ToString();
string now;
now = string.Format("{0:yyyy-MM-dd HH:mm:ss}",DateTime.Now);
DriveInfo[] allDrives = DriveInfo.GetDrives();
for(int i=0;i<allDrives.Length;i++)
{
DriveInfo a = allDrives[i];
if (a.Name.Equals("C:\\"))
{
diskSize = a.TotalSize - a.TotalFreeSpace;
diskValue = diskSize / a.TotalSize * 100;
}
}
string line = string.Format("{0}|{1}%|{2}%({3}GB)|{4}%({5}GB)"
, now
, Math.Round(Convert.ToDouble(cpuValue), 2)
, Math.Round(Convert.ToDouble(totalRamValue), 2)
, Math.Round(Convert.ToDouble(ramValue)/1024 / 1024 / 1024, 2) //RAM GB
, Math.Round(diskValue, 2)
, Math.Round(diskSize / 1024 / 1024 / 1024, 2)
);
string diskValueTemp = string.Format("{0} DISK Used:{1}%({2}GB)"
,now
, Math.Round(diskValue, 2)
, Math.Round(diskSize / 1024 / 1024 / 1024, 2));
cpuValue = string.Format("{0} CPU Used:{1}%"
, now
, Math.Round(Convert.ToDouble(cpuValue), 2));
ramValue = string.Format("{0} DISK Used:{1}%({2}GB)"
, now
, Math.Round(Convert.ToDouble(totalRamValue), 2)
, Math.Round(Convert.ToDouble(ramValue) / 1024 / 1024 / 1024, 2));
col.Add(new Oid("CPU"), new OctetString(cpuValue));
col.Add(new Oid("RAM"), new OctetString(ramValue));
col.Add(new Oid("DISK"), new OctetString(diskValueTemp));
//file.WriteLineAsync(line);
//file.Flush();
SnmpV1TrapPacket packet = new SnmpV1TrapPacket();
packet.Pdu.VbList.Add(col);
agent.SendV1Trap(packet, new IpAddress(_IP_ADDRESS_SENDER),162);
// OR
agent.SendV1Trap(new IpAddress(_IP_ADDRESS), 162,"public", new Oid("1.3.6.1.2.1.1.1.0"),new IpAddress(_IP_ADDRESS_SENDER),SnmpConstants.LinkUp,0,13432,col);
Console.WriteLine(line);
log.Info(line);
System.Threading.Thread.Sleep(3000);
}
}
}
catch(Exception e) { Console.WriteLine(e.Message); }
}
}
}
2017년 9월 5일 화요일
[Postgre SQL] Procedure Example
select beecloud.ag_recode_string_agg('CM','CONFIG')
-- DROP FUNCTION beecloud.ag_recode_string_agg(character varying, character varying);
create or replace function beecloud.ag_recode_string_agg(IN job_type_name character varying, IN db_instance_name character varying)
returns SETOF text AS
$BODY$
BEGIN
RETURN QUERY select string_agg(array_to_string(ARRAY[''||A.db_instance||''],','),',') as db_agg
from (select * from beecloud.agents where job_type=''||job_type_name||'' and db_instance=''||db_instance_name||'') A;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;
create or replace function beecloud.ag_recode_string_agg(IN job_type_name character varying)
returns SETOF text AS
$BODY$
BEGIN
RETURN QUERY select string_agg(array_to_string(ARRAY[''||A.db_instance||''],','),',') as db_agg
from (select * from beecloud.agents where job_type=''||job_type_name||'') A;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;
-------------------------------------------------------------
select * from beecloud.agents
select beecloud.ag_create_connection_string('CM', 'CONFIG')
create or replace function beecloud.ag_create_connection_string(IN job_type character varying,IN db_instance_name character varying)
returns table(db_instance text,conn_string text) as
$BODY$
BEGIN
RETURN QUERY
select A.db_instance ,'hostaddr='||A.db_server||' port='||A.db_port||' dbname='||A.db_database||' user='||A.db_account||' password='||A.db_pwd as conn_string
from beecloud.ag_select_config_db(''||job_type||'',''||db_instance_name||'') A;
END;
$BODY$ LANGUAGE plpgsql VOLATILE;
-- - ----------------------------------------------------------
select * from beecloud.ag_recode_string_agg('CM');
select count(*) from unnest(dblink_get_connection()) as conn where conn='CONFIG';
select * from dblink_get_connections()
select dblink_connect('CONFIG','hostaddr=... port=5432 dbname=postgres user=postgres password=...')
select * from beecloud.ag_select_config_db('CM', 'CONFIG')
create or replace function beecloud.ag_select_config_db (IN job_type_name character varying,IN websv_schema character varying)
returns table(db_instance text,db_server text,db_port text,db_database text,db_account text,db_pwd text) as
$BODY$
declare
filter_str text;
v_sql text;
con_cnt int;
msg text;
BEGIN
filter_str:=''; msg :=''; con_cnt :=0;
EXECUTE 'select * from beecloud.ag_recode_string_agg('''||job_type_name||''')' INTO filter_str;
v_sql:='select db_instance,db_server,db_port,db_database,db_account,db_pwd from beecloud.database
where db_instance in ('||filter_str||')';
EXECUTE 'select count(*) from unnest(dblink_get_connections()) as conn where conn=''CONFIG'' ' INTO con_cnt;
IF con_cnt=0 THEN
EXECUTE ' select dblink_connect(''CONFIG'',''hostaddr=192.168.0.22 port=5432 dbname=postgres user=postgres password=beeHive0622'') ' INTO msg;
ELSE
EXECUTE 'select dblink_disconnect(''CONFIG'') ';
EXECUTE ' select dblink_connect(''CONFIG'',''hostaddr=192.168.0.22 port=5432 dbname=postgres user=postgres password=beeHive0622'') ' INTO msg;
END IF;
RETURN QUERY select * from dblink('CONFIG',''||v_sql||'') as
t(db_instance text,db_server text,db_port text,db_database text,db_account text,db_pwd text);
END;
$BODY$ LANGUAGE plpgsql VOLATILE;
-- ------------------------------------------
beecloud.ag_select_web_config_db();
create or replace function beecloud.ag_select_web_config_db(IN job_type_name character varying,IN instance_name character varying)
returns table (sv_ip text,sv_port text ,sv_user text,sv_pwd text,sv_rootpath text) as
$BODY$
declare filter_str text;conn_string text; v_sql text; v_sql_schema text; schema_nm text; con_cnt int; msg text;
BEGIN
conn_string:='';
filter_str:=''; msg:=''; con_cnt:=0;
EXECUTE 'select * from beecloud.ag_recode_string_agg('''||job_type_name||''','''||instance_name||''') ' INTO filter_str;
EXECUTE 'select count(*) from unnesst(dblink_get_connections()) as conn where conn=''CONFIG'' ' INTO con_cnt;
IF con_cnt=0 THEN
EXECUTE ' select dblink_connect(''CONFIG'',''hostaddr=... port=5432 dbname=postgres user=... password=...'') ' INTO msg;
ELSE
EXECUTE 'select dblink_disconnect(''CONFIG'')';
EXECUTE ' select dblink_connect(''CONFIG'',''hostaddr=... port=5432 dbname=postgres user=... password=...'') ' INTO msg;
END IF;
v_sql_schema :='select db_schema from beecloud.database where db_instance='''||filter_str||''' ';
EXECUTE 'select* from dblink(''CONFIG'','''||v_sql_schema||''') t(db_schema text)' INTO schema_nm;
EXECUTE 'select A.conn_string from beecloud.ag_create_connection_string('''||job_type_name||''','''||instance_name||''','''||schema_name||''') A'
INTO conn_string;
EXECUTE ' select count(*) from unnest(dblink_get_connections()) as conn where conn='''||instance_name||''' ' INTO con_cnt;
IF con_cnt=0 THEN
EXECUTE 'select dblink_connect('''||instance_name||''','''||conn_string||''') ' INTO msg;
ELSE
EXECUTE 'select dblink_disconnect('''||instance_name||''') ' INTO msg;
EXECUTE 'select dblink_connect('''||instance_name||''','''||conn_string||''') ' INTO msg;
END IF;
v_sql:='select sv_ip,sv_port,sv_user,sv_pwd,sv_rootpath from '||schema_nm||'.server where sv_type=''CHART'' ';
RETURN QUERY select * from dblink(''||instance_name||'',''||v_sql||'')as
t(sv_ip text,sv_port text ,sv_user text,sv_pwd text,sv_rootpath text);
END;
$BODY$ LANGUAGE plpgsql VOLATILE;
피드 구독하기:
글 (Atom)