ASCU_ALL/ClientCollector/Program.cs

558 lines
15 KiB
C#
Raw Normal View History

2021-07-31 22:27:59 +05:00
using NLog;
using NLog.Config;
using NLog.Targets;
using System;
using System.Net;
using System.Net.Http;
using DataClient;
using DataClient.Struct;
using System.Linq;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using ApiServer.ApiStruct;
using Newtonsoft.Json;
using System.Text;
using System.IO;
2021-08-01 19:48:09 +05:00
using System.Collections.Generic;
2021-08-02 23:01:18 +05:00
using System.Diagnostics;
2021-07-31 22:27:59 +05:00
namespace ClientCollector
{
class Program
{
static Logger log = LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
LogConf();
log.Info("Start Client Collector.");
2021-08-01 19:48:09 +05:00
Task taskPasp = null;
2021-08-02 23:01:18 +05:00
Task taskData = null;
2021-08-01 19:48:09 +05:00
while (true)
{
if (taskPasp == null || taskPasp.IsCompleted)
{
log.Info("Start Pasport Task.");
2021-08-02 23:01:18 +05:00
taskPasp = WorkPasport();
}
if (taskData == null || taskData.IsCompleted)
{
log.Info("Start Data Task.");
taskData = WorkData();
2021-08-01 19:48:09 +05:00
}
log.Info("Wait tasks.");
2021-08-02 23:01:18 +05:00
Task.WaitAny(new Task[] { taskPasp, taskData });
2021-08-01 19:48:09 +05:00
}
}
2021-08-02 23:01:18 +05:00
static async Task WorkPasport()
2021-08-01 19:48:09 +05:00
{
2021-08-02 23:01:18 +05:00
await Task.Delay(1000);
2021-08-01 22:56:52 +05:00
var IpSTP = "10.10.45.152";
var PortSTP = 1070;
2021-08-01 19:48:09 +05:00
var nameCurrDate = "pasport";
var currDate = GetCurrData(nameCurrDate);
if (!currDate.HasValue)
2021-08-02 23:01:18 +05:00
currDate = new DateTime(2001, 02, 01);
2021-08-01 22:56:52 +05:00
NETClient netClient = new NETClient(IpSTP, PortSTP);
2021-08-02 23:01:18 +05:00
var flagcycle = false;
2021-08-01 19:48:09 +05:00
while (currDate.Value < DateTime.Now.AddDays(-1))
2021-07-31 22:27:59 +05:00
{
try
{
2021-08-01 19:48:09 +05:00
var currDir =
currDate.Value.Year.ToString("D4") + '/' +
currDate.Value.Month.ToString("D2") + '/' +
currDate.Value.Day.ToString("D2");
log.Info("Get pasports from: " + currDir);
2021-08-02 23:01:18 +05:00
while (!netClient.Connected() || flagcycle)
{
flagcycle = false;
if (!netClient.ReConnect())
2021-07-31 22:27:59 +05:00
{
2021-08-01 19:48:09 +05:00
netClient.Close();
2021-08-01 22:56:52 +05:00
netClient = new NETClient(IpSTP, PortSTP);
2021-08-01 19:48:09 +05:00
log.Warn("Can't connect to STP.");
await Task.Delay(10000);
2021-07-31 22:27:59 +05:00
}
2021-08-02 23:01:18 +05:00
}
2021-08-01 19:48:09 +05:00
var currPasports = netClient.Full_Dir_Browse(currDir);
netClient.Close();
if (currPasports == null)
currPasports = Array.Empty<string>();
foreach (var paspDir in currPasports)
2021-07-31 22:27:59 +05:00
{
2021-08-01 19:48:09 +05:00
do
2021-07-31 22:27:59 +05:00
{
2021-08-01 19:48:09 +05:00
try
2021-07-31 22:27:59 +05:00
{
2021-08-01 22:56:52 +05:00
log.Info("Get pasport: " + paspDir);
2021-08-02 23:01:18 +05:00
while (!netClient.Connected() || flagcycle)
{
flagcycle = false;
if (!netClient.ReConnect())
2021-07-31 22:27:59 +05:00
{
log.Warn("Can't connect to STP.");
2021-08-01 19:48:09 +05:00
netClient.Close();
2021-08-01 22:56:52 +05:00
netClient = new NETClient(IpSTP, PortSTP);
2021-08-01 19:48:09 +05:00
await Task.Delay(10000);
2021-07-31 22:27:59 +05:00
}
2021-08-02 23:01:18 +05:00
}
2021-08-01 19:48:09 +05:00
var pasp = netClient.Full_Pasp_Download(paspDir);
netClient.Close();
if (pasp == null || !pasp.HasData)
{
log.Warn("Can't get pasport.");
2021-08-02 23:01:18 +05:00
netClient.Close();
2021-08-01 22:56:52 +05:00
netClient = new NETClient(IpSTP, PortSTP);
2021-08-02 23:01:18 +05:00
flagcycle = true;
2021-08-01 19:48:09 +05:00
await Task.Delay(10000);
continue;
}
2021-08-01 22:56:52 +05:00
while (!SendPasport(pasp))
2021-08-01 19:48:09 +05:00
{
log.Warn("Can't send pasp to API.");
await Task.Delay(10000);
}
break;
}
catch (Exception e)
{
2021-08-01 22:56:52 +05:00
log.Warn(e.Message);
2021-08-02 23:01:18 +05:00
netClient.Close();
flagcycle = true;
2021-08-01 19:48:09 +05:00
await Task.Delay(5000);
2021-07-31 22:27:59 +05:00
}
}
2021-08-01 22:56:52 +05:00
while (true);
2021-07-31 22:27:59 +05:00
}
2021-08-01 22:56:52 +05:00
log.Info("End day: " + currDir);
2021-08-01 19:48:09 +05:00
SaveCurrData(nameCurrDate, currDate.Value);
currDate = currDate.Value.AddDays(1);
2021-08-02 23:01:18 +05:00
await Task.Delay(5000);
2021-07-31 22:27:59 +05:00
}
catch (Exception e)
{
2021-08-01 22:56:52 +05:00
log.Warn(e.Message);
2021-08-02 23:01:18 +05:00
flagcycle = true;
netClient.Close();
netClient = new NETClient(IpSTP, PortSTP);
2021-08-01 19:48:09 +05:00
await Task.Delay(1000 * 60 * 5);
2021-07-31 22:27:59 +05:00
}
}
2021-08-01 19:48:09 +05:00
do
{
log.Info("Wait next day.");
await Task.Delay(1000 * 60 * 60);
} while (!(currDate.Value < DateTime.Now.AddDays(-1)));
2021-08-02 23:01:18 +05:00
currDate.Value.AddDays(-15);
2021-08-01 19:48:09 +05:00
SaveCurrData(nameCurrDate, currDate.Value);
2021-07-31 22:27:59 +05:00
}
2021-08-02 23:01:18 +05:00
static async Task WorkData()
2021-07-31 22:27:59 +05:00
{
2021-08-02 23:01:18 +05:00
await Task.Delay(1000);
var IpSTP = "10.10.45.152";
var PortSTP = 1070;
NETClient netClient = new NETClient(IpSTP, PortSTP);
var mainDir = Path.Combine(Directory.GetCurrentDirectory(), "archive");
var nameCurrDate = "data";
var currDate = GetCurrData(nameCurrDate);
if (!currDate.HasValue)
currDate = new DateTime(2001, 02, 01);
var flagcycle = false;
2021-08-03 06:28:06 +05:00
{
log.Info("Connect to archive.");
await CreateConnectionNFS(mainDir);
}
2021-08-02 23:01:18 +05:00
while (currDate.Value < DateTime.Now.AddDays(-1))
{
try
{
2021-08-03 06:28:06 +05:00
/*while(DateTime.Now.Hour < 12)
2021-08-02 23:01:18 +05:00
{
log.Info("Await 12:00.");
await Task.Delay(15000 * 60);
2021-08-03 06:28:06 +05:00
}*/
2021-08-02 23:01:18 +05:00
var subDir = Path.Combine(mainDir, "data",
currDate.Value.Year.ToString("D4"),
currDate.Value.Month.ToString("D2"),
currDate.Value.Day.ToString("D2"));
log.Info("Check dir: " + subDir);
2021-08-03 06:28:06 +05:00
if (Directory.Exists(Path.Combine(mainDir, "data"))) {
if (Directory.Exists(subDir))
{
var listFiles = Directory.GetFiles(subDir);
foreach (var fileDir in listFiles)
2021-08-02 23:01:18 +05:00
{
2021-08-03 06:28:06 +05:00
log.Info("Get file: " + fileDir);
var fileStruct = File.ReadAllBytes(fileDir);
log.Info("Send file to API: " + fileDir);
while (!SendData(currDate.Value, Path.GetFileName(fileDir), fileStruct))
{
log.Warn("Can't send data to API.");
await Task.Delay(10000);
}
2021-08-02 23:01:18 +05:00
}
2021-08-03 06:28:06 +05:00
}
log.Info("End day: " + subDir);
SaveCurrData(nameCurrDate, currDate.Value);
currDate = currDate.Value.AddDays(1);
await Task.Delay(1000);
}
else
{
log.Warn("Archive not exist.");
2021-08-02 23:01:18 +05:00
}
}
catch (Exception e)
{
log.Warn(e.Message);
}
}
do
{
log.Info("Wait next day.");
await Task.Delay(1000 * 60 * 60);
} while (!(currDate.Value < DateTime.Now.AddDays(-1)));
currDate.Value.AddDays(-15);
SaveCurrData(nameCurrDate, currDate.Value);
}
2021-08-03 06:28:06 +05:00
static async Task ConnectNFS(string dir)
2021-08-02 23:01:18 +05:00
{
var dirCreated = false;
while (!dirCreated)
{
try
{
dirCreated = Directory.Exists(Path.Combine(dir));
if (!dirCreated) Directory.CreateDirectory(dir);
}
catch (Exception e)
{
log.Warn(e.Message);
log.Warn("Can't create directory");
await Task.Delay(60000);
}
}
var connected = false;
while (!connected)
{
try
2021-08-01 19:48:09 +05:00
{
2021-08-02 23:01:18 +05:00
var procD = new Process
2021-08-01 19:48:09 +05:00
{
2021-08-02 23:01:18 +05:00
StartInfo = new ProcessStartInfo
{
FileName = "/usr/bin/umount",
Arguments = dir,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
}
2021-08-01 19:48:09 +05:00
};
2021-08-02 23:01:18 +05:00
var procC = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "/usr/bin/mount",
Arguments = "-t nfs 10.10.45.236:/archiv " + dir,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
},
};
if (!procC.Start())
{
log.Warn("Can't start mount command.");
await Task.Delay(60000);
continue;
}
var answer = procC.StandardError.ReadToEnd() + procC.StandardOutput.ReadToEnd();
connected = string.IsNullOrEmpty(answer);
if (connected)
{
log.Info("Connect Success");
continue;
}
else log.Info(answer);
if (!procD.Start())
{
log.Warn("Can't start umount command.");
await Task.Delay(60000);
continue;
}
answer = procC.StandardError.ReadToEnd() + procC.StandardOutput.ReadToEnd();
log.Info(string.IsNullOrEmpty(answer) ? "NFS disconnected." : answer);
}
catch (Exception e)
{
log.Warn(e.Message);
log.Warn("Can't connect to NFS.");
await Task.Delay(60000);
2021-08-01 19:48:09 +05:00
}
}
2021-08-02 23:01:18 +05:00
}
2021-08-01 19:48:09 +05:00
2021-08-02 23:01:18 +05:00
static HttpWebRequest GetRequest(string path, bool useProxy = true)
{
HttpWebRequest clientReq = (HttpWebRequest)WebRequest.Create(path);
clientReq.Method = "POST";
clientReq.ContentType = "application/json; charset=utf-8";
if (useProxy)
{
clientReq.Proxy = new WebProxy("194.226.128.245", 3128)
{
BypassProxyOnLocal = false,
Credentials = new NetworkCredential("user4", "user4")
};
}
return clientReq;
}
static bool SendPasport(Pasport pasp)
{
2021-07-31 22:27:59 +05:00
try
{
{
log.Info("Check pasport on remote API server.");
var req = JsonConvert.SerializeObject(
2021-08-01 19:48:09 +05:00
new PasportCheckApi()
2021-07-31 22:27:59 +05:00
{
2021-08-01 19:48:09 +05:00
Status = true,
2021-07-31 22:27:59 +05:00
DateAndTime = pasp.dEnd.Value,
2021-08-01 19:48:09 +05:00
Name = string.IsNullOrEmpty(pasp.nplav) ? pasp.numVDP.Value.ToString("D2") : pasp.nplav
2021-07-31 22:27:59 +05:00
});
var reqArr = Encoding.UTF8.GetBytes(req);
2021-08-01 19:48:09 +05:00
HttpWebRequest clientReq = GetRequest("https://vsmpo.mbucb.ru/api/pasport/check");
2021-07-31 22:27:59 +05:00
clientReq.ContentLength = reqArr.Length;
using (var stream = clientReq.GetRequestStream())
{
stream.Write(reqArr, 0, reqArr.Length);
}
string response = "";
using (var clientRes = (HttpWebResponse)clientReq.GetResponse())
{
using (var readStream = new StreamReader(clientRes.GetResponseStream(), Encoding.UTF8))
{
response = readStream.ReadToEnd();
readStream.Close();
clientRes.Close();
}
}
2021-08-01 19:48:09 +05:00
var rep = JsonConvert.DeserializeObject<PasportCheckClient>(response);
2021-07-31 22:27:59 +05:00
if (!rep.Status) return false;
2021-08-01 19:48:09 +05:00
ulong paspSum = 0;
var paspArr = pasp.PaspByte;
foreach (var b in paspArr)
paspSum += b;
if (rep.Exist && rep.PaspSum == paspSum) return true;
if (!rep.Exist)
log.Info("API: Pasport not exist.");
if (rep.Exist && rep.PaspSum != paspSum)
log.Info("API: Wrong size pasport.");
2021-07-31 22:27:59 +05:00
}
{
log.Info("Send pasport to remote API server.");
var req = JsonConvert.SerializeObject(
2021-08-01 19:48:09 +05:00
new PasportCreateApi()
2021-07-31 22:27:59 +05:00
{
2021-08-01 19:48:09 +05:00
Status = true,
2021-07-31 22:27:59 +05:00
Pasp = pasp
});
var reqArr = Encoding.UTF8.GetBytes(req);
2021-08-01 19:48:09 +05:00
HttpWebRequest clientReq = GetRequest("https://vsmpo.mbucb.ru/api/pasport/create");
2021-07-31 22:27:59 +05:00
clientReq.ContentLength = reqArr.Length;
using (var stream = clientReq.GetRequestStream())
{
stream.Write(reqArr, 0, reqArr.Length);
}
string response = "";
using (var clientRes = (HttpWebResponse)clientReq.GetResponse())
{
using (var readStream = new StreamReader(clientRes.GetResponseStream(), Encoding.UTF8))
{
response = readStream.ReadToEnd();
readStream.Close();
clientRes.Close();
}
}
2021-08-01 19:48:09 +05:00
var rep = JsonConvert.DeserializeObject<PasportCreateClient>(response);
2021-07-31 22:27:59 +05:00
if (!rep.Status) return false;
}
return true;
}
catch (Exception e)
{
log.Warn(e.Message);
return false;
}
}
2021-08-02 23:01:18 +05:00
static bool SendData(DateTime dateAndTime, string fileName, byte[] fileStruct)
{
try
{
{
log.Info("Check data on remote API server.");
var req = JsonConvert.SerializeObject(
new DataCheckApi()
{
Status = true,
DateAndTime = dateAndTime,
Name = fileName
});
var reqArr = Encoding.UTF8.GetBytes(req);
HttpWebRequest clientReq = GetRequest("https://vsmpo.mbucb.ru/api/data/check");
clientReq.ContentLength = reqArr.Length;
using (var stream = clientReq.GetRequestStream())
{
stream.Write(reqArr, 0, reqArr.Length);
}
string response = "";
using (var clientRes = (HttpWebResponse)clientReq.GetResponse())
{
using (var readStream = new StreamReader(clientRes.GetResponseStream(), Encoding.UTF8))
{
response = readStream.ReadToEnd();
readStream.Close();
clientRes.Close();
}
}
var rep = JsonConvert.DeserializeObject<DataCheckClient>(response);
if (!rep.Status) return false;
if (rep.Exist && rep.DataSize == (ulong)fileStruct.Length) return true;
if (!rep.Exist)
log.Info("API: Data not exist.");
if (rep.Exist && rep.DataSize != (ulong)fileStruct.Length)
log.Info("API: Wrong size data.");
}
{
log.Info("Send data to remote API server.");
var req = JsonConvert.SerializeObject(
new DataCreateApi()
{
Status = true,
DateAndTime = dateAndTime,
Name = fileName,
Struct = fileStruct
});
var reqArr = Encoding.UTF8.GetBytes(req);
2021-07-31 22:27:59 +05:00
2021-08-02 23:01:18 +05:00
HttpWebRequest clientReq = GetRequest("https://vsmpo.mbucb.ru/api/data/create");
clientReq.ContentLength = reqArr.Length;
using (var stream = clientReq.GetRequestStream())
{
stream.Write(reqArr, 0, reqArr.Length);
}
string response = "";
using (var clientRes = (HttpWebResponse)clientReq.GetResponse())
{
using (var readStream = new StreamReader(clientRes.GetResponseStream(), Encoding.UTF8))
{
response = readStream.ReadToEnd();
readStream.Close();
clientRes.Close();
}
}
var rep = JsonConvert.DeserializeObject<DataCreateClient>(response);
if (!rep.Status) return false;
}
return true;
}
catch (Exception e)
{
log.Warn(e.Message);
return false;
}
}
2021-07-31 22:27:59 +05:00
static void LogConf()
{
var conf = new LoggingConfiguration();
var logcon = new ConsoleTarget()
{
Name = "logcon",
Layout = @"${time}|${level:uppercase=true}|${logger}|${message}${when:when=length('${exception}')>0:Inner=|}${exception:format=ToString,StackTrace}"
};
conf.AddRule(LogLevel.Trace, LogLevel.Fatal, logcon);
LogManager.Configuration = conf;
}
2021-08-01 19:48:09 +05:00
static bool SaveCurrData(string name, DateTime currDate)
{
try
{
var fileForSave = Path.Combine(Directory.GetCurrentDirectory(), "currentState");
var currStrings = Array.Empty<string>();
if (File.Exists(fileForSave))
currStrings = File.ReadAllLines(fileForSave, Encoding.UTF8);
var newString =
name + ':' +
currDate.Year.ToString("D4") +
currDate.Month.ToString("D2") +
currDate.Day.ToString("D2");
for (var i = 0; i < currStrings.Length; i++)
{
var splitString = currStrings[i].Split(':');
if (splitString.Length != 2) continue;
if (splitString[0] != name) continue;
currStrings[i] = newString;
newString = null;
break;
}
if (!string.IsNullOrEmpty(newString))
{
Array.Resize(ref currStrings, currStrings.Length + 1);
currStrings[currStrings.Length - 1] = newString;
}
File.WriteAllLines(fileForSave, currStrings, Encoding.UTF8);
return true;
}
catch (Exception e)
{
2021-08-01 22:56:52 +05:00
log.Warn(e.Message);
2021-08-01 19:48:09 +05:00
return false;
}
}
static DateTime? GetCurrData(string name)
{
try
{
var file = Path.Combine(Directory.GetCurrentDirectory(), "currentState");
if (!File.Exists(file))
{
log.Info("State file not exist.");
return null;
}
var listStrings = File.ReadAllLines(file, Encoding.UTF8);
for(var i = 0; i < listStrings.Length; i++)
{
var splitString = listStrings[i].Split(':');
if (splitString.Length != 2) continue;
if (splitString[0] != name) continue;
if (
!int.TryParse(splitString[1].Substring(0, 4), out int year) ||
!int.TryParse(splitString[1].Substring(4, 2), out int month) ||
!int.TryParse(splitString[1].Substring(6, 2), out int day))
{
log.Warn("Wron format state string.");
return null;
}
return new DateTime(year, month, day);
}
log.Info("State not exist.");
return null;
}
catch (Exception e)
{
2021-08-01 22:56:52 +05:00
log.Warn(e.Message);
2021-08-01 19:48:09 +05:00
return null;
}
}
2021-07-31 22:27:59 +05:00
}
}