summaryrefslogtreecommitdiff
path: root/desktop-cronish
blob: 338aef5fb29052e03fd9732f47276a84ad99e270 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#!/usr/bin/python
# Copyright 2013  Lars Wirzenius
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# =*= License: GPL-3+ =*=


import cliapp
import logging
import os
import time
import sys
import ttystatus
import yaml


import cronish


class DesktopCronish(cliapp.Application):

    def add_settings(self):
        self.settings.integer(
            ['max-jobs'],
            'run at least N jobs, then quit (use 0 for infinite)',
            metavar='N',
            default=0)
    
        self.settings.boolean(
            ['quiet', 'q'],
            'no status messaging to terminal')
            
        self.settings.integer(
            ['sleep'],
            'if there is no known job, sleep for SECONDS',
            default=1)
    
    def process_args(self, args):
        self.ts = ttystatus.TerminalStatus(period=0.1)
        self.ts.format('%String(timestamp) %String(msg)')
        if self.settings['quiet']:
            self.ts.disable()
        self.jobs = {}
        self.previously = {}
        self.process_inputs(args)
        self.execute_jobs()
        self.ts.finish()

    def status(self, msg):
        logging.info(msg)
        self.ts['timestamp'] = time.strftime('%H:%M:%S')
        self.ts['msg'] = ' '.join(msg.split('\n'))
        self.ts.flush()
    
    def process_input(self, filename):
        self.status('Loading jobs from %s' % filename)
        with self.open_input(filename, 'r') as f:
            job_dict = yaml.safe_load(f)
        self.jobs.update(job_dict)

    def execute_jobs(self):
        n = 0
        max_jobs = self.settings['max-jobs']
        while max_jobs == 0 or n < max_jobs:
            job_name, when = self.choose_job()
            if job_name is not None:
                self.wait_until(when, job_name)
                self.execute_job(job_name)
            else:
                self.status(
                    'No idea what to do, sleeping for %d seconds' %
                        self.settings['sleep'])
                time.sleep(self.settings['sleep'])
            n += 1
        self.status('Stopped executing after %d jobs' % n)
    
    def choose_job(self):
        next_job_name = None
        next_when = 0
        for job_name, job in self.jobs.items():
            if 'interval' in job:
                job_when = self.when_interval_job(job_name, job)
            elif 'trigger-file' in job:
                job_when = self.when_trigger_file_job(job_name, job)
            else:
                raise cliapp.AppException(
                    'Unknown job trigger for %s' % job_name)
            if job_when is not None:
                if next_job_name is None or job_when <= next_when:
                    next_job_name = job_name
                    next_when = job_when
        return next_job_name, next_when
    
    def when_interval_job(self, job_name, job):
        return self.previously.get(job_name, 0) + job['interval']
    
    def when_trigger_file_job(self, job_name, job):
        filename = job['trigger-file']

        # If file doesn't exist, trigger now.
        if not os.path.exists(filename):
            return self.now()

        # If there is no max age for file, but it exists, never trigger.
        if 'trigger-age' not in job:
            return None

        # If the file exists and is too old, trigger now.
        mtime = os.path.getmtime(filename)
        if mtime + job['trigger-age'] <= self.now():
            return self.now()
        
        # Do not trigger now. We can't compute the next time to trigger:
        # the file  might go missing, or get updated, so we need to test
        # it every iteration.
        return None
    
    def wait_until(self, when, for_what):
        while self.now() < when:
            seconds = when - self.now()
            t = time.strftime('%H:%M:%S', time.localtime(when))
            self.status('Sleeping until %s for %s' % (t, for_what))
            time.sleep(seconds)
    
    def execute_job(self, job_name):
        job = self.jobs[job_name]
        self.ts.notify(
            '%s Executing job %s' % (time.strftime('%H:%M:%S'), job_name))
        self.status('Started command: %s' % job['command'])
        argv = ['sh', '-c', job['command']]
        if 'timeout' in job:
            argv = ['timeout', str(job['timeout'])] + argv
        exit, out, err = cliapp.runcmd_unchecked(argv)
        if out.endswith('\n'):
            out = out[:-1]
        if out:
            self.ts.notify(out)
        if exit != 0:
            self.ts.error(
                'ERROR: Job %s: Command failed: %s' %
                    (job_name, job['command']))
            if err:
                self.ts.error(err)
        self.previously[job_name] = self.now()

    def now(self):
        return time.time()


DesktopCronish(version=cronish.__version__).run()