summaryrefslogtreecommitdiff
path: root/morphlib/cachekeycomputer.py
blob: ff0d595a3a9f1b0f642cca2cc718940298bed3b9 (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
# Copyright (C) 2012-2015  Codethink Limited
#
# 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; version 2 of the License.
#
# 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/>.


import hashlib
import logging

import morphlib


class CacheKeyComputer(object):

    def __init__(self, build_env):
        self._build_env = build_env
        self._calculated = {}
        self._hashed = {}

    def _filterenv(self, env):
        keys = ["LOGNAME", "MORPH_ARCH", "TARGET", "TARGET_STAGE1",
                "USER", "USERNAME"]
        return dict([(k, env[k]) for k in keys])

    def compute_key(self, source):
        try:
            return self._hashed[source]
        except KeyError:
            ret = self._hash_id(self.get_cache_id(source))
            self._hashed[source] = ret
            logging.debug(
                'computed cache key %s for artifact %s from source ',
                 ret, (source.repo_name, source.sha1, source.filename))
            return ret

    def _hash_id(self, cache_id):
        sha = hashlib.sha256()
        self._hash_dict(sha, cache_id)
        return sha.hexdigest()

    def _hash_thing(self, sha, thing):
        if type(thing) == dict:
            self._hash_dict(sha, thing)
        elif type(thing) == list:
            self._hash_list(sha, thing)
        elif type(thing) == tuple:
            self._hash_tuple(sha, thing)
        else:
            sha.update(str(thing))

    def _hash_dict(self, sha, d):
        for tup in sorted(d.iteritems()):
            self._hash_thing(sha, tup)

    def _hash_list(self, sha, l):
        for item in l:
            self._hash_thing(sha, item)

    def _hash_tuple(self, sha, tup):
        for item in tup:
            self._hash_thing(sha, item)

    def get_cache_id(self, source):
        try:
            ret = self._calculated[source]
            return ret
        except KeyError:
            cacheid = self._calculate(source)
            self._calculated[source] = cacheid
            return cacheid

    def _calculate(self, source):
        keys = {
            'env': self._filterenv(self._build_env.env),
            'kids': [{'artifact': a.name,
                      'cache-key': self.compute_key(a.source)}
                     for a in source.dependencies],
            'metadata-version': 1
        }

        morphology = source.morphology
        kind = morphology['kind']
        if kind == 'chunk':
            keys['build-mode'] = source.build_mode
            keys['prefix'] = source.prefix
            keys['tree'] = source.tree
            keys['split-rules'] = [(a, [rgx.pattern for rgx in r._regexes])
                                   for (a, r) in source.split_rules]

            # Avoid adding the 'extra-trees' key if there were no
            # extra-sources, to avoid unnecessary rebuilds
            if source.subtrees: # pragma no cover
                keys['extra-trees'] = source.subtrees

            # Include morphology contents, since it doesn't always come
            # from the source tree
            keys['devices'] = morphology.get('devices')
            keys['max-jobs'] = morphology.get('max-jobs')
            keys['system-integration'] = morphology.get('system-integration',
                                                        {})
            # products is omitted as they are part of the split-rules
            # include {pre-,,post-}{configure,build,test,install}-commands
            # in morphology key
            for prefix in ('pre-', '', 'post-'):
                for cmdtype in ('configure', 'build', 'test',
                                'install', 'strip'):
                    cmd_field = prefix + cmdtype + '-commands'
                    if cmd_field in morphology:
                        keys[cmd_field] = morphology[cmd_field]
        elif kind in ('system', 'stratum'):
            morph_dict = dict((k, morphology[k]) for k in morphology.keys())

            # Disregard all fields of a morphology that aren't important
            ignored_fields = (
                'description', # purely cosmetic, doesn't change builds
                # Configuration extensions don't run at build time, therefore
                # they don't have to be included in the cache key.
                'configuration-extensions',
                # The following are used to determine dependencies,
                # so are already handled by the 'kids' field.
                'strata', 'build-depends', 'chunks',
                'products')
            for key in morph_dict:
                if key not in ignored_fields:
                    keys[key] = morph_dict[key]
        if kind == 'stratum':
            keys['stratum-format-version'] = 1
        elif kind == 'system':
            keys['system-compatibility-version'] = "2~ (upgradable, root rw)"

        return keys