PostService

This commit is contained in:
Mike Phares 2023-06-23 15:40:59 -07:00
parent 9452454b8a
commit 98c6262a4d
19 changed files with 338 additions and 6 deletions

View File

@ -3,8 +3,68 @@
# apt-get-install
```bash
sudo -i
apt-get install links unzip net-tools ufw nginx git -y
```
```bash
# Checking your Ubuntu Version
lsb_release -a
# There are several good, effective answers listed above.
# However, this is the mechanism I personally use -- apt-ftparchive.
# I'm documenting it here, in case I need it again in the future. Perhaps it might be useful to you.
# Creating the Archive Snapshot
# Create an instance of Ubuntu that closely mimics the target environment
# For example, an Ubuntu 12.04 64-bit instance in Amazon
# Start with a clean package environment
apt-get clean
# Update the package lists
apt-get update
# Download all package updates available
apt-get dist-upgrade --download-only
# recursive-dependencies-of-a-debian-package
apt-cache depends --recurse --no-recommends --no-suggests --no-conflicts --no-breaks --no-replaces --no-enhances smbclient | grep "^\w" | sort -u
# Download all relevant packages and dependencies
apt-get install --download-only byobu run-one bikeshed dotdee powernap
apt-get install --download-only --reinstall e2fsprogs fwupd grub-common libcups2 libglib2.0-0 netplan.io python3-systemd rsyslog smbclient
apt-get install --download-only --reinstall cdebconf coreutils debconf dpkg e2fsprogs fwupd gcc-10-base grub-common install-info libacl1 libarchive13 libasn1-8-heimdal libattr1 libaudit-common libaudit1 libavahi-client3 libavahi-common-data libavahi-common3 libbsd0 libbz2-1.0 libc6 libcap-ng0 libcap2 libcom-err2 libcrypt1 libcups2 libdb5.3 libdbus-1-3 libdebian-installer4 libexpat1 libffi7 libfuse2 libgcc-s1 libgcrypt20 libglib2.0-0 libgmp10 libgnutls30 libgpg-error0 libgssapi-krb5-2 libgssapi3-heimdal libhcrypto4-heimdal libheimbase1-heimdal libheimntlm0-heimdal libhogweed5 libhx509-5-heimdal libicu66 libidn2-0 libjansson4 libk5crypto3 libkeyutils1 libkrb5-26-heimdal libkrb5-3 libkrb5support0 libldap-2.4-2 libldap-common libldb2 liblmdb0 liblz4-1 liblzma5 libmpdec2 libncursesw6 libnetplan0 libnettle7 libnewt0.52 libp11-kit0 libpam0g libpcre2-8-0 libpopt0 libpython3-stdlib libpython3.8 libpython3.8-minimal libpython3.8-stdlib libreadline8 libroken18-heimdal libsasl2-2 libsasl2-modules-db libselinux1 libslang2 libsmbclient libsqlite3-0 libssl1.1 libstdc++6 libsystemd0 libtalloc2 libtasn1-6 libtdb1 libtevent0 libtextwrap1 libtinfo6 libtss2-esys0 libunistring2 libuuid1 libwbclient0 libwind0-heimdal libxml2 libzstd1 mime-support netplan.io perl-base python3 python3-ldb python3-minimal python3-systemd python3-talloc python3.8 python3.8-minimal readline-common rsyslog samba-common samba-libs sensible-utils smbclient tar tzdata ucf zlib1g
# Create the package manifest
(cd /var/cache/apt/archives/ && apt-ftparchive packages . ) | tee /var/cache/apt/archives/Packages
ls /var/cache/apt/archives
# Create an archive of the packages
cd /home/unity4
tar cvf snapshot.tar -C /var/cache/apt archives/
ls /home/unity4
```
```bash
scp unity4@unity4:/home/unity4/snapshot.tar D:/Tmp/Phares/snapshot.tar
```
```bash
pscp D:/Tmp/Phares/snapshot.tar unity5@unity5:/home/unity5/snapshot.tar
```
```bash
# Using the Archive Snapshot on the Offline Target System
# Through some mechanism, you will need to get the snapshot.tar from the source to the target system.
# Perhaps on a USB stick, or otherwise.
# Extract the archive on the target system (in this case, in /home/ubuntu)
cd /home/unity5
tar xvf snapshot.tar
cd /home/unity5/archives
ls /home/unity5/archives
dpkg -i *.deb
dpkg -i smbclient_2%3a4.15.13+dfsg-0ubuntu0.20.04.2_amd64.deb
# Add the local, offline source to /etc/apt/sources.list
echo "deb file:/home/unity5/archives /" | tee -a /etc/apt/sources.list
# Update the package list
apt-get update
# Install the packages as desired
apt-get install byobu run-one bikeshed dotdee powernap
apt-get install smbclient
```
## Sub-tasks

