Nodelist import update

This commit is contained in:
Deon George 2024-06-15 14:23:05 +10:00
parent df2873287c
commit 941117b342
5 changed files with 241 additions and 232 deletions

View File

@ -36,7 +36,6 @@ class NodelistImport extends Command
*/
public function handle():int
{
try {
return Job::dispatchSync(
is_numeric($x=$this->argument('file'))
? File::findOrFail($x)
@ -47,11 +46,5 @@ class NodelistImport extends Command
$this->option('test'),
$this->option('ignorecrc'),
);
} catch (\Exception $e) {
$this->error($e->getMessage());
return self::FAILURE;
}
}
}

View File

@ -13,13 +13,12 @@ use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use App\Models\{Address,Domain,File,Mailer,Nodelist,Setup,System,SystemZone,User,Zone};
use App\Models\{Address,Domain,File,Mailer,Nodelist,System,Zone};
use App\Traits\Import as ImportTrait;
class NodelistImport implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
use ImportTrait;
use Dispatchable,InteractsWithQueue,Queueable,SerializesModels,ImportTrait;
protected const LOGKEY = 'JNI';
private const importkey = 'nodelist';
@ -34,7 +33,11 @@ class NodelistImport implements ShouldQueue
private bool $ignore_crc;
/**
* Import Nodelist constructor.
* Import Nodelist from a file.
*
* A nodelist is treated as authoritative (it will add/update/delete details of existing entries), except where:
* + The system has a user owner (the user provides the authoritative information)
* + The system is a node of this instance (the admin provides the authoritative information)
*
* @param File|string $file
* @param string|null $domain
@ -74,30 +77,9 @@ class NodelistImport implements ShouldQueue
*/
public function handle()
{
$our_systems = SystemZone::select('system_id')
->get()
->pluck('system')
->flatten()
->pluck('addresses')
->flatten()
->filter(function($item) { return $item->active; })
->pluck('id');
$our_users = User::with(['systems.addresses'])
->get()
->pluck('systems')
->flatten()
->pluck('addresses')
->flatten()
->filter(function($item) { return $item->active; })
->pluck('id')
->diff($our_systems);
$our_addresses = our_address()->pluck('id');
// Get the file from the host
$file = $this->getFileFromHost(self::importkey,$this->file);
Log::debug(sprintf('%s:+ Loading file [%s] (%s).',static::LOGKEY,$file,getcwd()));
Log::debug(sprintf('%s:+ Loading file [%s].',static::LOGKEY,$file));
$lines = $this->getFileLines($file);
Log::debug(sprintf('%s:- Processing [%d] lines.',static::LOGKEY,$lines));
@ -125,49 +107,53 @@ class NodelistImport implements ShouldQueue
$date = Carbon::createFromFormat('D, M d, Y H:i',$matches[2].'0:00');
if ($date->dayOfYear != $matches[3]) {
if ($date->dayOfYear !== (int)$matches[3]) {
Log::error(sprintf('%s:! Nodelist date doesnt match [%d] (%d:%s).',static::LOGKEY,$matches[3],$date->dayOfYear,$date->format('Y-m-d')));
throw new \Exception('Nodelist date doesnt match for file: '.$this->file->id);
}
Log::alert(sprintf('%s:- Importing nodelist for [%s] dated [%s].',static::LOGKEY,$do->name,$date->format('Y-m-d')));
Log::info(sprintf('%s:- Importing nodelist for [%s] dated [%s].',static::LOGKEY,$do->name,$date->format('Y-m-d')));
// We'll only commit this if there were no errors
DB::beginTransaction();
$no = Nodelist::firstOrCreate(['date'=>$date,'domain_id'=>$do->id]);
if ($this->delete_recs)
$no->addresses()->detach();
elseif ($no->addresses->count()) {
Log::error($x=sprintf('%s:! Nodelist [%s] for [%s] has existing records [%d]',self::LOGKEY,$date,$do->name,$no->addresses->count()));
throw new \Exception($x);
}
$mailer_binkp = Mailer::where('name','BINKP')->singleOrFail();
$mailer_emsi = Mailer::where('name','EMSI')->singleOrFail();
$p = $c = 0;
$region = NULL;
$host = NULL;
$hub_id = NULL;
$ishub = FALSE;
$zo = NULL;
$tocrc = '';
$mailer_binkp = Mailer::where('name','BINKP')->singleOrFail();
$mailer_emsi = Mailer::where('name','EMSI')->singleOrFail();
$ho = NULL;
$crc_check = '';
while (! feof($fh)) {
$line = stream_get_line($fh,0,"\r\n");
$tocrc .= $line."\r\n";
$crc_check .= $line."\r\n";
// Lines beginning with a semicolon(;) are comments
if ((! $line) OR preg_match('/^;/',$line) OR ($line === chr(0x1a)))
continue;
// Remove any embedded CR and BOM
// Remove any embedded CR and UTF-8 BOM
$line = str_replace("\r",'',$line);
$line = preg_replace('/^\x{feff}/u','',$line);
$c++;
Log::debug(sprintf('%s:%s',self::LOGKEY,$line));
Log::debug(sprintf('%s:| %s',self::LOGKEY,$line));
$fields = str_getcsv(trim($line));
@ -182,10 +168,9 @@ class NodelistImport implements ShouldQueue
switch ($fields[0]) {
case 'Zone':
$zone = (int)$fields[1];
Zone::unguard();
$zo = Zone::firstOrNew([
'zone_id'=>$zone,
'zone_id'=>(int)$fields[1],
'domain_id'=>$do->id,
'active'=>TRUE,
]);
@ -193,26 +178,26 @@ class NodelistImport implements ShouldQueue
$region = 0;
$host = 0;
$hub_id = NULL;
$ishub = FALSE;
break;
case 'Region':
$region = (int)$fields[1];
$host = (int)$fields[1];
$hub_id = NULL;
$ishub = FALSE;
break;
case 'Host':
$host = (int)$fields[1];
$hub_id = NULL;
$ishub = FALSE;
break;
case 'Hub':
$node = (int)$fields[1];
$role = Address::NODE_HC;
$ishub = TRUE;
break;
@ -234,6 +219,7 @@ class NodelistImport implements ShouldQueue
break;
// Normal Node
case '':
$node = $fields[1];
break;
@ -243,14 +229,15 @@ class NodelistImport implements ShouldQueue
continue 2;
}
if (! $zone) {
if (! $zo) {
Log::error(sprintf('%s:! Zone NOT set, ignoring record...',self::LOGKEY));
continue;
}
// Find or load an existing entry
Address::unguard();
$ao = Address::firstOrNew([
'zone_id' => $zo->id,
'zone_id' => $zo?->id,
'host_id' => $host,
'node_id' => $node,
'point_id' => 0,
@ -258,42 +245,46 @@ class NodelistImport implements ShouldQueue
]);
Address::reguard();
if ($ao->region_id && ($ao->region_id !== $region))
Log::alert(sprintf('%s:%% Address [%s] changing regions [%d->%d]',self::LOGKEY,$ao->ftn,$ao->region_id,$region));
// If the address doesnt exist, we'll need to add in the region
if (! $ao->exists)
$ao->region_id = $region;
$ao->role = $role;
$ao->hub_id = $hub_id;
if ($ao->exists) {
Log::info(sprintf('%s:- Processing existing address [%s] (%d)',self::LOGKEY,$ao->ftn,$ao->id));
// If the address is linked to a user's system, or our system, we'll not process it any further
$skip = FALSE;
if ($our_addresses->contains($ao->id)) {
Log::info(sprintf('%s:! Ignoring updating an address belonging to me',self::LOGKEY));
$skip = TRUE;
// Address moved regions
if ($ao->region_id && ($ao->region_id !== $region)) {
Log::alert(sprintf('%s:%% Address [%s] changing regions [%d->%d]',self::LOGKEY,$ao->ftn,$ao->region_id,$region));
$ao->region_id = $region;
}
if ($our_systems->contains($ao->id)) {
Log::info(sprintf('%s:! Ignoring a system managed by this site',self::LOGKEY));
$skip = TRUE;
}
if ($our_users->contains($ao->id)) {
Log::info(sprintf('%s:! Ignoring a system managed by a user',self::LOGKEY));
$skip = TRUE;
}
if ($skip) {
$no->addresses()->attach($ao,['role'=>$ao->role]);
continue;
}
// Hub details changed
if ($ao->hub_id && ($ao->hub_id !== $ho?->id)) {
Log::alert(sprintf('%s:%% Address [%s] changing hubs [%d->%s]',self::LOGKEY,$ao->ftn,$ao->hub_id,$ho?->id));
$ao->hub_id = $ho?->id;
}
$sysop = trim(str_replace('_',' ',$fields[4]));
$system = trim(str_replace('_',' ',$fields[2]));
$protect = FALSE;
if ($ao->exists) {
Log::info(sprintf('%s:- Processing existing address [%s] (%d)',self::LOGKEY,$ao->ftn,$ao->id));
// If the address is linked to a user's system, or our system, we'll not process it any further
if (our_address()->contains($ao->id)) {
Log::info(sprintf('%s:! Limiting update to an address belonging to me',self::LOGKEY));
$protect = TRUE;
} elseif ($ao->is_hosted) {
Log::info(sprintf('%s:! Limiting update to a system managed by this site',self::LOGKEY));
$protect = TRUE;
} elseif ($ao->is_owned) {
Log::info(sprintf('%s:! Limiting update to a system managed by a user',self::LOGKEY));
$protect = TRUE;
}
$so = $ao->system;
}
// Flags
$methods = collect();
$address = '';
@ -361,26 +352,41 @@ class NodelistImport implements ShouldQueue
}
}
// Get the System
// If we are a zone/region record, then the system may change
switch ($role) {
// If we are a zone/region/host record, then the system servicing that address may change
switch ($ao->role_id) {
case Address::NODE_ZC:
case Address::NODE_RC:
case Address::NODE_NC:
$so = ($x=System::distinct('systems.*')
// For new address, we'll need to add/link to a system
if ($ao->exists) {
if (($ao->system->address !== $address) || ($ao->system->name !== $system) || ($ao->system->sysop !== $sysop)) {
Log::alert(sprintf('%s:! System has changed for [%s], no longer [%s]',self::LOGKEY,$ao->ftn,$ao->system->name));
$ao->active = FALSE;
$ao->save();
$ao = $ao->replicate();
$ao->active = TRUE;
$ao->system_id = NULL;
}
}
if (! $ao->system_id) {
// When searching for a system, we prioritise in this order:
// - the mailer address is correct
// - the system name is correct
$so = System::select('systems.*')
->join('mailer_system',['mailer_system.system_id'=>'systems.id'])
->where('sysop',$sysop)
->where(function($query) use ($address,$methods) {
return $query->where('systems.address',$address)
->when($methods->pluck('address')->filter()->count(),function ($query) use ($methods) {
return $query->whereIN('mailer_system.address',$methods->pluck('address'));
});
})
->when($methods->pluck('port')->filter()->count(),function ($query) use ($methods) {
return $query->whereIN('mailer_system.port',$methods->pluck('port'));
}))
->when($address,
fn($query)=>$query->where(
fn($query)=>$query
->where('systems.address',$address)
->orWhere('mailer_system.address',$address)
),
fn($query)=>$query->where('systems.name',$system))
->single();
// If no system, we'll need to create one
if (! $so) {
Log::info(sprintf('%s:= New System for ZC/RC/NC [%s] - System [%s] Sysop [%s]',self::LOGKEY,$ao->ftn,$system,$sysop));
$so = new System;
@ -394,43 +400,33 @@ class NodelistImport implements ShouldQueue
$so->save();
}
// If the address exists, but it was discovered, assign it to this new host
if ($ao->system_id && ($ao->system_id !== $so->id) && ($ao->system->name === System::default)) {
Log::info(sprintf('%s:= Re-assigning discovered address to [%s]',self::LOGKEY,$so->id));
} elseif (! $ao->system_id) {
Log::alert(sprintf('%s:%% [%s] address not assigned to any system [%s:%s]',self::LOGKEY,$ao->ftn,$system,$sysop));
} elseif ($ao->system_id !== $so->id) {
Log::alert(sprintf('%s:%% [%s] hosted by new system [%s:%s] (was %s:%s)',self::LOGKEY,$ao->ftn,$system,$sysop,$ao->system->name,$ao->system->sysop));
$ao->active = FALSE;
$ao->save();
$ao = $ao->replicate();
$ao->active = TRUE;
}
$ao->system_id = $so->id;
$ao->save();
$ao->load('system');
}
if ($ao->system_id && ((($ao->system->sysop === $sysop) || ($ao->system->name === $system)) && (($ao->system->address === $address) || ($methods->pluck('address')->search($address) !== FALSE)))) {
$ao->save();
$no->addresses()->attach($ao,['role'=>$ao->role_id]);
continue 2;
}
if (! $protect) {
// Normal Node
if ($ao->system_id && (
(($ao->system->sysop === $sysop) || ($ao->system->name === $system))
&& (($ao->system->address === $address) || $methods->pluck('address')->contains($address))))
{
Log::info(sprintf('%s:= Matched [%s] to existing system [%s] with address [%s]',self::LOGKEY,$ao->ftn,$ao->system->name,$ao->system->address));
$so = $ao->system;
// If the sysop name is different
if ($so->sysop !== $sysop) {
Log::alert(sprintf('%s:! Sysop Name changed for BBS [%s:%s] from [%s] to [%s]',
self::LOGKEY,$so->id,$so->name,$so->sysop,$sysop));
Log::alert(sprintf('%s:! Sysop Name changed for BBS [%s:%s] from [%s] to [%s]',self::LOGKEY,$so->id,$so->name,$so->sysop,$sysop));
$so->sysop = $sysop;
// We have the same name has changed (except for ZC/RC addresses)
} elseif (($so->name !== $system) && (! ((Address::NODE_ZC|Address::NODE_RC|Address::NODE_NC) & $ao->role_id))) {
Log::alert(sprintf('%s:! System Name changed for BBS [%s:%s] to [%s]',
self::LOGKEY,$so->id,$so->name,$system));
} elseif ($so->name !== $system) {
Log::alert(sprintf('%s:! System Name changed for BBS [%s:%s] to [%s]',self::LOGKEY,$so->id,$so->name,$system));
$so->name = $system;
}
@ -438,19 +434,19 @@ class NodelistImport implements ShouldQueue
// We'll search and see if we already have that system
} else {
Log::debug(sprintf('%s:- Looking for existing system [%s] with address [%s]',self::LOGKEY,$system,$address));
// If we dont have $address/port
$so = NULL;
if ($address) {
// When searching for a system, we prioritise in this order:
// - the mailer address is correct
// - the system name is correct
$so = System::select('systems.*')
->distinct()
->join('mailer_system',['mailer_system.system_id'=>'systems.id'])
->where(function($query) use ($address) {
return $query->where('systems.address',$address)
->orWhere('mailer_system.address',$address);
})
->when($address,
fn($query)=>$query->where(
fn($query)=>$query
->where('systems.address',$address)
->orWhere('mailer_system.address',$address)
),
fn($query)=>$query->where('systems.name',$system))
->single();
}
if (! $so) {
Log::debug(sprintf('%s:- Didnt match on system address, looking for System [%s] AND Sysop [%s]',self::LOGKEY,$system,$sysop));
@ -478,12 +474,6 @@ class NodelistImport implements ShouldQueue
$so->phone = $fields[5] != '-Unpublished-' ? $fields[5] : NULL;
$so->location = trim(str_replace('_',' ',$fields[3]));
/*
if (! in_array($fields[5],['-Unpublished-']))
$so->phone = $fields[5];
$so->baud = $fields[6];
*/
// Save the system record
try {
@ -496,20 +486,26 @@ class NodelistImport implements ShouldQueue
throw new \Exception($e->getMessage());
}
// @todo This should be a bit test ($ao->rule & Address::NODE_PVT)?
if ($methods->count() && ($ao->role != Address::NODE_PVT)) {
$methods->transform(function($item) { $item['active'] = Arr::get($item,'active',TRUE); return $item; });
$ao->system_id = $so->id;
}
if ($methods->count() && (! $ao->is_private)) {
$methods->transform(function($item) {
$item['active'] = Arr::get($item,'active',TRUE);
return $item;
});
$so->mailers()->sync($methods);
}
// If our zone didnt exist, we'll create it with this system
if (! $zo->exists) {
$zo->system_id = $so->id;
$zo->system_id = $ao->system_id;
$zo->save();
}
$ao->zone_id = $zo->id;
$ao->validated = TRUE;
$ao->role = $role;
if ($ao->getDirty())
$p++;
@ -517,10 +513,13 @@ class NodelistImport implements ShouldQueue
try {
$so->addresses()->save($ao);
if ($ao->role_id === Address::NODE_HC)
$hub_id = $ao->id;
// If we were the hub
if ($ishub) {
$ho = $ao;
$ishub = FALSE;
}
$no->addresses()->attach($ao,['role'=>$ao->role]);
$no->addresses()->attach($ao,['role'=>($ao->role_id & $role)]);
} catch (\Exception $e) {
Log::error(sprintf('%s:! Error with line [%s] (%s)',self::LOGKEY,$line,$e->getMessage()),['fields'=>$fields]);
@ -536,27 +535,34 @@ class NodelistImport implements ShouldQueue
// Remove addresses not recorded;
$no->load('addresses');
$remove = $zo->addresses->diff($no->addresses)->except($our_systems->toArray())->except($our_users->toArray());
Log::alert(sprintf('%s:%% Deleting [%d] addresses [%s]',self::LOGKEY,$remove->count(),$remove->pluck('ftn2d')->join(',')));
Address::whereIN('id',$remove->pluck('id')->toArray())->update(['active'=>FALSE]);
Address::whereIN('id',$remove->pluck('id')->toArray())->delete();
$crc = crc16(substr($tocrc,0,-3));
$remove = $zo
->addresses->pluck('id')
->diff($no->addresses->pluck('id'))
->diff(our_address($do)->pluck('id'))
->diff(our_nodes($do)->pluck('id'));
$remove = Address::whereIn('id',$remove)->get();
Log::alert(sprintf('%s:%% Deleting [%d] addresses [%s]',self::LOGKEY,$remove->count(),$remove->pluck('ftn4d')->join(',')));
Address::whereIN('id',$remove->pluck('id'))->update(['active'=>FALSE]);
Address::whereIN('id',$remove->pluck('id'))->delete();
Log::info(sprintf('%s:= Updated %d AKA records from %d Systems',self::LOGKEY,$p,$c));
$crc = crc16(substr($crc_check,0,-3));
if ((! $this->testmode) && ($this->ignore_crc || ($crc === $file_crc))) {
Log::info(sprintf('%s:= Committing nodelist',self::LOGKEY));
DB::commit();
if ($this->delete_file and $c)
unlink($file);
} else {
Log::error(sprintf('%s:! Rolling back nodelist, CRC doesnt match [%s](%s) or test mode',self::LOGKEY,$crc,$file_crc));
Log::error(sprintf('%s:! Rolling back nodelist, CRC doesnt match [%s != %s] or TEST mode',self::LOGKEY,$crc,$file_crc));
DB::rollBack();
}
fclose($fh);
if ($this->delete_file and $c)
unlink($file);
Log::info(sprintf('%s:= Updated %d records from %d systems',self::LOGKEY,$p,$c));
}
}

View File

@ -393,7 +393,7 @@ class Address extends Model
*/
public function scopeFTN($query)
{
return $query->select(['zone_id','host_id','node_id','point_id'])
return $query->select(['addresses.zone_id','host_id','node_id','point_id'])
->with('zone.domain');
}
@ -775,6 +775,11 @@ class Address extends Model
return $this->role & self::NODE_HOLD;
}
public function getIsOwnedAttribute(): bool
{
return $this->system->is_owned;
}
public function getIsPrivateAttribute(): bool
{
return (! $this->system->address);
@ -793,7 +798,7 @@ class Address extends Model
$val = ($this->role & self::NODE_ALL);
$role = $this->ftn_role();
if ($this->isRoleOverride()) {
if ($this->isRoleOverride($role)) {
if (! $warn) {
$warn = TRUE;
Log::alert(sprintf('%s:! Address ROLE [%d] is not consistent with what is expected [%d] for [%s]',self::LOGKEY,$val,$role,$this->ftn));
@ -1194,10 +1199,10 @@ class Address extends Model
return $o;
}
public function isRoleOverride(): bool
public function isRoleOverride(int $role=NULL): bool
{
$val = ($this->role & self::NODE_ALL);
$role = $this->ftn_role();
$role = $role ?: $this->ftn_role();
return ($val && ($role !== $val)) || (! $role);
}

View File

@ -170,6 +170,11 @@ class System extends Model
}
}
public function getIsOwnedAttribute(): bool
{
return $this->users->count();
}
public function getPktMsgsAttribute(?int $val): int
{
return $val ?: Setup::findOrFail(config('app.id'))->msgs_pkt;

View File

@ -42,19 +42,19 @@ trait Import
if ($z->open($file,\ZipArchive::RDONLY) === TRUE) {
if ($z->count() !== 1)
throw new \Exception(sprintf('%s:File [%s] has more than 1 file (%d)', self::LOGKEY, $file, $z->count()));
throw new \Exception(sprintf('%s:! File [%s] has more than 1 file (%d)', self::LOGKEY, $file, $z->count()));
$zipfile = $z->statIndex(0, \ZipArchive::FL_UNCHANGED);
Log::debug(sprintf('%s:Looking at [%s] in archive [%s]', self::LOGKEY,$zipfile['name'],$file));
Log::debug(sprintf('%s:- Looking at [%s] in archive [%s]', self::LOGKEY,$zipfile['name'],$file));
$f = $z->getStream($zipfile['name']);
if (! $f)
throw new \Exception(sprintf('%s:Failed getting ZipArchive::stream (%s)',self::LOGKEY,$z->getStatusString()));
throw new \Exception(sprintf('%s:! Failed getting ZipArchive::stream (%s)',self::LOGKEY,$z->getStatusString()));
else
return $z;
} else {
throw new \Exception(sprintf('%s:Failed opening ZipArchive [%s] (%s)',self::LOGKEY,$file,$z->getStatusString()));
throw new \Exception(sprintf('%s:! Failed opening ZipArchive [%s] (%s)',self::LOGKEY,$file,$z->getStatusString()));
}
}