|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +""" serverlog. |
| 4 | +""" |
| 5 | + |
| 6 | +from __future__ import absolute_import, print_function, unicode_literals |
| 7 | + |
| 8 | +from datetime import datetime, timedelta |
| 9 | +import signal |
| 10 | +import argparse |
| 11 | +import json |
| 12 | + |
| 13 | + |
| 14 | +class Job: |
| 15 | + time_offset = timedelta(seconds=1) |
| 16 | + |
| 17 | + def __init__(self, cycle, job_callback): |
| 18 | + self.cycle= cycle |
| 19 | + self.job_callback = job_callback |
| 20 | + self.next_time = datetime.utcnow() |
| 21 | + |
| 22 | + def check_and_do_job(self): |
| 23 | + now = datetime.utcnow() + self.time_offset |
| 24 | + if now > self.next_time: |
| 25 | + self.job_callback() |
| 26 | + # subp.call(['zbackup.sh',self.dataset,self.rot]) |
| 27 | + self.next_time = ((now - self.next_time)//self.cycle + 1) * self.cycle |
| 28 | + return self.next_time |
| 29 | + |
| 30 | + |
| 31 | +job_queue = [] |
| 32 | +def do_jobs(): |
| 33 | + sleep_until = min(x.check_and_do_job() for x in job_queue) |
| 34 | + sleep_time_int = int((sleep_until-datetime.utcnow()).total_seconds()) |
| 35 | + signal.alarm(max(sleep_time_int,1)) |
| 36 | + |
| 37 | +config_file_path = '' |
| 38 | +def load_config_file(): |
| 39 | + with open(config_file_path) as f: |
| 40 | + config = json.load(f) |
| 41 | + |
| 42 | + job_queue.clear() |
| 43 | + for job in config.get('jobs', []): |
| 44 | + pass |
| 45 | + |
| 46 | +def set_signal_handler(): |
| 47 | + signal.signal(signal.SIGALRM, do_jobs) |
| 48 | + signal.signal(signal.SIGUSR1, load_config_file) |
| 49 | + |
| 50 | +def start_service(): |
| 51 | + load_config_file() |
| 52 | + while True: |
| 53 | + signal.pause() |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == '__main__': |
| 57 | + parser = argparse.ArgumentParser( |
| 58 | + description='Server status or service status logging service.') |
| 59 | + parser.add_argument('-d','--deamon', |
| 60 | + dest='is_deamon', |
| 61 | + action='store_const', |
| 62 | + const=True, |
| 63 | + default=False, |
| 64 | + help='Run the service in deamon mond.') |
| 65 | + parser.add_argument('-c','--config', |
| 66 | + dest='config', |
| 67 | + default='/usr/local/etc/serverlog.conf', |
| 68 | + help='The path of the configuration file.') |
| 69 | + parser.add_argument('-p','--pid', |
| 70 | + dest='pidfile', |
| 71 | + default='/var/run/serverlog.pid', |
| 72 | + help='The path of the pid file.') |
| 73 | + |
| 74 | + args = parser.parse_args() |
| 75 | + if args.is_deamon: |
| 76 | + pid = os.fork() |
| 77 | + if pid != 0: |
| 78 | + with open(args.pidfile, 'w') as pidfile: |
| 79 | + pidfile.write('%d' % pid) |
| 80 | + exit(0) |
| 81 | + config_file_path = args.config |
| 82 | + start_service() |
0 commit comments