View File

@ -34,6 +34,20 @@ network:
addresses: [192.168.0.1, 8.8.8.8, 4.4.4.4]
```
```bash
network:
version: 2
renderer: networkd
ethernets:
eno1:
addresses:
- 192.168.0.12/24
routes:
- to: default
via: 192.168.0.1
nameservers:
addresses: [192.168.0.1, 8.8.8.8, 4.4.4.4]
```
```bash
netplan apply
ip addr flush eno1
# soft reset
@ -52,6 +66,20 @@ network:
nameservers:
addresses: [10.95.128.11, 10.64.152.171, 8.8.8.8, 4.4.4.4]
```
```bash
network:
version: 2
renderer: networkd
ethernets:
eno1:
addresses:
- 10.95.154.18/24
routes:
- to: default
via: 10.95.154.1
nameservers:
addresses: [10.95.128.11, 10.64.152.171, 8.8.8.8, 4.4.4.4]
```
## Sub-tasks

View File

@ -11,9 +11,30 @@ mkdir /var/www
mkdir /var/www/Barcode-Host
mkdir /var/www/Barcode-Host/Server
cd /home/unity4/Barcode-Host/Server
dotnet user-secrets init
dotnet user-secrets set "SerialPortName" ""
dotnet user-secrets set "RootPassword" "asdf"
dotnet user-secrets set "EquipmentName" "BIORAD4"
dotnet user-secrets set "FileShare" "\\\mestsa003.infineon.com\\EC_Metrology_Si\\BarcodeHost\\API"
dotnet user-secrets list
dotnet publish --configuration Release --output /var/www/Barcode-Host/Server
cd /var/www/Barcode-Host/Server
dotnet /var/www/Barcode-Host/Server/Barcode.Host.Server.dll
systemctl start barcode-host.service
```
```bash
nano /etc/fstab
10.95.176.46:EC_Metrology_Si /var/locally-mounted/eaf-dev.mes.infineon.com nfs defaults 0 0
mount /var/locally-mounted/eaf-dev.mes.infineon.com nfs defaults 0 0
mkdir /mnt/share
mkdir /mnt/share/nmshare
mkdir /mnt/share/nmshare/eaf-dev.mes.infineon.com
apt install cifs-utils
mount.cifs //10.95.128.34/EC_Metrology_Si /mnt/share/nmshare/eaf-dev.mes.infineon.com
mount -t cifs -o rw,guest,vers=1.0 //10.95.128.34/EC_Metrology_Si /mnt/share/nmshare/eaf-dev.mes.infineon.com
smbclient --list=10.95.128.34 --no-pass
apt install smbclient
ecmesEAF-10.95.128.34-mestsa07ec(A-Both)
```
```conf
2023-06-03 16:02:25.011 -07:00 [Information] (Barcode.Host.Server.Program.) () () Starting Web Application

View File

@ -14,4 +14,4 @@ do-release-upgrade
- [x] phares3757
- [x] unity4
- [x] unity5
- [ ] unity5

View File

@ -0,0 +1,52 @@
using Barcode.Host.Shared.Models;
using Barcode.Host.Shared.Models.Stateless;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
namespace Barcode.Host.Tests;
[TestClass]
public class UnitTestFileService
{
#pragma warning disable CS8618
private static ILogger _Logger;
private static TestContext _TestContext;
private static WebApplicationFactory<Server.Program> _WebApplicationFactory;
#pragma warning restore
[ClassInitialize]
public static void ClassInitAsync(TestContext testContext)
{
_TestContext = testContext;
_Logger = Log.ForContext<UnitTestFileService>();
_WebApplicationFactory = new WebApplicationFactory<Server.Program>();
}
private static void NonThrowTryCatch()
{
try
{ throw new Exception(); }
catch (Exception) { }
}
#if DEBUG
[Ignore]
#endif
[TestMethod]
public void GetWrite()
{
_Logger.Information("Starting Web Application");
IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider;
Server.Models.AppSettings appSettings = serviceProvider.GetRequiredService<Server.Models.AppSettings>();
IFileService fileService = serviceProvider.GetRequiredService<IFileService>();
Notification notification = new(KeyPressEvent: null, "Test");
fileService.Write(appSettings.EquipmentName, appSettings.FileShare, calendar: null, notification);
_Logger.Information($"{_TestContext?.TestName} completed");
NonThrowTryCatch();
}
}

View File

@ -0,0 +1,53 @@
using Barcode.Host.Shared.Models;
using Barcode.Host.Shared.Models.Stateless;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
namespace Barcode.Host.Tests;
[TestClass]
public class UnitTestPostService
{
#pragma warning disable CS8618
private static ILogger _Logger;
private static TestContext _TestContext;
private static WebApplicationFactory<Server.Program> _WebApplicationFactory;
#pragma warning restore
[ClassInitialize]
public static void ClassInitAsync(TestContext testContext)
{
_TestContext = testContext;
_Logger = Log.ForContext<UnitTestPostService>();
_WebApplicationFactory = new WebApplicationFactory<Server.Program>();
}
private static void NonThrowTryCatch()
{
try
{ throw new Exception(); }
catch (Exception) { }
}
#if DEBUG
[Ignore]
#endif
[TestMethod]
public void GetPostTo()
{
_Logger.Information("Starting Web Application");
HttpClient httpClient = _WebApplicationFactory.CreateClient();
IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider;
Server.Models.AppSettings appSettings = serviceProvider.GetRequiredService<Server.Models.AppSettings>();
IPostService postService = serviceProvider.GetRequiredService<IPostService>();
Notification notification = new(KeyPressEvent: null, "Test");
_ = postService.Post(appSettings.PostTo, httpClient, notification);
_Logger.Information($"{_TestContext?.TestName} completed");
NonThrowTryCatch();
}
}

View File

@ -6,6 +6,7 @@ using Barcode.Host.Shared.Models;
using Barcode.Host.Shared.Models.Stateless;
using Microsoft.AspNetCore.SignalR;
using Serilog.Context;
using System.Globalization;
namespace Barcode.Host.Server.HostedService;
@ -15,28 +16,36 @@ public class TimedHostedService : IHostedService, IAggregateInputReader, IDispos
public event InputReader.RaiseKeyPress? OnKeyPress;
private readonly int _ExecutionCount;
protected readonly Calendar _Calendar;
private readonly AppSettings _AppSettings;
private readonly IFileService _FileService;
private readonly IPostService _PostService;
private readonly ISerialService _SerialService;
private readonly ILastScanService _LastScanService;
private readonly ILogger<TimedHostedService> _Logger;
private readonly IHttpClientFactory _HttpClientFactory;
private readonly ILinuxGroupManager _LinuxGroupManager;
private readonly IHubContext<NotificationHub> _HubContext;
private readonly Dictionary<string, InputReader> _Readers;
private readonly Dictionary<EventCode, char> _CharToEventCodes;
private readonly List<(string MethodName, Timer Timer)> _Timers;
public TimedHostedService(ILogger<TimedHostedService> logger, AppSettings appSettings, ILinuxGroupManager linuxGroupManager, ILastScanService lastScanService, ISerialService serialService, IHubContext<NotificationHub> hubContext)
public TimedHostedService(ILogger<TimedHostedService> logger, AppSettings appSettings, ILinuxGroupManager linuxGroupManager, ILastScanService lastScanService, ISerialService serialService, IHttpClientFactory httpClientFactory, IHubContext<NotificationHub> hubContext, IFileService fileService, IPostService postService)
{
_Timers = new();
_Readers = new();
_Logger = logger;
_Readers = new();
_ExecutionCount = 0;
_HubContext = hubContext;
_CharToEventCodes = new();
_AppSettings = appSettings;
_FileService = fileService;
_PostService = postService;
_SerialService = serialService;
_LastScanService = lastScanService;
_HttpClientFactory = httpClientFactory;
_LinuxGroupManager = linuxGroupManager;
_Calendar = new CultureInfo("en-US").Calendar;
Timer writeTimer = new(Write, null, Timeout.Infinite, Timeout.Infinite);
Timer scanForNewInputsTimer = new(ScanForNewInputs, null, Timeout.Infinite, Timeout.Infinite);
if (!string.IsNullOrEmpty(_AppSettings.SerialPortName))
@ -122,6 +131,13 @@ public class TimedHostedService : IHostedService, IAggregateInputReader, IDispos
{
Notification notification = new(e, result.Results);
_ = _HubContext.Clients.All.SendAsync(nameof(NotificationHub.NotifyAll), notification);
if (!string.IsNullOrEmpty(_AppSettings.FileShare))
_FileService.Write(_AppSettings.EquipmentName, _AppSettings.FileShare, _Calendar, notification);
if (!string.IsNullOrEmpty(_AppSettings.PostTo))
{
HttpClient httpClient = _HttpClientFactory.CreateClient(nameof(TimedHostedService));
_ = _PostService.PostAsync(_AppSettings.PostTo, httpClient, notification);
}
}
}
}

View File

@ -6,8 +6,10 @@ public record AppSettings(string BuildNumber,
string Company,
int ClearLastScanServiceAfter,
string DeviceNameEndsWith,
string EquipmentName,
int ExpectedScanLengthA,
int ExpectedScanLengthB,
string FileShare,
string GitCommitSeven,
string LinuxDevicePath,
bool IsDevelopment,
@ -16,6 +18,7 @@ public record AppSettings(string BuildNumber,
string MockRoot,
string MonAResource,
string MonASite,
string PostTo,
string RootPassword,
string SerialPortName,
string URLs,

View File

@ -12,8 +12,10 @@ public class AppSettings
[Display(Name = "Company"), Required] public string Company { get; set; }
[Display(Name = "Last Scan Service Clear After"), Required] public int? ClearLastScanServiceAfter { get; set; }
[Display(Name = "Device Name Ends With"), Required] public string DeviceNameEndsWith { get; set; }
[Display(Name = "Equipment Name"), Required] public string EquipmentName { get; set; }
[Display(Name = "ExpectedScanLengthA"), Required] public int? ExpectedScanLengthA { get; set; }
[Display(Name = "ExpectedScanLengthB"), Required] public int? ExpectedScanLengthB { get; set; }
[Display(Name = "File Share"), Required] public string FileShare { get; set; }
[Display(Name = "Git Commit Seven"), Required] public string GitCommitSeven { get; set; }
[Display(Name = "Linux Device Path"), Required] public string LinuxDevicePath { get; set; }
[Display(Name = "Is Development"), Required] public bool? IsDevelopment { get; set; }
@ -22,6 +24,7 @@ public class AppSettings
[Display(Name = "Mock Root"), Required] public string MockRoot { get; set; }
[Display(Name = "MonA Resource"), Required] public string MonAResource { get; set; }
[Display(Name = "MonA Site"), Required] public string MonASite { get; set; }
[Display(Name = "PostTo"), Required] public string PostTo { get; set; }
[Display(Name = "RootPassword"), Required] public string RootPassword { get; set; }
[Display(Name = "Serial Port Name"), Required] public string SerialPortName { get; set; }
[Display(Name = "URLs"), Required] public string URLs { get; set; }
@ -49,10 +52,14 @@ public class AppSettings
throw new NullReferenceException(nameof(ClearLastScanServiceAfter));
if (appSettings.DeviceNameEndsWith is null)
throw new NullReferenceException(nameof(DeviceNameEndsWith));
if (appSettings.EquipmentName is null)
throw new NullReferenceException(nameof(EquipmentName));
if (appSettings.ExpectedScanLengthA is null)
throw new NullReferenceException(nameof(ExpectedScanLengthA));
if (appSettings.ExpectedScanLengthB is null)
throw new NullReferenceException(nameof(ExpectedScanLengthB));
if (appSettings.FileShare is null)
throw new NullReferenceException(nameof(FileShare));
if (appSettings.GitCommitSeven is null)
throw new NullReferenceException(nameof(GitCommitSeven));
if (appSettings.LinuxDevicePath is null)
@ -69,6 +76,8 @@ public class AppSettings
throw new NullReferenceException(nameof(MonAResource));
if (appSettings.MonASite is null)
throw new NullReferenceException(nameof(MonASite));
if (appSettings.PostTo is null)
throw new NullReferenceException(nameof(PostTo));
if (appSettings.RootPassword is null)
throw new NullReferenceException(nameof(RootPassword));
if (appSettings.SerialPortName is null)
@ -84,8 +93,10 @@ public class AppSettings
appSettings.Company,
appSettings.ClearLastScanServiceAfter.Value,
appSettings.DeviceNameEndsWith,
appSettings.EquipmentName,
appSettings.ExpectedScanLengthA.Value,
appSettings.ExpectedScanLengthB.Value,
appSettings.FileShare,
appSettings.GitCommitSeven,
appSettings.LinuxDevicePath,
appSettings.IsDevelopment.Value,
@ -94,6 +105,7 @@ public class AppSettings
appSettings.MockRoot,
appSettings.MonAResource,
appSettings.MonASite,
appSettings.PostTo,
appSettings.RootPassword,
appSettings.SerialPortName,
appSettings.URLs,

View File

@ -1,5 +1,10 @@
@page
<div class="container">
<div class="row p-1">
<div class="col-6">
<h1 style="text-align:center">Scan RDS barcode before starting BioRad</h1>
</div>
</div>
<div class="row p-1">
<div class="col-6">
<h1 id="data" style="text-align:center"></h1>

View File

@ -6,7 +6,7 @@
<title>Barcode Host</title>
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
</head>
<body>
<body style="background-color: #191919; color: white">
<div class="container">
<main role="main" class="pb-3">
@RenderBody()

View File

@ -58,6 +58,10 @@ public class Program
_ = webApplicationBuilder.Services.AddSignalR();
_ = webApplicationBuilder.Services.AddControllersWithViews();
_ = webApplicationBuilder.Services.AddSingleton(_ => appSettings);
_ = webApplicationBuilder.Services.AddHttpClient();
_ = webApplicationBuilder.Services.AddSingleton<IFileService, FileService>();
_ = webApplicationBuilder.Services.AddSingleton<IPostService, PostService>();
_ = webApplicationBuilder.Services.AddSingleton<ISerialService, SerialService>();
_ = webApplicationBuilder.Services.AddSingleton<ISerialService, SerialService>();
_ = webApplicationBuilder.Services.AddSingleton<ILastScanService, LastScanService>();
_ = webApplicationBuilder.Services.AddSingleton<ILinuxGroupManager, LinuxGroupManager>();

View File

@ -0,0 +1,21 @@
using Barcode.Host.Shared.Models;
using Barcode.Host.Shared.Models.Stateless;
using System.Globalization;
namespace Barcode.Host.Server.Services;
public class FileService : IFileService
{
void IFileService.Write(string equipmentName, string fileShare, Calendar? calendar, Notification notification)
{
DateTime dateTime = DateTime.Now;
calendar ??= new CultureInfo("en-US").Calendar;
string weekOfYear = $"{dateTime:yyyy}_Week_{calendar.GetWeekOfYear(dateTime, CalendarWeekRule.FirstDay, DayOfWeek.Sunday):00}";
string directory = Path.Combine(fileShare, weekOfYear, dateTime.ToString("yyyy-MM-dd_HH"));
if (!Directory.Exists(directory))
_ = Directory.CreateDirectory(directory);
File.WriteAllText(Path.Combine(directory, $"{equipmentName}.csv"), notification.LastScanServiceResultValue);
}
}

View File

@ -0,0 +1,34 @@
using Barcode.Host.Shared.Models;
using Barcode.Host.Shared.Models.Stateless;
using System.Text;
namespace Barcode.Host.Server.Services;
public class PostService : IPostService
{
private static Task<HttpResponseMessage> PostAsync(string postTo, HttpClient httpClient, Notification notification)
{
Task<HttpResponseMessage> result;
string json = System.Text.Json.JsonSerializer.Serialize(notification);
StringContent stringContent = new(json, Encoding.UTF8, "application/json");
result = httpClient.PostAsync(postTo, stringContent);
return result;
}
Task<HttpResponseMessage> IPostService.PostAsync(string postTo, HttpClient httpClient, Notification notification)
{
Task<HttpResponseMessage> result = PostAsync(postTo, httpClient, notification);
return result;
}
HttpResponseMessage IPostService.Post(string postTo, HttpClient httpClient, Notification notification)
{
HttpResponseMessage result;
Task<HttpResponseMessage> httpResponseMessage = PostAsync(postTo, httpClient, notification);
httpResponseMessage.Wait();
result = httpResponseMessage.Result;
return result;
}
}

View File

@ -1,11 +1,13 @@
{
"BuildNumber": "1",
"Company": "Infineon Technologies Americas Corp.",
"ClearLastScanServiceAfter": 250,
"DeviceNameEndsWith": "Symbol Bar Code Scanner",
"EquipmentName": "",
"ExpectedScanLengthA": 8,
"ExpectedScanLengthB": 14,
"ExpectedScanLengthBExample": "1TO172125.1.11",
"ClearLastScanServiceAfter": 250,
"FileShare": "",
"GitCommitSeven": "1234567",
"LinuxDevicePath": "/proc/bus/input/devices",
"Logging": {
@ -22,6 +24,7 @@
"MockRoot": "",
"MonAResource": "OI_Metrology_Viewer_EC",
"MonASite": "auc",
"PostTo": "",
"SerialPortName": "/dev/ttyUSB0",
"Serilog": {
"Using": [

View File

@ -24,5 +24,6 @@
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" />
</ItemGroup>
</Project>

View File

@ -2,4 +2,4 @@ using Barcode.Host.Shared.KeyboardMouse;
namespace Barcode.Host.Shared.Models;
public record Notification(KeyPressEvent KeyPressEvent, string LastScanServiceResultValue);
public record Notification(KeyPressEvent? KeyPressEvent, string LastScanServiceResultValue);

View File

@ -0,0 +1,10 @@
using System.Globalization;
namespace Barcode.Host.Shared.Models.Stateless;
public interface IFileService
{
void Write(string equipmentName, string fileShare, Calendar? calendar, Notification notification);
}

View File

@ -0,0 +1,9 @@
namespace Barcode.Host.Shared.Models.Stateless;
public interface IPostService
{
HttpResponseMessage Post(string postTo, HttpClient httpClient, Notification notification);
Task<HttpResponseMessage> PostAsync(string postTo, HttpClient httpClient, Notification notification);
}