]> git.ipfire.org Git - ipfire.org.git/blob - src/backend/fireinfo.py
Merge branch 'fireinfo-wip' into new-design
[ipfire.org.git] / src / backend / fireinfo.py
1 #!/usr/bin/python
2
3 import datetime
4 import iso3166
5 import json
6 import jsonschema
7 import logging
8 import re
9
10 from . import hwdata
11 from . import util
12 from .misc import Object
13 from .decorators import *
14
15 N_ = lambda x: x
16
17 CPU_VENDORS = {
18 "AMDisbetter!" : "AMD",
19 "AuthenticAMD" : "AMD",
20 "CentaurHauls" : "VIA",
21 "CyrixInstead" : "Cyrix",
22 "GenuineIntel" : "Intel",
23 "TransmetaCPU" : "Transmeta",
24 "GenuineTMx86" : "Transmeta",
25 "Geode by NSC" : "NSC",
26 "NexGenDriven" : "NexGen",
27 "RiseRiseRise" : "Rise",
28 "SiS SiS SiS" : "SiS",
29 "SiS SiS SiS " : "SiS",
30 "UMC UMC UMC " : "UMC",
31 "VIA VIA VIA " : "VIA",
32 "Vortex86 SoC" : "Vortex86",
33 }
34
35 CPU_STRINGS = (
36 ### AMD ###
37 # APU
38 (r"AMD (Sempron)\(tm\) (\d+) APU with Radeon\(tm\) R\d+", r"AMD \1 \2 APU"),
39 (r"AMD ([\w\-]+) APU with Radeon\(tm\) HD Graphics", r"AMD \1 APU"),
40 (r"AMD ([\w\-]+) Radeon R\d+, \d+ Compute Cores \d+C\+\d+G", r"AMD \1 APU"),
41 # Athlon
42 (r"AMD Athlon.* II X2 ([a-z0-9]+).*", r"AMD Athlon X2 \1"),
43 (r"AMD Athlon\(tm\) 64 Processor (\w+)", r"AMD Athlon64 \1"),
44 (r"AMD Athlon\(tm\) 64 X2 Dual Core Processor (\w+)", r"AMD Athlon64 X2 \1"),
45 (r"(AMD Athlon).*(XP).*", r"\1 \2"),
46 (r"(AMD Phenom).* ([0-9]+) .*", r"\1 \2"),
47 (r"(AMD Phenom).*", r"\1"),
48 (r"(AMD Sempron).*", r"\1"),
49 # Geode
50 (r"Geode\(TM\) Integrated Processor by AMD PCS", r"AMD Geode"),
51 (r"(Geode).*", r"\1"),
52 # Mobile
53 (r"Mobile AMD (Athlon|Sempron)\(tm\) Processor (\d+\+?)", r"AMD \1-M \2"),
54
55 # Intel
56 (r"Intel\(R\) (Atom|Celeron).*CPU\s*([A-Z0-9]+) .*", r"Intel \1 \2"),
57 (r"(Intel).*(Celeron).*", r"\1 \2"),
58 (r"Intel\(R\)? Core\(TM\)?2 Duo *CPU .* ([A-Z0-9]+) .*", r"Intel C2D \1"),
59 (r"Intel\(R\)? Core\(TM\)?2 Duo CPU (\w+)", r"Intel C2D \1"),
60 (r"Intel\(R\)? Core\(TM\)?2 CPU .* ([A-Z0-9]+) .*", r"Intel C2 \1"),
61 (r"Intel\(R\)? Core\(TM\)?2 Quad *CPU .* ([A-Z0-9]+) .*", r"Intel C2Q \1"),
62 (r"Intel\(R\)? Core\(TM\)? (i[753]\-\w+) CPU", r"Intel Core \1"),
63 (r"Intel\(R\)? Xeon\(R\)? CPU (\w+) (0|v\d+)", r"Intel Xeon \1 \2"),
64 (r"Intel\(R\)? Xeon\(R\)? CPU\s+(\w+)", r"Intel Xeon \1"),
65 (r"(Intel).*(Xeon).*", r"\1 \2"),
66 (r"Intel.* Pentium.* (D|4) .*", r"Intel Pentium \1"),
67 (r"Intel.* Pentium.* Dual .* ([A-Z0-9]+) .*", r"Intel Pentium Dual \1"),
68 (r"Pentium.* Dual-Core .* ([A-Z0-9]+) .*", r"Intel Pentium Dual \1"),
69 (r"(Pentium I{2,3}).*", r"Intel \1"),
70 (r"(Celeron \(Coppermine\))", r"Intel Celeron"),
71
72 # NSC
73 (r"Geode\(TM\) Integrated Processor by National Semi", r"NSC Geode"),
74
75 # VIA
76 (r"(VIA \w*).*", r"\1"),
77
78 # Qemu
79 (r"QEMU Virtual CPU version .*", r"QEMU CPU"),
80
81 # ARM
82 (r"Feroceon .*", r"ARM Feroceon"),
83 )
84
85 PROFILE_SCHEMA = {
86 "$schema" : "https://json-schema.org/draft/2020-12/schema",
87 "$id" : "https://fireinfo.ipfire.org/profile.schema.json",
88 "title" : "Fireinfo Profile",
89 "description" : "Fireinfo Profile",
90 "type" : "object",
91
92 # Properties
93 "properties" : {
94 # Processor
95 "cpu" : {
96 "type" : "object",
97 "properties" : {
98 "arch" : {
99 "type" : "string",
100 "pattern" : r"^[a-z0-9\_]{,8}$",
101 },
102 "count" : {
103 "type" : "integer",
104 },
105 "family" : {
106 "type" : "integer",
107 },
108 "flags" : {
109 "type" : "array",
110 "items" : {
111 "type" : "string",
112 "pattern" : r"^.{,24}$",
113 },
114 },
115 "model" : {
116 "type" : "integer",
117 },
118 "model_string" : {
119 "type" : "string",
120 "pattern" : r"^.{,80}$",
121 },
122 "speed" : {
123 "type" : "number",
124 },
125 "stepping" : {
126 "type" : "integer",
127 },
128 "vendor" : {
129 "type" : "string",
130 "pattern" : r"^.{,80}$",
131 },
132 },
133 "additionalProperties" : False,
134 "required" : [
135 "arch",
136 "count",
137 "family",
138 "flags",
139 "model",
140 "model_string",
141 "speed",
142 "stepping",
143 "vendor",
144 ],
145 },
146
147 # Devices
148 "devices" : {
149 "type" : "array",
150 "items" : {
151 "type" : "object",
152 "properties" : {
153 "deviceclass" : {
154 "type" : ["string", "null"],
155 "pattern" : r"^.{,20}$",
156 },
157 "driver" : {
158 "type" : ["string", "null"],
159 "pattern" : r"^.{,24}$",
160 },
161 "model" : {
162 "type" : "string",
163 "pattern" : r"^[a-z0-9]{4}$",
164 },
165 "sub_model" : {
166 "type" : ["string", "null"],
167 "pattern" : r"^[a-z0-9]{4}$",
168 },
169 "sub_vendor" : {
170 "type" : ["string", "null"],
171 "pattern" : r"^[a-z0-9]{4}$",
172 },
173 "subsystem" : {
174 "type" : "string",
175 "pattern" : r"^[a-z]{3}$",
176 },
177 "vendor" : {
178 "type" : "string",
179 "pattern" : r"^[a-z0-9]{4}$",
180 },
181 },
182 "additionalProperties" : False,
183 "required" : [
184 "deviceclass",
185 "driver",
186 "model",
187 "subsystem",
188 "vendor",
189 ],
190 },
191 },
192
193 # Network
194 "network" : {
195 "type" : "object",
196 "properties" : {
197 "blue" : {
198 "type" : "boolean",
199 },
200 "green" : {
201 "type" : "boolean",
202 },
203 "orange" : {
204 "type" : "boolean",
205 },
206 "red" : {
207 "type" : "boolean",
208 },
209 },
210 "additionalProperties" : False,
211 },
212
213 # System
214 "system" : {
215 "type" : "object",
216 "properties" : {
217 "kernel_release" : {
218 "type" : "string",
219 "pattern" : r"^.{,40}$",
220 },
221 "language" : {
222 "type" : "string",
223 "pattern" : r"^[a-z]{2}$",
224 },
225 "memory" : {
226 "type" : "integer",
227 },
228 "model" : {
229 "type" : "string",
230 "pattern" : r"^.{,80}$",
231 },
232 "release" : {
233 "type" : "string",
234 "pattern" : r"^.{,80}$",
235 },
236 "root_size" : {
237 "type" : "number",
238 },
239 "vendor" : {
240 "type" : "string",
241 "pattern" : r"^.{,80}$",
242 },
243 "virtual" : {
244 "type" : "boolean"
245 },
246 },
247 "additionalProperties" : False,
248 "required" : [
249 "kernel_release",
250 "language",
251 "memory",
252 "model",
253 "release",
254 "root_size",
255 "vendor",
256 "virtual",
257 ],
258 },
259
260 # Hypervisor
261 "hypervisor" : {
262 "type" : "object",
263 "properties" : {
264 "vendor" : {
265 "type" : "string",
266 "pattern" : r"^.{,40}$",
267 },
268 },
269 "additionalProperties" : False,
270 "required" : [
271 "vendor",
272 ],
273 },
274
275 # Error - BogoMIPS
276 "bogomips" : {
277 "type" : "number",
278 },
279 },
280 "additionalProperties" : False,
281 "required" : [
282 "cpu",
283 "devices",
284 "network",
285 "system",
286 ],
287 }
288
289 class Network(Object):
290 def init(self, blob):
291 self.blob = blob
292
293 def __iter__(self):
294 ret = []
295
296 for zone in ("red", "green", "orange", "blue"):
297 if self.has_zone(zone):
298 ret.append(zone)
299
300 return iter(ret)
301
302 def has_zone(self, name):
303 return self.blob.get(name, False)
304
305 @property
306 def has_red(self):
307 return self.has_zone("red")
308
309 @property
310 def has_green(self):
311 return self.has_zone("green")
312
313 @property
314 def has_orange(self):
315 return self.has_zone("orange")
316
317 @property
318 def has_blue(self):
319 return self.has_zone("blue")
320
321
322 class Processor(Object):
323 def init(self, blob):
324 self.blob = blob
325
326 def __str__(self):
327 s = []
328
329 if self.model_string and not self.model_string.startswith(self.vendor):
330 s.append(self.vendor)
331 s.append("-")
332
333 s.append(self.model_string or "Generic")
334
335 if self.core_count > 1:
336 s.append("x%s" % self.core_count)
337
338 return " ".join(s)
339
340 @property
341 def vendor(self):
342 vendor = self.blob.get("vendor")
343
344 try:
345 return CPU_VENDORS[vendor]
346 except KeyError:
347 return vendor
348
349 @property
350 def family(self):
351 return self.blob.get("family")
352
353 @property
354 def model(self):
355 return self.blob.get("model")
356
357 @property
358 def stepping(self):
359 return self.blob.get("stepping")
360
361 @property
362 def model_string(self):
363 return self.blob.get("model_string")
364
365 @property
366 def flags(self):
367 return self.blob.get("flags")
368
369 def has_flag(self, flag):
370 return flag in self.flags
371
372 def uses_ht(self):
373 if self.vendor == "Intel" and self.family == 6 and self.model in (15, 55, 76, 77):
374 return False
375
376 return self.has_flag("ht")
377
378 @property
379 def core_count(self):
380 return self.blob.get("count", 1)
381
382 @property
383 def count(self):
384 if self.uses_ht():
385 return self.core_count // 2
386
387 return self.core_count
388
389 @property
390 def clock_speed(self):
391 return self.__clock_speed
392
393 def format_clock_speed(self):
394 if not self.clock_speed:
395 return
396
397 if self.clock_speed < 1000:
398 return "%dMHz" % self.clock_speed
399
400 return "%.2fGHz" % round(self.clock_speed / 1000, 2)
401
402 @property
403 def bogomips(self):
404 return self.__bogomips
405
406 @property
407 def capabilities(self):
408 caps = [
409 ("64bit", self.has_flag("lm")),
410 ("aes", self.has_flag("aes")),
411 ("nx", self.has_flag("nx")),
412 ("pae", self.has_flag("pae") or self.has_flag("lpae")),
413 ("rdrand", self.has_flag("rdrand")),
414 ]
415
416 # If the system is already running in a virtual environment,
417 # we cannot correctly detect if the CPU supports svm or vmx
418 if self.has_flag("hypervisor"):
419 caps.append(("virt", None))
420 else:
421 caps.append(("virt", self.has_flag("vmx") or self.has_flag("svm")))
422
423 return caps
424
425 def format_model(self):
426 s = self.model_string or ""
427
428 # Remove everything after the @: Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz
429 s, sep, rest = s.partition("@")
430
431 for pattern, repl in CPU_STRINGS:
432 if re.match(pattern, s) is None:
433 continue
434
435 s = re.sub(pattern, repl, s)
436 break
437
438 # Otherwise remove the symbols
439 for i in ("C", "R", "TM", "tm"):
440 s = s.replace("(%s)" % i, "")
441
442 # Replace too long strings with shorter ones
443 pairs = (
444 ("Quad-Core Processor", ""),
445 ("Dual-Core Processor", ""),
446 ("Processor", "CPU"),
447 ("processor", "CPU"),
448 )
449 for k, v in pairs:
450 s = s.replace(k, v)
451
452 # Remove too many spaces
453 s = " ".join((e for e in s.split() if e))
454
455 return s
456
457 @property
458 def friendly_string(self):
459 s = []
460
461 model = self.format_model()
462 if model:
463 s.append(model)
464
465 clock_speed = self.format_clock_speed()
466 if clock_speed:
467 s.append("@ %s" % clock_speed)
468
469 if self.count > 1:
470 s.append("x%s" % self.count)
471
472 return " ".join(s)
473
474
475 class Device(Object):
476 classid2name = {
477 "pci" : {
478 "00" : N_("Unclassified"),
479 "01" : N_("Mass storage"),
480 "02" : N_("Network"),
481 "03" : N_("Display"),
482 "04" : N_("Multimedia"),
483 "05" : N_("Memory controller"),
484 "06" : N_("Bridge"),
485 "07" : N_("Communication"),
486 "08" : N_("Generic system peripheral"),
487 "09" : N_("Input device"),
488 "0a" : N_("Docking station"),
489 "0b" : N_("Processor"),
490 "0c" : N_("Serial bus"),
491 "0d" : N_("Wireless"),
492 "0e" : N_("Intelligent controller"),
493 "0f" : N_("Satellite communications controller"),
494 "10" : N_("Encryption"),
495 "11" : N_("Signal processing controller"),
496 "ff" : N_("Unassigned class"),
497 },
498
499 "usb" : {
500 "00" : N_("Unclassified"),
501 "01" : N_("Multimedia"),
502 "02" : N_("Communication"),
503 "03" : N_("Input device"),
504 "05" : N_("Generic system peripheral"),
505 "06" : N_("Image"),
506 "07" : N_("Printer"),
507 "08" : N_("Mass storage"),
508 "09" : N_("Hub"),
509 "0a" : N_("Communication"),
510 "0b" : N_("Smart card"),
511 "0d" : N_("Encryption"),
512 "0e" : N_("Display"),
513 "0f" : N_("Personal Healthcare"),
514 "dc" : N_("Diagnostic Device"),
515 "e0" : N_("Wireless"),
516 "ef" : N_("Unclassified"),
517 "fe" : N_("Unclassified"),
518 "ff" : N_("Unclassified"),
519 }
520 }
521
522 def init(self, blob):
523 self.blob = blob
524
525 def __repr__(self):
526 return "<%s vendor=%s model=%s>" % (self.__class__.__name__,
527 self.vendor_string, self.model_string)
528
529 def __eq__(self, other):
530 if isinstance(other, self.__class__):
531 return self.blob == other.blob
532
533 return NotImplemented
534
535 def __lt__(self, other):
536 if isinstance(other, self.__class__):
537 return self.cls < other.cls or \
538 self.vendor_string < other.vendor_string or \
539 self.vendor < other.vendor or \
540 self.model_string < other.model_string or \
541 self.model < other.model
542
543 return NotImplemented
544
545 def is_showable(self):
546 if self.driver in ("usb", "pcieport", "hub"):
547 return False
548
549 return True
550
551 @property
552 def subsystem(self):
553 return self.blob.get("subsystem")
554
555 @property
556 def model(self):
557 return self.blob.get("model")
558
559 @lazy_property
560 def model_string(self):
561 return self.fireinfo.get_model_string(self.subsystem, self.vendor, self.model)
562
563 @property
564 def vendor(self):
565 return self.blob.get("vendor")
566
567 @lazy_property
568 def vendor_string(self):
569 return self.fireinfo.get_vendor_string(self.subsystem, self.vendor)
570
571 @property
572 def driver(self):
573 return self.blob.get("driver")
574
575 @lazy_property
576 def cls(self):
577 classid = self.blob.get("deviceclass")
578
579 if self.subsystem == "pci":
580 classid = classid[:-4]
581 if len(classid) == 1:
582 classid = "0%s" % classid
583
584 elif self.subsystem == "usb" and classid:
585 classid = classid.split("/")[0]
586 classid = "%02x" % int(classid)
587
588 try:
589 return self.classid2name[self.subsystem][classid]
590 except KeyError:
591 return "N/A"
592
593
594 class System(Object):
595 def init(self, blob):
596 self.blob = blob
597
598 @property
599 def arch(self):
600 return self.blob.get("arch")
601
602 @property
603 def language(self):
604 return self.blob.get("language")
605
606 @property
607 def vendor(self):
608 return self.blob.get("vendor")
609
610 @property
611 def model(self):
612 return self.blob.get("model")
613
614 @property
615 def release(self):
616 return self.blob.get("release")
617
618 @property
619 def storage(self):
620 return self.blob.get("storage_size", 0)
621
622 def is_virtual(self):
623 return self.blob.get("virtual", False)
624
625
626 class Hypervisor(Object):
627 def init(self, blob):
628 self.blob = blob
629
630 def __str__(self):
631 return self.vendor
632
633 @property
634 def vendor(self):
635 return self.blob.get("vendor")
636
637
638 class Profile(Object):
639 def init(self, profile_id, private_id, created_at, expired_at, version, blob,
640 last_updated_at, country_code, **kwargs):
641 self.profile_id = profile_id
642 self.private_id = private_id
643 self.created_at = created_at
644 self.expired_at = expired_at
645 self.version = version
646 self.blob = blob
647 self.last_updated_at = last_updated_at
648 self.country_code = country_code
649
650 def __repr__(self):
651 return "<%s %s>" % (self.__class__.__name__, self.profile_id)
652
653 def is_showable(self):
654 return True if self.blob else False
655
656 @property
657 def public_id(self):
658 """
659 An alias for the profile ID
660 """
661 return self.profile_id
662
663 # Location
664
665 @property
666 def location(self):
667 return self.country_code
668
669 @property
670 def location_string(self):
671 return self.backend.get_country_name(self.location) or self.location
672
673 # Devices
674
675 @lazy_property
676 def devices(self):
677 return [Device(self.backend, blob) for blob in self.blob.get("devices", [])]
678
679 # System
680
681 @lazy_property
682 def system(self):
683 return System(self.backend, self.blob.get("system", {}))
684
685 # Processor
686
687 @property
688 def processor(self):
689 return Processor(self.backend, self.blob.get("cpu", {}))
690
691 # Memory
692
693 @property
694 def memory(self):
695 return self.blob.get("memory")
696
697 @property
698 def friendly_memory(self):
699 return util.format_size(self.memory or 0)
700
701 # Virtual
702
703 def is_virtual(self):
704 return self.system.is_virtual()
705
706 @property
707 def hypervisor(self):
708 return Hypervisor(self.backend, self.blob.get("hypervisor"))
709
710 # Network
711
712 @lazy_property
713 def network(self):
714 return Network(self.backend, self.blob.get("network", {}))
715
716
717 class Fireinfo(Object):
718 async def expire(self):
719 """
720 Called to expire any profiles that have not been updated in a fortnight
721 """
722 self.db.execute("UPDATE fireinfo SET expired_at = CURRENT_TIMESTAMP \
723 WHERE last_updated_at <= CURRENT_TIMESTAMP - %s", datetime.timedelta(days=14))
724
725 def _get_profile(self, query, *args, **kwargs):
726 res = self.db.get(query, *args, **kwargs)
727
728 if res:
729 return Profile(self.backend, **res)
730
731 def get_profile_count(self, when=None):
732 if when:
733 res = self.db.get("""
734 SELECT
735 COUNT(*) AS count
736 FROM
737 fireinfo
738 WHERE
739 created_at <= %s
740 AND
741 (
742 expired_at IS NULL
743 OR
744 expired_at > %s
745 )
746 """)
747 else:
748 res = self.db.get("""
749 SELECT
750 COUNT(*) AS count
751 FROM
752 fireinfo
753 WHERE
754 expired_at IS NULL
755 """,
756 )
757
758 return res.count if res else 0
759
760 def get_profile_histogram(self):
761 today = datetime.date.today()
762
763 t1 = datetime.date(year=today.year - 10, month=today.month, day=1)
764 t2 = datetime.date(year=today.year, month=today.month, day=1)
765
766 res = self.db.query("""
767 SELECT
768 date,
769 COUNT(*) AS count
770 FROM
771 generate_series(%s, %s, INTERVAL '1 month') date
772 JOIN
773 fireinfo ON date >= created_at
774 AND (expired_at IS NULL OR expired_at > date)
775 GROUP BY
776 date
777 """, t1, t2)
778
779 return { row.date : row.count for row in res }
780
781 # Profiles
782
783 def get_profile(self, profile_id, when=None):
784 if when:
785 return self._get_profile("""
786 SELECT
787 *
788 FROM
789 fireinfo
790 WHERE
791 profile_id = %s
792 AND
793 %s BETWEEN created_at AND expired_at
794 """, profile_id,
795 )
796
797 return self._get_profile("""
798 SELECT
799 *
800 FROM
801 fireinfo
802 WHERE
803 profile_id = %s
804 AND
805 expired_at IS NULL
806 """, profile_id,
807 )
808
809 # Handle profile
810
811 def handle_profile(self, profile_id, blob, country_code=None, when=None):
812 private_id = blob.get("private_id", None)
813 assert private_id
814
815 now = datetime.datetime.utcnow()
816
817 # Fetch the profile version
818 version = blob.get("profile_version")
819
820 # Extract the profile
821 profile = blob.get("profile")
822
823 # Validate the profile
824 self._validate(profile_id, version, profile)
825
826 # Pre-process the profile
827 profile = self._preprocess(profile)
828
829 # Fetch the previous profile
830 prev = self.get_profile(profile_id)
831
832 if prev:
833 # Check if the private ID matches
834 if not prev.private_id == private_id:
835 logging.error("Private ID for profile %s does not match" % profile_id)
836 return False
837
838 # Check when the last update was
839 elif now - prev.last_updated_at < datetime.timedelta(hours=6):
840 logging.warning("Profile %s has been updated too soon" % profile_id)
841 return False
842
843 # Check if the profile has changed
844 elif prev.version == version and prev.blob == blob:
845 logging.debug("Profile %s has not changed" % profile_id)
846
847 # Update the timestamp
848 self.db.execute("UPDATE fireinfo SET last_updated_at = CURRENT_TIMESTAMP \
849 WHERE profile_id = %s AND expired_at IS NULL", profile_id)
850
851 return True
852
853 # Delete the previous profile
854 self.db.execute("UPDATE fireinfo SET expired_at = CURRENT_TIMESTAMP \
855 WHERE profile_id = %s AND expired_at IS NULL", profile_id)
856
857 # Store the new profile
858 self.db.execute("""
859 INSERT INTO
860 fireinfo
861 (
862 profile_id,
863 private_id,
864 version,
865 blob,
866 country_code
867 )
868 VALUES
869 (
870 %s,
871 %s,
872 %s,
873 %s,
874 %s
875 )
876 """, profile_id, private_id, version, json.dumps(profile), country_code,
877 )
878
879 def _validate(self, profile_id, version, blob):
880 """
881 Validate the profile
882 """
883 if not version == 0:
884 raise ValueError("Unsupported profile version")
885
886 # Validate the blob
887 try:
888 return jsonschema.validate(blob, schema=PROFILE_SCHEMA)
889
890 # Raise a ValueError instead which is easier to handle later on
891 except jsonschema.exceptions.ValidationError as e:
892 raise ValueError("%s" % e) from e
893
894 def _preprocess(self, blob):
895 """
896 Modifies the profile before storing it
897 """
898 # Remove the architecture from the release string
899 blob["system"]["release"]= self._filter_release(blob["system"]["release"])
900
901 return blob
902
903 def _filter_release(self, release):
904 """
905 Removes the arch part
906 """
907 r = [e for e in release.split() if e]
908
909 for s in ("(x86_64)", "(aarch64)", "(i586)", "(armv6l)", "(armv5tel)", "(riscv64)"):
910 try:
911 r.remove(s)
912 break
913 except ValueError:
914 pass
915
916 return " ".join(r)
917
918 # Data outputs
919
920 def get_random_profile(self, when=None):
921 if when:
922 return self._get_profile("""
923 SELECT
924 *
925 FROM
926 fireinfo
927 WHERE
928 created_at <= %s
929 AND
930 (
931 expired_at IS NULL
932 OR
933 expired_at > %s
934 )
935 ORDER BY
936 RANDOM()
937 LIMIT
938 1
939 """, when, when,
940 )
941
942 return self._get_profile("""
943 SELECT
944 *
945 FROM
946 fireinfo
947 WHERE
948 expired_at IS NULL
949 ORDER BY
950 RANDOM()
951 LIMIT
952 1
953 """)
954
955 def get_active_profiles(self, when=None):
956 if when:
957 raise NotImplementedError
958
959 else:
960 res = self.db.get("""
961 SELECT
962 COUNT(*) AS total_profiles,
963 COUNT(*) FILTER (WHERE blob IS NOT NULL) AS active_profiles
964 FROM
965 fireinfo
966 WHERE
967 expired_at IS NULL
968 """)
969
970 if res:
971 return res.active_profiles, res.total_profiles
972
973 def get_geo_location_map(self, when=None):
974 if when:
975 res = self.db.query("""
976 SELECT
977 country_code,
978 fireinfo_percentage(
979 COUNT(*), SUM(COUNT(*)) OVER ()
980 ) AS p
981 FROM
982 fireinfo
983 WHERE
984 created_at <= %s
985 AND
986 (
987 expired_at IS NULL
988 OR
989 expired_at > %s
990 )
991 AND
992 country_code IS NOT NULL
993 GROUP BY
994 country_code
995 """, when, when)
996 else:
997 res = self.db.query("""
998 SELECT
999 country_code,
1000 fireinfo_percentage(
1001 COUNT(*), SUM(COUNT(*)) OVER ()
1002 ) AS p
1003 FROM
1004 fireinfo
1005 WHERE
1006 expired_at IS NULL
1007 AND
1008 country_code IS NOT NULL
1009 GROUP BY
1010 country_code
1011 """)
1012
1013 return { row.country_code : row.p for row in res }
1014
1015 @property
1016 def cpu_vendors(self):
1017 res = self.db.query("""
1018 SELECT DISTINCT
1019 blob->'cpu'->'vendor' AS vendor
1020 FROM
1021 fireinfo
1022 WHERE
1023 blob->'cpu'->'vendor' IS NOT NULL
1024 """,
1025 )
1026
1027 return sorted((CPU_VENDORS.get(row.vendor, row.vendor) for row in res))
1028
1029 def get_cpu_vendors_map(self, when=None):
1030 if when:
1031 raise NotImplementedError
1032
1033 else:
1034 res = self.db.query("""
1035 SELECT
1036 blob->'cpu'->'vendor' AS vendor,
1037 fireinfo_percentage(
1038 COUNT(*), SUM(COUNT(*)) OVER ()
1039 ) AS p
1040 FROM
1041 fireinfo
1042 WHERE
1043 expired_at IS NULL
1044 AND
1045 blob IS NOT NULL
1046 AND
1047 blob->'cpu'->'vendor' IS NOT NULL
1048 GROUP BY
1049 blob->'cpu'->'vendor'
1050 """)
1051
1052 return { CPU_VENDORS.get(row.vendor, row.vendor) : row.p for row in res }
1053
1054 def get_cpu_flags_map(self, when=None):
1055 if when:
1056 raise NotImplementedError
1057
1058 else:
1059 res = self.db.query("""
1060 WITH arch_flags AS (
1061 SELECT
1062 ROW_NUMBER() OVER (PARTITION BY blob->'cpu'->'arch') AS id,
1063 blob->'cpu'->'arch' AS arch,
1064 blob->'cpu'->'flags' AS flags
1065 FROM
1066 fireinfo
1067 WHERE
1068 expired_at IS NULL
1069 AND
1070 blob->'cpu'->'arch' IS NOT NULL
1071 AND
1072 blob->'cpu'->'flags' IS NOT NULL
1073
1074 -- Filter out virtual systems
1075 AND
1076 CAST((blob->'system'->'virtual') AS boolean) IS FALSE
1077 )
1078
1079 SELECT
1080 arch,
1081 flag,
1082 fireinfo_percentage(
1083 COUNT(*),
1084 (
1085 SELECT
1086 MAX(id)
1087 FROM
1088 arch_flags __arch_flags
1089 WHERE
1090 arch_flags.arch = __arch_flags.arch
1091 )
1092 ) AS p
1093 FROM
1094 arch_flags, jsonb_array_elements(arch_flags.flags) AS flag
1095 GROUP BY
1096 arch, flag
1097 """)
1098
1099 result = {}
1100
1101 for row in res:
1102 try:
1103 result[row.arch][row.flag] = row.p
1104 except KeyError:
1105 result[row.arch] = { row.flag : row.p }
1106
1107 return result
1108
1109 def get_average_memory_amount(self, when=None):
1110 if when:
1111 res = self.db.get("""
1112 SELECT
1113 AVG(
1114 CAST(blob->'system'->'memory' AS numeric)
1115 ) AS memory
1116 FROM
1117 fireinfo
1118 WHERE
1119 created_at <= %s
1120 AND
1121 (
1122 expired_at IS NULL
1123 OR
1124 expired_at > %s
1125 )
1126 """, when)
1127 else:
1128 res = self.db.get("""
1129 SELECT
1130 AVG(
1131 CAST(blob->'system'->'memory' AS numeric)
1132 ) AS memory
1133 FROM
1134 fireinfo
1135 WHERE
1136 expired_at IS NULL
1137 """,)
1138
1139 return res.memory if res else 0
1140
1141 def get_arch_map(self, when=None):
1142 if when:
1143 raise NotImplementedError
1144
1145 else:
1146 res = self.db.query("""
1147 SELECT
1148 blob->'cpu'->'arch' AS arch,
1149 fireinfo_percentage(
1150 COUNT(*), SUM(COUNT(*)) OVER ()
1151 ) AS p
1152 FROM
1153 fireinfo
1154 WHERE
1155 expired_at IS NULL
1156 AND
1157 blob->'cpu'->'arch' IS NOT NULL
1158 GROUP BY
1159 blob->'cpu'->'arch'
1160 """)
1161
1162 return { row.arch : row.p for row in res }
1163
1164 # Virtual
1165
1166 def get_hypervisor_map(self, when=None):
1167 if when:
1168 raise NotImplementedError
1169 else:
1170 res = self.db.query("""
1171 SELECT
1172 blob->'hypervisor'->'vendor' AS vendor,
1173 fireinfo_percentage(
1174 COUNT(*), SUM(COUNT(*)) OVER ()
1175 ) AS p
1176 FROM
1177 fireinfo
1178 WHERE
1179 expired_at IS NULL
1180 AND
1181 CAST((blob->'system'->'virtual') AS boolean) IS TRUE
1182 AND
1183 blob->'hypervisor'->'vendor' IS NOT NULL
1184 GROUP BY
1185 blob->'hypervisor'->'vendor'
1186 """)
1187
1188 return { row.vendor : row.p for row in res }
1189
1190 def get_virtual_ratio(self, when=None):
1191 if when:
1192 raise NotImplementedError
1193
1194 else:
1195 res = self.db.get("""
1196 SELECT
1197 fireinfo_percentage(
1198 COUNT(*) FILTER (
1199 WHERE CAST((blob->'system'->'virtual') AS boolean) IS TRUE
1200 ),
1201 COUNT(*)
1202 ) AS p
1203 FROM
1204 fireinfo
1205 WHERE
1206 expired_at IS NULL
1207 AND
1208 blob IS NOT NULL
1209 """)
1210
1211 return res.p if res else 0
1212
1213 # Releases
1214
1215 def get_releases_map(self, when=None):
1216 if when:
1217 raise NotImplementedError
1218
1219 else:
1220 res = self.db.query("""
1221 SELECT
1222 blob->'system'->'release' AS release,
1223 fireinfo_percentage(
1224 COUNT(*), SUM(COUNT(*)) OVER ()
1225 ) AS p
1226 FROM
1227 fireinfo
1228 WHERE
1229 expired_at IS NULL
1230 AND
1231 blob IS NOT NULL
1232 AND
1233 blob->'system'->'release' IS NOT NULL
1234 GROUP BY
1235 blob->'system'->'release'
1236 """)
1237
1238 return { row.release : row.p for row in res }
1239
1240 # Kernels
1241
1242 def get_kernels_map(self, when=None):
1243 if when:
1244 raise NotImplementedError
1245
1246 else:
1247 res = self.db.query("""
1248 SELECT
1249 blob->'system'->'kernel' AS kernel,
1250 fireinfo_percentage(
1251 COUNT(*), SUM(COUNT(*)) OVER ()
1252 ) AS p
1253 FROM
1254 fireinfo
1255 WHERE
1256 expired_at IS NULL
1257 AND
1258 blob IS NOT NULL
1259 AND
1260 blob->'system'->'kernel' IS NOT NULL
1261 GROUP BY
1262 blob->'system'->'kernel'
1263 """)
1264
1265 return { row.kernel : row.p for row in res }
1266
1267 subsystem2class = {
1268 "pci" : hwdata.PCI(),
1269 "usb" : hwdata.USB(),
1270 }
1271
1272 def get_vendor_string(self, subsystem, vendor_id):
1273 try:
1274 cls = self.subsystem2class[subsystem]
1275 except KeyError:
1276 return ""
1277
1278 return cls.get_vendor(vendor_id) or ""
1279
1280 def get_model_string(self, subsystem, vendor_id, model_id):
1281 try:
1282 cls = self.subsystem2class[subsystem]
1283 except KeyError:
1284 return ""
1285
1286 return cls.get_device(vendor_id, model_id) or ""
1287
1288 def get_vendor_list(self, when=None):
1289 if when:
1290 raise NotImplementedError
1291
1292 else:
1293 res = self.db.query("""
1294 WITH devices AS (
1295 SELECT
1296 jsonb_array_elements(blob->'devices') AS device
1297 FROM
1298 fireinfo
1299 WHERE
1300 expired_at IS NULL
1301 AND
1302 blob IS NOT NULL
1303 AND
1304 blob->'devices' IS NOT NULL
1305 AND
1306 jsonb_typeof(blob->'devices') = 'array'
1307 )
1308
1309 SELECT
1310 devices.device->'subsystem' AS subsystem,
1311 devices.device->'vendor' AS vendor
1312 FROM
1313 devices
1314 WHERE
1315 devices.device->'subsystem' IS NOT NULL
1316 AND
1317 devices.device->'vendor' IS NOT NULL
1318 AND
1319 NOT devices.device->>'driver' = 'usb'
1320 GROUP BY
1321 subsystem, vendor
1322 """)
1323
1324 vendors = {}
1325
1326 for row in res:
1327 vendor = self.get_vendor_string(row.subsystem, row.vendor) or row.vendor
1328
1329 # Drop if vendor could not be determined
1330 if vendor is None:
1331 continue
1332
1333 try:
1334 vendors[vendor].append((row.subsystem, row.vendor))
1335 except KeyError:
1336 vendors[vendor] = [(row.subsystem, row.vendor)]
1337
1338 return vendors
1339
1340 def _get_devices(self, query, *args, **kwargs):
1341 res = self.db.query(query, *args, **kwargs)
1342
1343 return [Device(self.backend, blob) for blob in res]
1344
1345 def get_devices_by_vendor(self, subsystem, vendor, when=None):
1346 if when:
1347 raise NotImplementedError
1348
1349 else:
1350 return self._get_devices("""
1351 WITH devices AS (
1352 SELECT
1353 jsonb_array_elements(blob->'devices') AS device
1354 FROM
1355 fireinfo
1356 WHERE
1357 expired_at IS NULL
1358 AND
1359 blob IS NOT NULL
1360 AND
1361 blob->'devices' IS NOT NULL
1362 AND
1363 jsonb_typeof(blob->'devices') = 'array'
1364 )
1365
1366 SELECT
1367 device.deviceclass,
1368 device.subsystem,
1369 device.vendor,
1370 device.model,
1371 device.driver
1372 FROM
1373 devices,
1374 jsonb_to_record(devices.device) AS device(
1375 deviceclass text,
1376 subsystem text,
1377 vendor text,
1378 sub_vendor text,
1379 model text,
1380 sub_model text,
1381 driver text
1382 )
1383 WHERE
1384 devices.device->>'subsystem' = %s
1385 AND
1386 devices.device->>'vendor' = %s
1387 AND
1388 NOT devices.device->>'driver' = 'usb'
1389 GROUP BY
1390 device.deviceclass,
1391 device.subsystem,
1392 device.vendor,
1393 device.model,
1394 device.driver
1395 """, subsystem, vendor,
1396 )
1397
1398 def get_devices_by_driver(self, driver, when=None):
1399 if when:
1400 raise NotImplementedError
1401
1402 else:
1403 return self._get_devices("""
1404 WITH devices AS (
1405 SELECT
1406 jsonb_array_elements(blob->'devices') AS device
1407 FROM
1408 fireinfo
1409 WHERE
1410 expired_at IS NULL
1411 AND
1412 blob IS NOT NULL
1413 AND
1414 blob->'devices' IS NOT NULL
1415 AND
1416 jsonb_typeof(blob->'devices') = 'array'
1417 )
1418
1419 SELECT
1420 device.deviceclass,
1421 device.subsystem,
1422 device.vendor,
1423 device.model,
1424 device.driver
1425 FROM
1426 devices,
1427 jsonb_to_record(devices.device) AS device(
1428 deviceclass text,
1429 subsystem text,
1430 vendor text,
1431 sub_vendor text,
1432 model text,
1433 sub_model text,
1434 driver text
1435 )
1436 WHERE
1437 devices.device->>'driver' = '%s'
1438 GROUP BY
1439 device.deviceclass,
1440 device.subsystem,
1441 device.vendor,
1442 device.model,
1443 device.driver
1444 """, driver,
1445 )