source: client/shared/bin/poweroffconf.py @ 937f1b5

ogClonningEngine
Last change on this file since 937f1b5 was 5b1449d, checked in by Antonio Emmanuel Guerrero Silva <aguerrero@…>, 7 months ago

refs #700 shared files convert to Python3

  • Property mode set to 100644
File size: 3.1 KB
Line 
1#!/usr/bin/env python3
2
3import os
4import sys
5import re
6import time
7from datetime import datetime, timedelta
8
9"""
10@file     poweroffconf
11@brief    Control de parada tras tiempo de inactividad para ahorro de energía.
12@param    int_minutos    Minutos de inactividad (opcional); "no" para deshabilitar.
13@note     La comprobación periódica debe ejecutarse en el "cron" del sistema.
14@note     Fichero de configuración: /etc/poweroff.conf
15@version  1.0.5: incluir opción para deshabilitar ahorro de energía.
16@version  1.1.1: Corregir problema al cambiar de día
17"""
18
19
20OPENGNSYS = os.getenv('OPENGNSYS', '/opt/opengnsys')
21OGETC = os.getenv('OGETC', f'{OPENGNSYS}/etc')
22POWEROFFCONF = '/etc/poweroff.conf'
23
24def ogRaiseError(error_code, message):
25    print(f"Error {error_code}: {message}", file=sys.stderr)
26    sys.exit(1)
27
28if not os.path.isfile(POWEROFFCONF):
29    ogRaiseError('OG_ERR_NOTFOUND', POWEROFFCONF)
30
31config = {}
32with open(POWEROFFCONF) as f:
33    for line in f:
34        name, var = line.partition("=")[::2]
35        config[name.strip()] = str(var).strip()
36
37POWEROFFSLEEP = config.get('POWEROFFSLEEP')
38POWEROFFTIME = config.get('POWEROFFTIME')
39
40if len(sys.argv) == 1:
41    if not POWEROFFSLEEP:
42        ogRaiseError('OG_ERR_FORMAT', "Sin tiempo de espera.")
43elif len(sys.argv) == 2:
44    POWEROFFSLEEP = sys.argv[1]
45    if POWEROFFSLEEP == "no":
46        POWEROFFSLEEP = ""
47    elif not re.match(r'^\d*$', POWEROFFSLEEP):
48        ogRaiseError('OG_ERR_FORMAT', 'Parámetro debe ser núm. minutos o "no" para deshabilitar.')
49   
50    with open(POWEROFFCONF, 'r') as file:
51        data = file.read()
52    data = re.sub(r'POWEROFFSLEEP=.*', f'POWEROFFSLEEP={POWEROFFSLEEP}', data)
53    with open(POWEROFFCONF, 'w') as file:
54        file.write(data)
55   
56    if POWEROFFSLEEP:
57        POWEROFFTIME = int((datetime.now() + timedelta(minutes=int(POWEROFFSLEEP))).timestamp())
58        with open(POWEROFFCONF, 'r') as file:
59            data = file.read()
60        data = re.sub(r'POWEROFFTIME=.*', f'POWEROFFTIME={POWEROFFTIME}', data)
61        with open(POWEROFFCONF, 'w') as file:
62            file.write(data)
63    sys.exit(0)
64else:
65    ogRaiseError('OG_ERR_FORMAT', f"Formato: {sys.argv[0]} [int_minutos | no]")
66
67pgrep_output = os.popen('pgrep -fa 2>&1').read()
68if 'invalid' in pgrep_output:
69    PGREP = 'pgrep -fl'
70else:
71    PGREP = 'pgrep -fa'
72
73pgrep_result = os.popen(f'{PGREP} {OPENGNSYS}').read()
74if re.search(f'{OGETC}|{sys.argv[0]}', pgrep_result) is None:
75    with open(POWEROFFCONF, 'r') as file:
76        data = file.read()
77    data = re.sub(r'POWEROFFTIME=.*', 'POWEROFFTIME=', data)
78    with open(POWEROFFCONF, 'w') as file:
79        file.write(data)
80else:
81    NOW = int(time.time())
82    if not POWEROFFTIME:
83        POWEROFFTIME = int((datetime.now() + timedelta(minutes=int(POWEROFFSLEEP))).timestamp())
84        with open(POWEROFFCONF, 'r') as file:
85            data = file.read()
86        data = re.sub(r'POWEROFFTIME=.*', f'POWEROFFTIME={POWEROFFTIME}', data)
87        with open(POWEROFFCONF, 'w') as file:
88            file.write(data)
89    else:
90        if NOW >= int(POWEROFFTIME):
91            os.system(f'{OPENGNSYS}/scripts/poweroff')
Note: See TracBrowser for help on using the repository browser.