Integrate 0.9.8 NDS read-only lab, repair upstream hook and simplify setup guidance
This commit is contained in:
125
nds/tools/snapshot.py
Normal file
125
nds/tools/snapshot.py
Normal file
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish a credential-free, single-server NDS lab directory from wizard metadata."""
|
||||
import argparse, contextlib, json, os, re, sqlite3, tempfile
|
||||
from pathlib import Path
|
||||
import directory as d
|
||||
|
||||
def label(s, n):
|
||||
return isinstance(s,str) and re.fullmatch(r'[A-Z0-9_-]{1,'+str(n)+r'}',s) is not None
|
||||
|
||||
def parse_resources(path):
|
||||
"""Only sections 1/2, matching the setup parser's ASCII token rules.
|
||||
Never copy passwords, filesystem paths, or arbitrary configuration lines.
|
||||
"""
|
||||
with Path(path).open('rb') as f: raw=f.read(1048577)
|
||||
if len(raw)>1048576 or b'\0' in raw: raise ValueError('Serverkonfiguration ungültig oder zu groß')
|
||||
servers=[]; volumes=[]
|
||||
for line in raw.split(b'\n'):
|
||||
m=re.match(rb'^[ \t]*(1|2)[ \t]+(.*)$',line.rstrip(b'\r'))
|
||||
if not m: continue
|
||||
fields=m[2].split(b'#',1)[0].split()
|
||||
if m[1]==b'2':
|
||||
if len(fields)!=1: raise ValueError('Abschnitt 2: genau ein Servername erforderlich')
|
||||
servers.append(fields[0].decode('ascii').upper())
|
||||
else:
|
||||
if len(fields)<2 or len(fields)>12: raise ValueError('Abschnitt 1: Volume und Pfad erforderlich')
|
||||
volumes.append(fields[0].decode('ascii').upper())
|
||||
if len(servers)!=1: raise ValueError('Genau ein ASCII-Servername erforderlich')
|
||||
validate_resources(servers[0],volumes)
|
||||
return servers[0],volumes
|
||||
|
||||
def validate_resources(server,volumes):
|
||||
if not label(server,47): raise ValueError('Ungültiger ASCII-Servername')
|
||||
if not isinstance(volumes,list) or not 1<=len(volumes)<=64 or not all(label(v,8) for v in volumes) or volumes.count('SYS')!=1 or len(set(volumes))!=len(volumes):
|
||||
raise ValueError('Volumes: genau ein SYS, eindeutige ASCII-Namen bis 8 Zeichen, maximal 64')
|
||||
|
||||
def plan(data, placements=False, resources=None):
|
||||
t,o,u=data['tree'],data['organization'],data['units']
|
||||
if not label(t,32) or not label(o,47) or not isinstance(u,list) or len(u)>128:
|
||||
raise ValueError('Baum/Organisation/OU-Liste ungültig')
|
||||
if not all(isinstance(x,str) and len(x)<=191 and len(x.split('/'))<=8 and all(label(y,47) for y in x.split('/')) for x in u):
|
||||
raise ValueError('OU-Pfad ungültig')
|
||||
if len(set(u))!=len(u) or any('/' in x and x.rsplit('/',1)[0] not in u for x in u):
|
||||
raise ValueError('OU doppelt oder Eltern-OU fehlt')
|
||||
base='O='+o; paths={'':base}; rows=[('[Root]','Organization',o,base)]
|
||||
for unit in sorted(u,key=lambda x:(x.count('/'),x)):
|
||||
parent,_,name=unit.rpartition('/'); dn='OU='+name+'.'+paths[parent]
|
||||
if len(dn)>255:raise ValueError('OU-DN zu lang')
|
||||
paths[unit]=dn;rows.append((paths[parent],'Organizational Unit',name,dn))
|
||||
if placements:
|
||||
p=data.get('placements',[])
|
||||
if not isinstance(p,list) or len(p)>1024:raise ValueError('Zuordnungsliste ungültig')
|
||||
for item in p:
|
||||
raw_name=item['name']; unit=item['unit']; typ=item['type']
|
||||
if not isinstance(raw_name,str) or not re.fullmatch(r'[A-Za-z0-9_-]{1,47}',raw_name):raise ValueError('Objektname muss ASCII sein')
|
||||
name=raw_name.upper()
|
||||
if not label(name,47) or unit not in paths or type(typ) is not int or typ not in (1,2):
|
||||
raise ValueError('Nur ASCII-Zuordnungen A-Z, 0-9, _ und - im NDS-Labor')
|
||||
dn='CN='+name+'.'+paths[unit]
|
||||
if len(dn)>255:raise ValueError('Objekt-DN zu lang')
|
||||
rows.append((paths[unit],'User' if typ==1 else 'Group',name,dn))
|
||||
if resources is not None:
|
||||
server,volumes=resources
|
||||
validate_resources(server,volumes)
|
||||
parent=paths.get('SERVERS',base)
|
||||
sd='CN='+server+'.'+parent
|
||||
rows.append((parent,'NCP Server',server,sd))
|
||||
for volume in sorted(volumes):
|
||||
name=server+'_'+volume
|
||||
dn='CN='+name+'.'+parent
|
||||
if len(name)>63 or len(dn)>255:raise ValueError('Volume-Objektname oder DN zu lang')
|
||||
rows.append((parent,'Volume',name,dn))
|
||||
if len({r[3] for r in rows})!=len(rows):raise ValueError('NDS-Namenskollision')
|
||||
return {'tree':t,'organization':o,'units':u},rows
|
||||
|
||||
def publish(data, path, placements=False, resources=None):
|
||||
config,rows=plan(data,placements,resources)
|
||||
path=Path(path);fd,tmp=tempfile.mkstemp(prefix='.nds-',dir=path.parent);os.close(fd);os.unlink(tmp)
|
||||
try:
|
||||
if path.exists():
|
||||
with contextlib.closing(d.connect(path)) as old, contextlib.closing(sqlite3.connect(tmp)) as new:
|
||||
old.backup(new)
|
||||
else:d.initialize(tmp)
|
||||
with contextlib.closing(d.connect(tmp)) as db:
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
db.execute('CREATE TABLE IF NOT EXISTS mars_nds_snapshot(id INTEGER PRIMARY KEY CHECK(id=1),tree TEXT NOT NULL,organization TEXT NOT NULL)')
|
||||
db.execute('CREATE TABLE IF NOT EXISTS mars_nds_volume(id INTEGER PRIMARY KEY REFERENCES nds_entries(id) ON DELETE CASCADE, server_id INTEGER NOT NULL REFERENCES nds_entries(id) ON DELETE CASCADE, resource TEXT NOT NULL)')
|
||||
db.execute('DELETE FROM mars_nds_volume')
|
||||
prior=db.execute('SELECT tree FROM mars_nds_snapshot WHERE id=1').fetchone()
|
||||
if prior and prior[0]!=config['tree']:raise ValueError('Baumname geändert: neue Datenbank erforderlich; alte vorher sichern')
|
||||
wanted={r[3]:r[1] for r in rows};wanted['[Root]']='Root'
|
||||
for i,dn,cls in db.execute('SELECT id,dn,cls FROM nds_entries ORDER BY length(dn) DESC').fetchall():
|
||||
if dn not in wanted or wanted[dn]!=cls:db.execute('DELETE FROM nds_entries WHERE id=?',(i,))
|
||||
for parent,cls,name,dn in rows:
|
||||
if db.execute('SELECT id FROM nds_entries WHERE dn=?',(dn,)).fetchone():continue
|
||||
pid,pudn,pcls=db.execute('SELECT id,udn,cls FROM nds_entries WHERE dn=?',(parent,)).fetchone()
|
||||
udn=name if pcls=='Root' else name+'.'+pudn
|
||||
db.execute('INSERT INTO nds_entries(parent,dn,udn,name,cls) VALUES(?,?,?,?,?)',(pid,dn,udn,name,cls))
|
||||
if resources is not None:
|
||||
server,volumes=resources
|
||||
server_dn=next(r[3] for r in rows if r[1]=='NCP Server')
|
||||
sid=db.execute('SELECT id FROM nds_entries WHERE dn=?',(server_dn,)).fetchone()[0]
|
||||
for volume in volumes:
|
||||
dn=next(r[3] for r in rows if r[1]=='Volume' and r[2]==server+'_'+volume)
|
||||
vid=db.execute('SELECT id FROM nds_entries WHERE dn=?',(dn,)).fetchone()[0]
|
||||
db.execute('INSERT INTO mars_nds_volume VALUES(?,?,?)',(vid,sid,volume))
|
||||
db.execute('INSERT OR REPLACE INTO mars_nds_snapshot VALUES(1,?,?)',(config['tree'],config['organization']))
|
||||
db.commit()
|
||||
if db.execute('PRAGMA integrity_check').fetchone()!=('ok',) or db.execute('PRAGMA foreign_key_check').fetchone() is not None:raise ValueError('SQLite-Integritätsfehler')
|
||||
os.chmod(tmp,0o644) # public metadata only; nwconn may drop privileges
|
||||
os.replace(tmp,path)
|
||||
return config
|
||||
finally:
|
||||
if os.path.exists(tmp):os.unlink(tmp)
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser(description=__doc__);p.add_argument('source',type=Path);p.add_argument('database',type=Path);p.add_argument('--public-placements',action='store_true');p.add_argument('--check',action='store_true');p.add_argument('--discovery',action='store_true',help='validate tree name for SAP/SLP lab discovery');p.add_argument('--server-config',type=Path,help='optional: import only server and volume names from nwserv.conf');a=p.parse_args()
|
||||
try:
|
||||
with a.source.open('rb') as f:raw=f.read(524289)
|
||||
if len(raw)>524288:raise ValueError('Verzeichnisdatei zu groß')
|
||||
data=json.loads(raw);resources=parse_resources(a.server_config) if a.server_config else None;config,rows=plan(data,a.public_placements,resources)
|
||||
if a.discovery and config['tree'].endswith('_'):raise ValueError('Discovery: Baumname darf nicht auf Unterstrich enden (SAP-Padding)')
|
||||
if not a.check:publish(data,a.database,a.public_placements,resources)
|
||||
print(json.dumps(config,separators=(',',':')))
|
||||
except (OSError,ValueError,TypeError,KeyError,AttributeError,sqlite3.Error) as e:p.exit(1,'NDS: '+str(e)+'\n')
|
||||
if __name__=='__main__':main()
|
||||
Reference in New Issue
Block a user