blob: efc6b3a946397031caf48d4ba7f505e52f3894fe [file] [log] [blame]
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001#
2# ex:ts=4:sw=4:sts=4:et
3# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
4#
5# BitBake Toaster Implementation
6#
Brad Bishopd7bf8c12018-02-25 22:55:05 -05007# Copyright (C) 2016-2017 Intel Corporation
Patrick Williamsc0f7c042017-02-23 20:41:17 -06008#
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License version 2 as
11# published by the Free Software Foundation.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License along
19# with this program; if not, write to the Free Software Foundation, Inc.,
20# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
Brad Bishopd7bf8c12018-02-25 22:55:05 -050022from django.core.management.base import BaseCommand
Patrick Williamsc0f7c042017-02-23 20:41:17 -060023
24from orm.models import LayerSource, Layer, Release, Layer_Version
25from orm.models import LayerVersionDependency, Machine, Recipe
Brad Bishopd7bf8c12018-02-25 22:55:05 -050026from orm.models import Distro
27from orm.models import ToasterSetting
Patrick Williamsc0f7c042017-02-23 20:41:17 -060028
Patrick Williamsc124f4f2015-09-15 14:41:29 -050029import os
Patrick Williamsc0f7c042017-02-23 20:41:17 -060030import sys
31
32import json
33import logging
34import threading
35import time
36logger = logging.getLogger("toaster")
37
38DEFAULT_LAYERINDEX_SERVER = "http://layers.openembedded.org/layerindex/api/"
39
40
41class Spinner(threading.Thread):
42 """ A simple progress spinner to indicate download/parsing is happening"""
43 def __init__(self, *args, **kwargs):
44 super(Spinner, self).__init__(*args, **kwargs)
45 self.setDaemon(True)
46 self.signal = True
47
48 def run(self):
49 os.system('setterm -cursor off')
50 while self.signal:
51 for char in ["/", "-", "\\", "|"]:
52 sys.stdout.write("\r" + char)
53 sys.stdout.flush()
54 time.sleep(0.25)
55 os.system('setterm -cursor on')
56
57 def stop(self):
58 self.signal = False
59
Patrick Williamsc124f4f2015-09-15 14:41:29 -050060
Brad Bishopd7bf8c12018-02-25 22:55:05 -050061class Command(BaseCommand):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060062 args = ""
63 help = "Updates locally cached information from a layerindex server"
Patrick Williamsc124f4f2015-09-15 14:41:29 -050064
Patrick Williamsc0f7c042017-02-23 20:41:17 -060065 def mini_progress(self, what, i, total):
66 i = i + 1
67 pec = (float(i)/float(total))*100
68
69 sys.stdout.write("\rUpdating %s %d%%" %
70 (what,
71 pec))
72 sys.stdout.flush()
73 if int(pec) is 100:
74 sys.stdout.write("\n")
75 sys.stdout.flush()
76
77 def update(self):
78 """
79 Fetches layer, recipe and machine information from a layerindex
80 server
81 """
82 os.system('setterm -cursor off')
83
84 self.apiurl = DEFAULT_LAYERINDEX_SERVER
Brad Bishopd7bf8c12018-02-25 22:55:05 -050085 if ToasterSetting.objects.filter(name='CUSTOM_LAYERINDEX_SERVER').count() == 1:
86 self.apiurl = ToasterSetting.objects.get(name = 'CUSTOM_LAYERINDEX_SERVER').value
Patrick Williamsc0f7c042017-02-23 20:41:17 -060087
88 assert self.apiurl is not None
89 try:
90 from urllib.request import urlopen, URLError
91 from urllib.parse import urlparse
92 except ImportError:
93 from urllib2 import urlopen, URLError
94 from urlparse import urlparse
95
96 proxy_settings = os.environ.get("http_proxy", None)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060097
Brad Bishopd7bf8c12018-02-25 22:55:05 -050098 def _get_json_response(apiurl=None):
99 if None == apiurl:
100 apiurl=self.apiurl
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600101 http_progress = Spinner()
102 http_progress.start()
103
104 _parsedurl = urlparse(apiurl)
105 path = _parsedurl.path
106
107 # logger.debug("Fetching %s", apiurl)
108 try:
109 res = urlopen(apiurl)
110 except URLError as e:
111 raise Exception("Failed to read %s: %s" % (path, e.reason))
112
113 parsed = json.loads(res.read().decode('utf-8'))
114
115 http_progress.stop()
116 return parsed
117
118 # verify we can get the basic api
119 try:
120 apilinks = _get_json_response()
121 except Exception as e:
122 import traceback
123 if proxy_settings is not None:
124 logger.info("EE: Using proxy %s" % proxy_settings)
125 logger.warning("EE: could not connect to %s, skipping update:"
126 "%s\n%s" % (self.apiurl, e, traceback.format_exc()))
127 return
128
129 # update branches; only those that we already have names listed in the
130 # Releases table
131 whitelist_branch_names = [rel.branch_name
132 for rel in Release.objects.all()]
133 if len(whitelist_branch_names) == 0:
134 raise Exception("Failed to make list of branches to fetch")
135
136 logger.info("Fetching metadata releases for %s",
137 " ".join(whitelist_branch_names))
138
139 branches_info = _get_json_response(apilinks['branches'] +
140 "?filter=name:%s"
141 % "OR".join(whitelist_branch_names))
142
143 # Map the layer index branches to toaster releases
144 li_branch_id_to_toaster_release = {}
145
146 total = len(branches_info)
147 for i, branch in enumerate(branches_info):
148 li_branch_id_to_toaster_release[branch['id']] = \
149 Release.objects.get(name=branch['name'])
150 self.mini_progress("Releases", i, total)
151
152 # keep a track of the layerindex (li) id mappings so that
153 # layer_versions can be created for these layers later on
154 li_layer_id_to_toaster_layer_id = {}
155
156 logger.info("Fetching layers")
157
158 layers_info = _get_json_response(apilinks['layerItems'])
159
160 total = len(layers_info)
161 for i, li in enumerate(layers_info):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600162 try:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500163 l, created = Layer.objects.get_or_create(name=li['name'])
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600164 l.up_date = li['updated']
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600165 l.summary = li['summary']
166 l.description = li['description']
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500167
168 if created:
169 # predefined layers in the fixtures (for example poky.xml)
170 # always preempt the Layer Index for these values
171 l.vcs_url = li['vcs_url']
172 l.vcs_web_url = li['vcs_web_url']
173 l.vcs_web_tree_base_url = li['vcs_web_tree_base_url']
174 l.vcs_web_file_base_url = li['vcs_web_file_base_url']
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600175 l.save()
176 except Layer.MultipleObjectsReturned:
177 logger.info("Skipped %s as we found multiple layers and "
178 "don't know which to update" %
179 li['name'])
180
181 li_layer_id_to_toaster_layer_id[li['id']] = l.pk
182
183 self.mini_progress("layers", i, total)
184
185 # update layer_versions
186 logger.info("Fetching layer versions")
187 layerbranches_info = _get_json_response(
188 apilinks['layerBranches'] + "?filter=branch__name:%s" %
189 "OR".join(whitelist_branch_names))
190
191 # Map Layer index layer_branch object id to
192 # layer_version toaster object id
193 li_layer_branch_id_to_toaster_lv_id = {}
194
195 total = len(layerbranches_info)
196 for i, lbi in enumerate(layerbranches_info):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500197 # release as defined by toaster map to layerindex branch
198 release = li_branch_id_to_toaster_release[lbi['branch']]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600199
200 try:
201 lv, created = Layer_Version.objects.get_or_create(
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600202 layer=Layer.objects.get(
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500203 pk=li_layer_id_to_toaster_layer_id[lbi['layer']]),
204 release=release
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600205 )
206 except KeyError:
207 logger.warning(
208 "No such layerindex layer referenced by layerbranch %d" %
209 lbi['layer'])
210 continue
211
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500212 if created:
213 lv.release = li_branch_id_to_toaster_release[lbi['branch']]
214 lv.up_date = lbi['updated']
215 lv.commit = lbi['actual_branch']
216 lv.dirpath = lbi['vcs_subdir']
217 lv.save()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600218
219 li_layer_branch_id_to_toaster_lv_id[lbi['id']] =\
220 lv.pk
221 self.mini_progress("layer versions", i, total)
222
223 logger.info("Fetching layer version dependencies")
224 # update layer dependencies
225 layerdependencies_info = _get_json_response(
226 apilinks['layerDependencies'] +
227 "?filter=layerbranch__branch__name:%s" %
228 "OR".join(whitelist_branch_names))
229
230 dependlist = {}
231 for ldi in layerdependencies_info:
232 try:
233 lv = Layer_Version.objects.get(
234 pk=li_layer_branch_id_to_toaster_lv_id[ldi['layerbranch']])
235 except Layer_Version.DoesNotExist as e:
236 continue
237
238 if lv not in dependlist:
239 dependlist[lv] = []
240 try:
241 layer_id = li_layer_id_to_toaster_layer_id[ldi['dependency']]
242
243 dependlist[lv].append(
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500244 Layer_Version.objects.get(layer__pk=layer_id,
245 release=lv.release))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600246
247 except Layer_Version.DoesNotExist:
248 logger.warning("Cannot find layer version (ls:%s),"
249 "up_id:%s lv:%s" %
250 (self, ldi['dependency'], lv))
251
252 total = len(dependlist)
253 for i, lv in enumerate(dependlist):
254 LayerVersionDependency.objects.filter(layer_version=lv).delete()
255 for lvd in dependlist[lv]:
256 LayerVersionDependency.objects.get_or_create(layer_version=lv,
257 depends_on=lvd)
258 self.mini_progress("Layer version dependencies", i, total)
259
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500260 # update Distros
261 logger.info("Fetching distro information")
262 distros_info = _get_json_response(
263 apilinks['distros'] + "?filter=layerbranch__branch__name:%s" %
264 "OR".join(whitelist_branch_names))
265
266 total = len(distros_info)
267 for i, di in enumerate(distros_info):
268 distro, created = Distro.objects.get_or_create(
269 name=di['name'],
270 layer_version=Layer_Version.objects.get(
271 pk=li_layer_branch_id_to_toaster_lv_id[di['layerbranch']]))
272 distro.up_date = di['updated']
273 distro.name = di['name']
274 distro.description = di['description']
275 distro.save()
276 self.mini_progress("distros", i, total)
277
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600278 # update machines
279 logger.info("Fetching machine information")
280 machines_info = _get_json_response(
281 apilinks['machines'] + "?filter=layerbranch__branch__name:%s" %
282 "OR".join(whitelist_branch_names))
283
284 total = len(machines_info)
285 for i, mi in enumerate(machines_info):
286 mo, created = Machine.objects.get_or_create(
287 name=mi['name'],
288 layer_version=Layer_Version.objects.get(
289 pk=li_layer_branch_id_to_toaster_lv_id[mi['layerbranch']]))
290 mo.up_date = mi['updated']
291 mo.name = mi['name']
292 mo.description = mi['description']
293 mo.save()
294 self.mini_progress("machines", i, total)
295
296 # update recipes; paginate by layer version / layer branch
297 logger.info("Fetching recipe information")
298 recipes_info = _get_json_response(
299 apilinks['recipes'] + "?filter=layerbranch__branch__name:%s" %
300 "OR".join(whitelist_branch_names))
301
302 total = len(recipes_info)
303 for i, ri in enumerate(recipes_info):
304 try:
305 lv_id = li_layer_branch_id_to_toaster_lv_id[ri['layerbranch']]
306 lv = Layer_Version.objects.get(pk=lv_id)
307
308 ro, created = Recipe.objects.get_or_create(
309 layer_version=lv,
310 name=ri['pn']
311 )
312
313 ro.layer_version = lv
314 ro.up_date = ri['updated']
315 ro.name = ri['pn']
316 ro.version = ri['pv']
317 ro.summary = ri['summary']
318 ro.description = ri['description']
319 ro.section = ri['section']
320 ro.license = ri['license']
321 ro.homepage = ri['homepage']
322 ro.bugtracker = ri['bugtracker']
323 ro.file_path = ri['filepath'] + "/" + ri['filename']
324 if 'inherits' in ri:
325 ro.is_image = 'image' in ri['inherits'].split()
326 else: # workaround for old style layer index
327 ro.is_image = "-image-" in ri['pn']
328 ro.save()
329 except Exception as e:
330 logger.warning("Failed saving recipe %s", e)
331
332 self.mini_progress("recipes", i, total)
333
334 os.system('setterm -cursor on')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500335
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500336 def handle(self, **options):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600337 self.update()