summaryrefslogtreecommitdiff
path: root/lorry-controller
blob: b1f4d86296f20d79b5119be1d563ed32833b1cc5 (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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#!/usr/bin/env python
#
# Copyright (C) 2012  Codethink Limited


import cliapp
import logging
import os
import time

defaults = {
    'work-area': '/home/lorry/controller-area',
    'config-name': 'lorry-controller.conf',
    'lorry': 'lorry',
}

from lorrycontroller.confparser import LorryControllerConfig
from lorrycontroller.workingstate import WorkingStateManager

class LorryController(cliapp.Application):

    def add_settings(self):
        self.settings.string(['work-area'],
                             'path to the area for  the controller to work in',
                             metavar='PATH',
                             default=defaults['work-area'])
        self.settings.boolean(['dry-run'],
                              "do a dry-run and don't actually do anything "
                              "beyond updating the git tree",
                              default=False)
        self.settings.string(['lorry'],
                             'path to the lorry binary to use',
                             metavar='LORRY',
                             default=defaults['lorry'])
        self.settings.string(['config-name'],
                             'configuration leafname.  Defaults to '
                             'lorry-controller.conf',
                             metavar='CONFNAME',
                             default=defaults['config-name'])
        self.settings.boolean(['lorry-verbose'],
                              'Whether to pass --verbose to lorry',
                              default=False)
        self.settings.string(['lorry-log'],
                             'Log file name for lorry if wanted',
                             metavar='LORRYLOG',
                             default=None)

    def process_args(self, args):
        logging.info("Starting to control lorry")
        try:
            os.chdir(self.settings['work-area'])
        except OSError, e:
            logging.error("Unable to chdir() to %s" % 
                          self.settings['work-area'])
            raise SystemExit(2)
        if not os.path.isdir("git"):
            logging.error("Unable to find git checkout")
            raise SystemExit(3)
        if not os.path.isdir("work"):
            os.mkdir("work")

        logging.info("Updating configuration checkout")
        self.rungit(['remote', 'update', 'origin'])
        self.rungit(['reset', '--hard', 'origin/master'])
        self.rungit(['clean', '-fdx'])

        self.lorrycmd=[self.settings['lorry']]
        if self.settings['lorry-verbose']:
            self.lorrycmd += ["--verbose"]
        if self.settings['lorry-log'] is not None:
            self.lorrycmd += ["--log", self.settings['lorry-log']]

        if not os.path.exists(os.path.join('git',
                                           self.settings['config-name'])):
            logging.error("Unable to find lorry-controller.conf in git")
            raise SystemExit(4)

        self.conf = LorryControllerConfig(self, 'git/lorry-controller.conf')

        with WorkingStateManager(self) as mgr:
            # Update any troves
            self.conf.update_troves(mgr)
            prev_lorries = set(mgr.lorry_state.keys())
            cur_lorries = set(self.conf.lorries.keys())
            logging.info("Starting processing.  Previously %d lorries "
                         "were handled.  We currently have %d defined." % (
                    len(prev_lorries), len(cur_lorries)))

            # 1. Handle deletes for any old lorries we no longer want
            logging.info("Delete any old lorries...")
            for dead_lorry in prev_lorries - cur_lorries:
                logging.info("Dead lorry: %s" % dead_lorry)
                conf_uuid = mgr.lorry_state[dead_lorry]['conf']
                should_delete = self.conf.configs[conf_uuid]['destroy']
                # TODO: also handle 'unchanged'
                if should_delete == "always":
                    logging.warning("TODO: Delete from Trove")
                del mgr.lorry_state[dead_lorry]

            # 2. Handle creates for any new lorries we now want
            logging.info("Create any new lorries...")
            for new_lorry in cur_lorries - prev_lorries:
                logging.info("New lorry: %s" % new_lorry)
                lorry = self.conf.lorries[new_lorry]
                conf_uuid = lorry['controller-uuid']
                conf = self.conf.configs[conf_uuid]
                nextdue = self.conf.duetimes[new_lorry]
                should_create = conf['create'] == "always"
                store_state = True
                if should_create:
                    exit, out, err = self.maybe_runcmd(["ssh", "git@localhost",
                                                        "create", new_lorry])
                    if exit != 0:
                        if ' already exists' in err:
                            logging.warn("Repository %s already exists" %
                                         new_lorry)
                        else:
                            logging.error("Unable to create repository %s" %
                                          new_lorry)
                            logging.error(err)
                            store_state = False
                if store_state:
                    mgr.lorry_state[new_lorry] = {
                        'conf': conf_uuid,
                        'lorry': lorry,
                        'next-due': nextdue,
                        }
                else:
                    # Remove this from cur_lorries so we don't run it
                    cur_lorries.remove(new_lorry)

            # 3. For every lorry we have, update the settings if necessary.
            #    and reset the next-due as appropriate.
            logging.info("Update active lorry configurations...")
            updated_count = 0
            for upd_lorry in cur_lorries:
                if mgr.lorry_state[upd_lorry]['lorry'] != \
                        self.conf.lorries[upd_lorry]:
                    lorry = self.conf.lorries[upd_lorry]
                    conf_uuid = lorry['controller-uuid']
                    nextdue = self.conf.duetimes[upd_lorry]
                    mgr.lorry_state[upd_lorry] = {
                        'conf': conf_uuid,
                        'lorry': lorry,
                        'next-due': nextdue,
                    }
                    updated_count += 1
            logging.info("Result: %d/%d lorries needed updating" % (
                    updated_count, len(cur_lorries)))

            # 3. Iterate all active lorries and see if they're due
            logging.info("Iterate active lorries looking for work...")
            now = time.time()
            lorried = 0
            earliest_due = None
            what_early_due = ""
            lorries_to_run = []
            for lorry in cur_lorries:
                state = mgr.lorry_state[lorry]
                conf_uuid = state['conf']
                conf = self.conf.configs[conf_uuid]
                due = state['next-due']
                if now >= due:
                    lorries_to_run.append(lorry)
            lorries_to_run.sort()
            for lorry in lorries_to_run:
                state = mgr.lorry_state[lorry]
                conf_uuid = state['conf']
                conf = self.conf.configs[conf_uuid]
                due = state['next-due']
                lorried += 1
                logging.info("Running %d/%d. Lorrying: %s" % (
                        lorried, len(lorries_to_run),lorry))
                with mgr.runner(lorry) as runner:
                    runner.run_lorry(*self.lorrycmd)
                while state['next-due'] <= now:
                    state['next-due'] += conf['interval-parsed']

            for lorry in cur_lorries:
                state = mgr.lorry_state[lorry]
                due = state['next-due']
                if earliest_due is None or due < earliest_due:
                    earliest_due = due
                    what_early_due = lorry

            if earliest_due is None:
                logging.info("Lorried %d.  No idea what's next." % lorried)
            else:
                logging.info("Lorried %d.  %s due in %d seconds" % (
                        lorried, what_early_due, int(earliest_due - now)))
            logging.info("All done.")

    def rungit(self, args):
        self.runcmd(['git']+args, cwd=os.path.join(self.settings['work-area'],
                                                   'git'))

    def maybe_runcmd(self, *args, **kwargs):
        if not self.settings['dry-run']:
            return self.runcmd_unchecked(*args, **kwargs)
        else:
            logging.debug("DRY-RUN: Not running %r" % args)
            return 0, 'DRY-RUN', 'DRY-RUN'

if __name__ == '__main__':
    LorryController(version='1').run()