refs #839 Migration of interfaceAdm code

pull/2/head
Antonio Guerrero 2024-10-17 01:35:20 +00:00
parent c113468f71
commit 0a5f74e1a3
14 changed files with 596 additions and 0 deletions

View File

@ -0,0 +1,9 @@
import os
import sys
def poweroff():
os.system('poweroff')
if __name__ == "__main__":
poweroff()
sys.exit(0)

View File

@ -0,0 +1,53 @@
import os
import sys
import subprocess
#!/usr/bin/env python3
def main():
if len(sys.argv) != 2:
print("Usage: CambiarAcceso.py <mode>")
sys.exit(1)
mode = sys.argv[1]
repo_ip = og_get_repo_ip()
if not repo_ip:
og_raise_error("OG_ERR_NOTFOUND", "repo no montado")
if og_is_repo_locked():
og_raise_error("OG_ERR_LOCKED", f"repo {repo_ip}")
proto = os.getenv("ogprotocol", "smb")
if proto not in ["nfs", "smb"]:
og_raise_error("OG_ERR_FORMAT", f"protocolo desconocido {proto}")
if mode == "admin":
mount_mode = "rw"
elif mode == "user":
mount_mode = "ro"
else:
og_raise_error("OG_ERR_FORMAT", f"modo desconocido {mode}")
ogimg = os.getenv("OGIMG", "/mnt/ogimg")
ogunit = os.getenv("ogunit", "")
if ogunit:
ogunit = f"/{ogunit}"
subprocess.run(["umount", ogimg], check=True)
og_echo("info", f"Montar repositorio {repo_ip} por {proto} en modo {mode}")
if proto == "nfs":
subprocess.run(["mount", "-t", "nfs", f"{repo_ip}:{ogimg}{ogunit}", ogimg, "-o", mount_mode], check=True)
elif proto == "smb":
with open("/scripts/ogfunctions", "r") as f:
for line in f:
if "OPTIONS=" in line:
pass_option = line.split("pass=")[1].split()[0]
break
else:
pass_option = "og"
subprocess.run(["mount.cifs", f"//{repo_ip}/ogimages{ogunit}", ogimg, "-o", f"{mount_mode},serverino,acl,username=opengnsys,password={pass_option}"], check=True)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,146 @@
import os
import sys
import subprocess
# Load engine configurator from engine.cfg file.
# Carga el configurador del engine desde el fichero engine.cfg
og_engine_configurate = os.getenv('OGENGINECONFIGURATE')
if not og_engine_configurate:
with open('/opt/opengnsys/client/etc/engine.cfg') as f:
for line in f:
if '=' in line:
key, value = line.strip().split('=', 1)
os.environ[key] = value
print(f"{key}={value}")
# Clear temporary file used as log track by httpdlog
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
og_log_session = os.getenv('OGLOGSESSION')
og_log_command = os.getenv('OGLOGCOMMAND')
if og_log_session:
# Check if the file exists, if not create it
if not os.path.exists(og_log_session):
os.makedirs(os.path.dirname(og_log_session), exist_ok=True)
with open(og_log_session, 'w') as f:
f.write(" ")
else:
with open(og_log_session, 'w') as f:
f.write(" ")
print("og_log_command", og_log_command)
if og_log_command:
with open(og_log_command, 'w') as f:
f.write(" ")
with open(f"{og_log_command}.tmp", 'w') as f:
f.write(" ")
print("og_log_session", og_log_session)
# Registro de inicio de ejecución
def og_echo(log_type, message):
# Implement the logging function here
pass
print("os.getenv('MSG_INTERFACE_START')", os.getenv('MSG_INTERFACE_START'))
msg_interface_start = os.getenv('MSG_INTERFACE_START')
if msg_interface_start:
og_echo('log', f"session {msg_interface_start} {__name__} {' '.join(os.sys.argv[1:])}")
# Solo ejecutable por OpenGnsys Client.
path = os.getenv('PATH')
if path:
os.environ['PATH'] = f"{path}:{os.path.dirname(__name__)}"
prog = os.path.basename(__name__)
print("prog", prog)
# Captura de parámetros (se ignora el 1er parámetro y se eliminan espacios y tabuladores).
param = ''.join(sys.argv[2:]).replace(' ', '').replace('\t', '')
print("param", param)
# Activate browser to see progress
browser_command = ["/opt/opengnsys/bin/browser", "-qws", "http://localhost/cgi-bin/httpd-log.sh"]
coproc = subprocess.Popen(browser_command)
# Read the two blocks of parameters, separated by '!'
tbprm = param.split('!')
pparam = tbprm[0] # General disk parameters
sparam = tbprm[1] # Partitioning and formatting parameters
# Take disk and cache values, separated by '*'
tbprm = pparam.split('*')
for item in tbprm:
if '=' in item:
key, value = item.split('=', 1)
os.environ[key] = value
# Error if disk parameter (dis) is not defined
if 'dis' not in os.environ:
sys.exit(int(os.getenv('OG_ERR_FORMAT', 1)))
# Take partition distribution values, separated by '%'
cfg = [] # Configuration values
tbp = [] # Partition table
tbf = [] # Formatting table
tbprm = sparam.split('%')
maxp = 0
for item in tbprm:
cfg = item.split('*')
for c in cfg:
if '=' in c:
key, value = c.split('=', 1)
os.environ[key] = value
if os.getenv('cpt') != "CACHE":
tbp.append(f"{os.getenv('cpt')}:{os.getenv('tam')}")
if os.getenv('ope') == '1':
if os.getenv('cpt') not in ["EMPTY", "EXTENDED", "LINUX-LVM", "LVM", "ZPOOL"]:
tbf.append(os.getenv('sfi'))
maxp = max(maxp, int(os.getenv('par', 0)))
# Process
# Current cache size
cache_size = subprocess.check_output(["ogGetCacheSize"]).strip()
# Unmount all partitions and cache
subprocess.run(["ogUnmountAll", os.getenv('dis')], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
subprocess.run(["ogUnmountCache"])
# Delete partition table if not MSDOS
if subprocess.check_output(["ogGetPartitionTableType", "1"]).strip() != b'MSDOS':
subprocess.run(["ogDeletePartitionTable", os.getenv('dis')])
subprocess.run(["ogExecAndLog", "COMMAND", "ogUpdatePartitionTable", os.getenv('dis')])
subprocess.run(["ogCreatePartitionTable", os.getenv('dis'), "MSDOS"])
# Initialize cache
if "CACHE" in sparam:
subprocess.run(["ogExecAndLog", "COMMAND", "initCache", os.getenv('tch')])
# Define partitioning
subprocess.run(["ogExecAndLog", "COMMAND", "ogCreatePartitions", os.getenv('dis')] + tbp)
if subprocess.run(["ogExecAndLog", "COMMAND", "ogUpdatePartitionTable", os.getenv('dis')]).returncode != 0:
coproc.kill()
sys.exit(int(subprocess.check_output(["ogRaiseError", "session", "log", os.getenv('OG_ERR_GENERIC', '1'), f"ogCreatePartitions {os.getenv('dis')} {' '.join(tbp)}"])))
# Format partitions
for par in range(1, maxp + 1):
if tbf[par] == "CACHE":
if cache_size == os.getenv('tch'):
subprocess.run(["ogExecAndLog", "COMMAND", "ogFormatCache"])
elif tbf[par]:
if subprocess.run(["ogExecAndLog", "COMMAND", "ogFormatFs", os.getenv('dis'), str(par), tbf[par]]).returncode != 0:
coproc.kill()
sys.exit(int(subprocess.check_output(["ogRaiseError", "session", "log", os.getenv('OG_ERR_GENERIC', '1'), f"ogFormatFs {os.getenv('dis')} {par} {tbf[par]}"])))
retval = 0
subprocess.run(["ogEcho", "log", "session", f"{os.getenv('MSG_INTERFACE_END')} {retval}"])
# Return
coproc.kill()
sys.exit(0)

View File

@ -0,0 +1,28 @@
import os
import sys
import subprocess
def main(script_path, output_path):
try:
# Make the script executable
os.chmod(script_path, 0o755)
# Execute the script and redirect output
with open(output_path, 'w') as output_file:
result = subprocess.run([script_path], stdout=output_file, stderr=subprocess.STDOUT)
# Exit with the script's return code
sys.exit(result.returncode)
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python ConsolaRemota.py <script_path> <output_path>")
sys.exit(1)
script_path = sys.argv[1]
output_path = sys.argv[2]
main(script_path, output_path)

View File

@ -0,0 +1,101 @@
import os
import subprocess
import sys
import time
# Error codes
OG_ERR_NOTEXEC = 1
OG_ERR_LOCKED = 4
OG_ERR_FORMAT = 1
OG_ERR_PARTITION = 3
OG_ERR_IMAGE = 5
OG_ERR_NOTWRITE = 14
OG_ERR_NOTCACHE = 15
OG_ERR_CACHESIZE = 16
OG_ERR_REDUCEFS = 17
OG_ERR_EXTENDFS = 18
def load_engine_config():
engine_config_path = "/opt/opengnsys/etc/engine.cfg"
if os.path.exists(engine_config_path):
with open(engine_config_path) as f:
exec(f.read(), globals())
def clear_temp_logs():
open(os.getenv('OGLOGSESSION'), 'w').close()
open(os.getenv('OGLOGCOMMAND'), 'w').close()
open(f"{os.getenv('OGLOGCOMMAND')}.tmp", 'w').close()
def log_session_start(script_name, args):
ogEcho("log session", f"{os.getenv('MSG_INTERFACE_START')} {script_name} {' '.join(args)}")
def log_session_end(retval):
ogEcho("log session", f"{os.getenv('MSG_INTERFACE_END')} {retval}")
def ogEcho(*args):
print(" ".join(args))
def ogRaiseError(error_code, message):
print(f"Error {error_code}: {message}", file=sys.stderr)
return error_code
def ogGetIpAddress():
return subprocess.check_output(["hostname", "-I"]).decode().strip()
def ogCheckIpAddress(ip):
try:
subprocess.check_call(["ping", "-c", "1", ip])
return 0
except subprocess.CalledProcessError:
return 1
def ogChangeRepo(repo, unit):
# Placeholder for actual implementation
return True
def CambiarAcceso(mode):
# Placeholder for actual implementation
return 0
def create_image(disk_num, partition_num, repo, image_name):
if subprocess.call(["which", "createImageCustom"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0:
return subprocess.call(["createImageCustom", disk_num, partition_num, repo, f"/{image_name}"])
else:
return subprocess.call(["createImage", disk_num, partition_num, repo, f"/{image_name}"])
def main():
if len(sys.argv) != 5:
sys.exit(ogRaiseError(OG_ERR_FORMAT, "Incorrect number of arguments"))
disk_num, partition_num, image_name, repo = sys.argv[1:5]
start_time = time.time()
load_engine_config()
clear_temp_logs()
log_session_start(sys.argv[0], sys.argv[1:])
repo = repo if repo else "REPO"
if repo == ogGetIpAddress():
repo = "CACHE"
if ogCheckIpAddress(repo) == 0 or repo == "REPO":
ogunit = os.getenv('ogunit', "")
if not ogChangeRepo(repo, ogunit):
sys.exit(ogRaiseError(OG_ERR_NOTFOUND, f"{repo}"))
if repo == "REPO" and os.getenv('boot') != "admin":
retval = CambiarAcceso("admin")
if retval > 0:
sys.exit(retval)
retval = create_image(disk_num, partition_num, repo, image_name)
if repo == "REPO" and os.getenv('boot') != "admin":
CambiarAcceso("user")
log_session_end(retval)
sys.exit(retval)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,56 @@
import os
import time
import subprocess
import sys
def main(script_path):
start_time = time.time()
# Load engine configurator from engine.cfg file
og_engine_configurate = os.getenv('OGENGINECONFIGURATE')
if not og_engine_configurate:
with open('/opt/opengnsys/etc/engine.cfg') as f:
exec(f.read())
# Clear temporary file used as log track by httpdlog
og_log_session = os.getenv('OGLOGSESSION')
og_log_command = os.getenv('OGLOGCOMMAND')
if og_log_session:
open(og_log_session, 'w').close()
if og_log_command:
open(og_log_command, 'w').close()
# Registro de inicio de ejecución
msg_interface_start = os.getenv('MSG_INTERFACE_START')
og_echo('log session', f"{msg_interface_start} {sys.argv[0]} {' '.join(sys.argv[1:])}")
og_log_file = os.getenv('OGLOGFILE')
if og_log_file:
with open(og_log_file, 'a') as log_file:
log_file.write("\n Instrucciones a ejecutar: *****************************\n")
with open(script_path) as script_file:
log_file.write(script_file.read())
log_file.write("\n Salida de las instrucciones: *****************************\n")
# Execute the script
os.chmod(script_path, 0o755)
retval = subprocess.call([script_path])
elapsed_time = time.time() - start_time
if retval == 0:
og_echo('log session', f"[100] Duracion de la operacion {int(elapsed_time // 60)}m {int(elapsed_time % 60)}s")
else:
og_raise_error('log session', retval)
og_echo('log session error', "Operacion no realizada")
# Registro de fin de ejecución
msg_interface_end = os.getenv('MSG_INTERFACE_END')
og_echo('log session', f"{msg_interface_end} {retval}")
sys.exit(retval)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python EjecutarScript.py <script_path>")
sys.exit(1)
main(sys.argv[1])

View File

@ -0,0 +1,17 @@
import sys
import subprocess
def main():
args = sys.argv[1:]
if len(args) == 1:
disk = 1
part = args[0]
else:
disk = args[0]
part = args[1]
boot_os(disk, part)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,20 @@
import subprocess
import sys
def list_hardware_info():
# Replace this with the actual command to list hardware info
result = subprocess.run(['listHardwareInfo'], capture_output=True, text=True)
return result.stdout
def save_hardware_inventory(output_file):
hardware_info = list_hardware_info()
lines = hardware_info.splitlines()
if len(lines) > 1:
with open(output_file, 'w') as f:
f.write('\n'.join(lines[1:]))
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python InventarioHardware.py <output_file>")
else:
save_hardware_inventory(sys.argv[1])

View File

@ -0,0 +1,49 @@
import os
import time
import shutil
import subprocess
import sys
def main(arg1, arg2, dest_file):
start_time = time.time()
# Load the engine configurator from the engine.cfg file
og_engine_configurate = os.getenv('OGENGINECONFIGURATE')
if not og_engine_configurate:
with open('/opt/opengnsys/etc/engine.cfg') as f:
exec(f.read())
# Clear the temporary files used as log tracking for httpdlog
og_log_session = os.getenv('OGLOGSESSION')
og_log_command = os.getenv('OGLOGCOMMAND')
if og_log_session and og_log_command:
with open(og_log_session, 'w') as f:
f.write(" ")
with open(og_log_command, 'w') as f:
f.write(" ")
with open(f"{og_log_command}.tmp", 'w') as f:
f.write(" ")
# Log the start of execution
msg_interface_start = os.getenv('MSG_INTERFACE_START')
if msg_interface_start:
subprocess.run(['ogEcho', 'log', 'session', f"{msg_interface_start} {__file__} {arg1} {arg2}"])
# Get the software info file and copy it to the destination
# Call the actual listSoftwareInfo function
file = listSoftwareInfo(arg1, arg2)
shutil.copy(file, dest_file)
# Log the execution time
elapsed_time = time.time() - start_time
msg_scripts_time_partial = os.getenv('MSG_SCRIPTS_TIME_PARTIAL')
if msg_scripts_time_partial:
subprocess.run(['ogEcho', 'log', 'session', f" [ ] {msg_scripts_time_partial} : {int(elapsed_time // 60)}m {int(elapsed_time % 60)}s"])
if __name__ == "__main__":
if len(sys.argv) != 4:
print("Usage: python InventarioSoftware.py <arg1> <arg2> <dest_file>")
sys.exit(1)
main(sys.argv[1], sys.argv[2], sys.argv[3])

View File

@ -0,0 +1,7 @@
import os
def reboot_system():
os.system('reboot')
if __name__ == "__main__":
reboot_system()

View File

@ -0,0 +1,18 @@
import sys
import subprocess
if __name__ == "__main__":
if len(sys.argv) < 7:
print("Usage: python RestaurarImagen.py <disk> <partition> <image_name> <ip> <protocol> <protocol_options> [additional_args...]")
sys.exit(1)
disk = sys.argv[1]
partition = sys.argv[2]
image_name = sys.argv[3]
ip = sys.argv[4]
protocol = sys.argv[5]
protocol_options = sys.argv[6]
additional_args = sys.argv[7:]
exit_code = deploy_image(ip, image_name, disk, partition, protocol, protocol_options, *additional_args)
sys.exit(exit_code)

View File

@ -0,0 +1,79 @@
import os
import subprocess
def run_command(command):
result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return result.stdout.decode().strip()
def main():
# No registrar los errores.
os.environ["DEBUG"] = "no"
ser = run_command("ogGetSerialNumber")
cfg = ""
disks = int(run_command("ogDiskToDev | wc -w"))
for dsk in range(1, disks + 1):
particiones = run_command(f"ogGetPartitionsNumber {dsk}")
particiones = int(particiones) if particiones else 0
ptt = run_command(f"ogGetPartitionTableType {dsk}")
ptt_map = {
"MSDOS": 1,
"GPT": 2,
"LVM": 3,
"ZPOOL": 4
}
ptt = ptt_map.get(ptt, 0)
cfg += f"{dsk}:0:{ptt}:::{run_command(f'ogGetDiskSize {dsk}')}:0;"
for par in range(1, particiones + 1):
cod = run_command(f"ogGetPartitionId {dsk} {par} 2>/dev/null")
fsi = run_command(f"getFsType {dsk} {par} 2>/dev/null") or "EMPTY"
tam = run_command(f"ogGetPartitionSize {dsk} {par} 2>/dev/null") or "0"
soi = ""
uso = 0
if fsi not in ["", "EMPTY", "LINUX-SWAP", "LINUX-LVM", "ZVOL"]:
if run_command(f"ogMount {dsk} {par} 2>/dev/null"):
soi = run_command(f"getOsVersion {dsk} {par} 2>/dev/null").split(":")[1]
if not soi:
soi = run_command(f"getOsVersion {dsk} {par} 2>/dev/null").split(":")[1]
if not soi and fsi not in ["EMPTY", "CACHE"]:
soi = "DATA"
uso = int(run_command(f"df $(ogGetMountPoint {dsk} {par}) | awk '{{getline; printf \"%d\",$5}}'") or 0)
else:
soi = ""
uso = 0
cfg += f"{dsk}:{par}:{cod}:{fsi}:{soi}:{tam}:{uso};"
if not cfg:
cfg = "1:0:0:::0;"
cfgfile = "/tmp/getconfig"
with open(cfgfile, "w") as f:
f.write(f"{ser + ';' if ser else ''}{cfg}")
run_command("generateMenuDefault &>/dev/null")
with open(cfgfile, "r") as f:
data = f.read()
lines = data.split(";")
for line in lines:
if line:
parts = line.split(":")
if len(parts) == 1:
print(f"ser={parts[0]}")
else:
print(f"disk={parts[0]}\tpar={parts[1]}\tcpt={parts[2]}\tfsi={parts[3]}\tsoi={parts[4]}\ttam={parts[5]}\tuso={parts[6]}")
run_command("rm -f /mnt/*/ogboot.* /mnt/*/*/ogboot.*")
# Volver a registrar los errores.
os.environ.pop("DEBUG", None)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,5 @@
import socket
#!/usr/bin/env python3
if __name__ == "__main__":
print("IP Address:", get_ip_address())

View File

@ -0,0 +1,8 @@
import sys
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python procesaCache.py <arg>")
sys.exit(1)
init_cache(sys.argv[1])