Commit 28b5efcc authored by heemayl's avatar heemayl

Updated installer and hatc help description

parent f5bf7f96
......@@ -8,4 +8,4 @@ logs/*
*.lock*
*.pkl
hatd.pid
test_run.py
......@@ -42,15 +42,36 @@ def parse_arguments():
'''Parse arguments (for client) and
return appropriate response back.
'''
# Manual formatter class to make `nargs='+'` show one arg
class ManualFormatter(argparse.RawTextHelpFormatter):
def _format_args(self, action, default_metavar):
get_metavar = self._metavar_formatter(action, default_metavar)
if action.nargs is None:
result = '%s' % get_metavar(1)
elif action.nargs == argparse.OPTIONAL:
result = '[%s]' % get_metavar(1)
elif action.nargs == argparse.ZERO_OR_MORE:
result = '[%s [%s ...]]' % get_metavar(2)
# Here...
elif action.nargs == argparse.ONE_OR_MORE:
result = '%s' % get_metavar(1)
elif action.nargs == argparse.REMAINDER:
result = '...'
elif action.nargs == argparse.PARSER:
result = '%s ...' % get_metavar(1)
else:
formats = ['%s' for _ in range(action.nargs)]
result = ' '.join(formats) % get_metavar(action.nargs)
return result
parser = argparse.ArgumentParser(prog='hatc', description='hat client',
formatter_class=argparse.
RawTextHelpFormatter)
formatter_class=ManualFormatter)
parser.add_argument('-l', '--list', dest='joblist',
required=False, action='store_true',
help='Show the list of queued jobs for current user\n')
parser.add_argument('-c', '--count', dest='jobcount',
required=False, action='store_true',
help='Show the number of queued jobs for current user\n')
help='Show the number of queued jobs for current user\n\n')
parser.add_argument('-a', '--add', dest='add_job',
metavar='<command> <datetime_spec> [<shell>]', nargs='+',
required=False, help="""Add a new job. If shell is specified, the job will be run in the given shell, otherwise no shell will be used. Example:
......@@ -67,7 +88,8 @@ def parse_arguments():
)
parser.add_argument('-m', '--modify', dest='modify_job',
metavar='<job_id> <command> <datetime_spec> [<shell>]', nargs='+',
required=False, help="""Modify an enqueued job. The first argument must be the job ID (from `hatc -l`). `_` can be used as a placeholder for using an already saved value for an argument (except <job_id>). If <shell> is used, <command> must be specified explicitly. Example:
required=False, help="""Modify an enqueued job. The first argument must be the job ID (from `hatc -l`). `_` can be used as a placeholder for using an
already saved value for an argument (except <job_id>). If <shell> is used, <command> must be specified explicitly. Example:
hatc --modify 2 'free -g' 'now + 30 min' # Everything is updated for Job with ID 2
hatc -m 31 _ 'tomorrow at 14:30' # The command is kept as original, only time is updated
......@@ -77,7 +99,7 @@ def parse_arguments():
"""
)
parser.add_argument('-r', '--remove', dest='remove_job',
metavar='<JOB_ID>', nargs='+',
metavar='<job_id> [<job_id> ...]', nargs='+',
required=False, help="""Remove queued job(s) by Job ID. Example:
hatc --remove 12
......
......@@ -11,14 +11,13 @@ HAT_DIR='/usr/lib/hatd'
HAT_DB_DIR='/var/lib/hatd'
mkdir -p "${HAT_DIR}"
# Copy everything to `$HAT_DIR`
GLOBIGNORE='install.sh'
cp -aRt "${HAT_DIR}" *
# Copy required stuffs to `$HAT_DIR`
cp -aRt "${HAT_DIR}" ./{hat{,d,-client},env_base.sh}
# Put Systemd file for the daemon in relevant place.
# If this gives an error regarding wrong/absent destination directory,
# please put the file manually in your distro-advised place
cp "${HAT_DIR}"/system/hat-daemon.service /etc/systemd/system/
cp system/hat-daemon.service /etc/systemd/system/
# Create symlink for the client
ln -sf "${HAT_DIR}"/hat-client /usr/bin/hatc
......@@ -30,7 +29,7 @@ mkdir -p /var/log/hatd/
[[ -f ${HAT_DB_DIR}/hatdb.pkl ]] || { mkdir -p "${HAT_DB_DIR}" && : >"${HAT_DB_DIR}"/hatdb.pkl ;}
# Copying the logrotate file
cp "${HAT_DIR}"/system/hat-daemon /etc/logrotate.d/
cp system/hat-daemon /etc/logrotate.d/
# Create `hatd` group and set SETGID on `/var/run/hatd/locks/`
addgroup hatd
......@@ -51,3 +50,16 @@ systemctl daemon-reload
systemctl enable hat-daemon.service && \
systemctl start hatd.service && { printf '%s\n' "${msgs[@]}" || printf '%s\n' "Installation Failed!" ;}
#
# To uninstall (as superuser):
#
# 1. Stop the dameon and remove init file:
# systemctl stop hatd.service && \
# rm /etc/systemd/system/hat-daemon.service && \
# systemctl daemon-reload
# 2. Remove other files and directories:
# rm -r /var/lib/hatd/ /var/run/hatd/ /usr/lib/hatd/ /etc/logrotate.d/hat-daemon
#
# N.B: If you want to keep the enqueued jobs, don't remove `/var/lib/hatd/`, precisely `/var/lib/hatd/hatdb.pkl`.
#
# logrotate conf file for hatd
/var/log/hatd/*.log {
weekly
maxsize 10M
......
import datetime
import os
# import multiprocessing
import time
import json
# from lib.scheduler import Job
from lib.runner import BaseRunner
# from daemon import HatDaemon
DAEMON_IN = '/var/run/hatd/ipc/daemon_in.fifo'
DAEMON_OUT = '/var/run/hatd/ipc/daemon_out.fifo'
# These are server daemon and client codes...
# daemon = HatDaemon()
# daemon.start()
# print(daemon.status_verbose)
# print(daemon.pid)
BaseRunner.write_to_file(DAEMON_IN, json.dumps({
'add_job': {
'euid': os.geteuid(),
'command': 'cat /etc/apg.conf',
'time_': (datetime.datetime.now() + datetime.timedelta(minutes=1))
.strftime('%Y-%m-%d %H:%M:%S'),
# 'use_shell': True
}
}), 'wt', True)
BaseRunner.write_to_file(DAEMON_IN, json.dumps({
'add_job': {
'euid': os.geteuid(),
'command': 'caasdasdasd',
'time_': (datetime.datetime.now() + datetime.timedelta(minutes=1))
.strftime('%Y-%m-%d %H:%M:%S'),
'use_shell': True
}
}), 'wt', True)
BaseRunner.write_to_file(DAEMON_IN, json.dumps({
'add_job': {
'euid': os.geteuid(),
'command': 'cat /etc/shadow',
'time_': (datetime.datetime.now() + datetime.timedelta(minutes=2))
.strftime('%Y-%m-%d %H:%M:%S'),
# 'use_shell': True
}
}), 'wt', True)
BaseRunner.write_to_file(DAEMON_IN, json.dumps({
'add_job': {
'euid': os.geteuid(),
'command': 'bash -c "foo(){ echo HAT ;}; foo"',
'time_': (datetime.datetime.now() + datetime.timedelta(minutes=4))
.strftime('%Y-%m-%d %H:%M:%S'),
'use_shell': True
}
}), 'wt', True)
BaseRunner.write_to_file(DAEMON_IN, json.dumps({
'remove_job': (1000, 4)
}), 'wt', True)
BaseRunner.write_to_file(DAEMON_IN, json.dumps({
'jobcount': 1000
}), 'wt', True)
BaseRunner.write_to_file(DAEMON_IN, json.dumps({
'joblist': 1000
}), 'wt', True)
# daemon.remove_job(1000, 8, 1)
# daemon.remove_job(1)
with open(DAEMON_OUT) as f:
while True:
for line in f:
print(json.loads(line))
# time.sleep(120)
# daemon.stop()
# The runner object
# runner_ = BaseRunner()
# queue = runner_.get_queue()
# # Starting the runner
# # def runner_wraper(queue):
# # while True:
# # if runner_._running:
# # item = queue.get()
# # with open('/home/chayan/checking', 'a') as f:
# # f.write(str(queue) + 'dads')
# # if isinstance(item, dict):
# # command = item['command']
# # time_ = item['time_']
# # Job(command, time_)
# # else:
# # with open('/home/chayan/checking', 'a') as f:
# # f.write('start')
# # runner_.start()
# # time.sleep(0.1)
# print(runner_.jobcount)
# proc = multiprocessing.Process(target=runner_.start)
# proc.start()
# print(proc.is_alive())
# #runner_.start()
# # Creating test jobs
# Job('cat /etc/shadow',
# (datetime.datetime.now() + datetime.timedelta(minutes=1))
# .strftime('%Y-%m-%d %H:%M:%S'))
# Job('cat /proc/uptime',
# (datetime.datetime.now() + datetime.timedelta(minutes=1))
# .strftime('%Y-%m-%d %H:%M:%S'))
# Job('no_such_command',
# (datetime.datetime.now() + datetime.timedelta(minutes=5))
# .strftime('%Y-%m-%d %H:%M:%S'))
# Job('whoami',
# (datetime.datetime.now() + datetime.timedelta(minutes=10))
# .strftime('%Y-%m-%d %H:%M:%S'))
# print(runner_.jobcount)
# # Creating test jobs
# queue.put_nowait({'command': 'cat /proc/meminfo',
# 'time_': (
# datetime.datetime.now() + datetime.timedelta(minutes=1))
# .strftime('%Y-%m-%d %H:%M:%S')})
# queue.put_nowait({'command': 'cat /proc/irq/default_smp_affinity',
# 'time_': (
# datetime.datetime.now() + datetime.timedelta(minutes=2))
# .strftime('%Y-%m-%d %H:%M:%S'),
# 'use_shell': True})
# # print(runner_.jobcount)
# time.sleep(140)
# print(runner_.jobcount)
# runner_.stop()
# time.sleep(2)
# print(runner_._running)
# print(proc.is_alive())
# # q.put('oooopsie poopsie',
# # (datetime.datetime.now() + datetime.timedelta(minutes=1))
# # .strftime('%Y-%m-%d %H:%M:%S'))
# # q.put('no_such_command',
# # (datetime.datetime.now() + datetime.timedelta(minutes=5))
# # .strftime('%Y-%m-%d %H:%M:%S'))
# # q.put('whoami',
# # (datetime.datetime.now() + datetime.timedelta(minutes=10))
# # .strftime('%Y-%m-%d %H:%M:%S'))
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment