]> git.ipfire.org Git - ipfire.org.git/blob - src/backend/fireinfo.py
fireinfo: Store empty profiles as NULL instead of serialised JSON
[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", "null"],
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", "null"],
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}(\.utf8)?$",
224 },
225 "memory" : {
226 "type" : "integer",
227 },
228 "model" : {
229 "type" : ["string", "null"],
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 arch(self):
342 return self.blob.get("arch")
343
344 @property
345 def vendor(self):
346 vendor = self.blob.get("vendor")
347
348 try:
349 return CPU_VENDORS[vendor]
350 except KeyError:
351 return vendor
352
353 @property
354 def family(self):
355 return self.blob.get("family")
356
357 @property
358 def model(self):
359 return self.blob.get("model")
360
361 @property
362 def stepping(self):
363 return self.blob.get("stepping")
364
365 @property
366 def model_string(self):
367 return self.blob.get("model_string")
368
369 @property
370 def flags(self):
371 return self.blob.get("flags")
372
373 def has_flag(self, flag):
374 return flag in self.flags
375
376 def uses_ht(self):
377 if self.vendor == "Intel" and self.family == 6 and self.model in (15, 55, 76, 77):
378 return False
379
380 return self.has_flag("ht")
381
382 @property
383 def core_count(self):
384 return self.blob.get("count", 1)
385
386 @property
387 def count(self):
388 if self.uses_ht():
389 return self.core_count // 2
390
391 return self.core_count
392
393 @property
394 def clock_speed(self):
395 return self.blob.get("speed", 0)
396
397 def format_clock_speed(self):
398 if not self.clock_speed:
399 return
400
401 if self.clock_speed < 1000:
402 return "%dMHz" % self.clock_speed
403
404 return "%.2fGHz" % round(self.clock_speed / 1000, 2)
405
406 @property
407 def bogomips(self):
408 return self.__bogomips
409
410 @property
411 def capabilities(self):
412 caps = [
413 ("64bit", self.has_flag("lm")),
414 ("aes", self.has_flag("aes")),
415 ("nx", self.has_flag("nx")),
416 ("pae", self.has_flag("pae") or self.has_flag("lpae")),
417 ("rdrand", self.has_flag("rdrand")),
418 ]
419
420 # If the system is already running in a virtual environment,
421 # we cannot correctly detect if the CPU supports svm or vmx
422 if self.has_flag("hypervisor"):
423 caps.append(("virt", None))
424 else:
425 caps.append(("virt", self.has_flag("vmx") or self.has_flag("svm")))
426
427 return caps
428
429 def format_model(self):
430 s = self.model_string or ""
431
432 # Remove everything after the @: Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz
433 s, sep, rest = s.partition("@")
434
435 for pattern, repl in CPU_STRINGS:
436 if re.match(pattern, s) is None:
437 continue
438
439 s = re.sub(pattern, repl, s)
440 break
441
442 # Otherwise remove the symbols
443 for i in ("C", "R", "TM", "tm"):
444 s = s.replace("(%s)" % i, "")
445
446 # Replace too long strings with shorter ones
447 pairs = (
448 ("Quad-Core Processor", ""),
449 ("Dual-Core Processor", ""),
450 ("Processor", "CPU"),
451 ("processor", "CPU"),
452 )
453 for k, v in pairs:
454 s = s.replace(k, v)
455
456 # Remove too many spaces
457 s = " ".join((e for e in s.split() if e))
458
459 return s
460
461 @property
462 def friendly_string(self):
463 s = []
464
465 model = self.format_model()
466 if model:
467 s.append(model)
468
469 clock_speed = self.format_clock_speed()
470 if clock_speed:
471 s.append("@ %s" % clock_speed)
472
473 if self.count > 1:
474 s.append("x%s" % self.count)
475
476 return " ".join(s)
477
478
479 class Device(Object):
480 classid2name = {
481 "pci" : {
482 "00" : N_("Unclassified"),
483 "01" : N_("Mass storage"),
484 "02" : N_("Network"),
485 "03" : N_("Display"),
486 "04" : N_("Multimedia"),
487 "05" : N_("Memory controller"),
488 "06" : N_("Bridge"),
489 "07" : N_("Communication"),
490 "08" : N_("Generic system peripheral"),
491 "09" : N_("Input device"),
492 "0a" : N_("Docking station"),
493 "0b" : N_("Processor"),
494 "0c" : N_("Serial bus"),
495 "0d" : N_("Wireless"),
496 "0e" : N_("Intelligent controller"),
497 "0f" : N_("Satellite communications controller"),
498 "10" : N_("Encryption"),
499 "11" : N_("Signal processing controller"),
500 "ff" : N_("Unassigned class"),
501 },
502
503 "usb" : {
504 "00" : N_("Unclassified"),
505 "01" : N_("Multimedia"),
506 "02" : N_("Communication"),
507 "03" : N_("Input device"),
508 "05" : N_("Generic system peripheral"),
509 "06" : N_("Image"),
510 "07" : N_("Printer"),
511 "08" : N_("Mass storage"),
512 "09" : N_("Hub"),
513 "0a" : N_("Communication"),
514 "0b" : N_("Smart card"),
515 "0d" : N_("Encryption"),
516 "0e" : N_("Display"),
517 "0f" : N_("Personal Healthcare"),
518 "dc" : N_("Diagnostic Device"),
519 "e0" : N_("Wireless"),
520 "ef" : N_("Unclassified"),
521 "fe" : N_("Unclassified"),
522 "ff" : N_("Unclassified"),
523 }
524 }
525
526 def init(self, blob):
527 self.blob = blob
528
529 def __repr__(self):
530 return "<%s vendor=%s model=%s>" % (self.__class__.__name__,
531 self.vendor_string, self.model_string)
532
533 def __eq__(self, other):
534 if isinstance(other, self.__class__):
535 return self.blob == other.blob
536
537 return NotImplemented
538
539 def __lt__(self, other):
540 if isinstance(other, self.__class__):
541 return self.cls < other.cls or \
542 self.vendor_string < other.vendor_string or \
543 self.vendor < other.vendor or \
544 self.model_string < other.model_string or \
545 self.model < other.model
546
547 return NotImplemented
548
549 def is_showable(self):
550 if self.driver in ("usb", "pcieport", "hub"):
551 return False
552
553 return True
554
555 @property
556 def subsystem(self):
557 return self.blob.get("subsystem")
558
559 @property
560 def model(self):
561 return self.blob.get("model")
562
563 @lazy_property
564 def model_string(self):
565 return self.fireinfo.get_model_string(self.subsystem, self.vendor, self.model)
566
567 @property
568 def vendor(self):
569 return self.blob.get("vendor")
570
571 @lazy_property
572 def vendor_string(self):
573 return self.fireinfo.get_vendor_string(self.subsystem, self.vendor)
574
575 @property
576 def driver(self):
577 return self.blob.get("driver")
578
579 @lazy_property
580 def cls(self):
581 classid = self.blob.get("deviceclass")
582
583 if self.subsystem == "pci":
584 classid = classid[:-4]
585 if len(classid) == 1:
586 classid = "0%s" % classid
587
588 elif self.subsystem == "usb" and classid:
589 classid = classid.split("/")[0]
590 classid = "%02x" % int(classid)
591
592 try:
593 return self.classid2name[self.subsystem][classid]
594 except KeyError:
595 return "N/A"
596
597
598 class System(Object):
599 def init(self, blob):
600 self.blob = blob
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, asn=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 if profile:
824 # Validate the profile
825 self._validate(profile_id, version, profile)
826
827 # Pre-process the profile
828 profile = self._preprocess(profile)
829
830 # Fetch the previous profile
831 prev = self.get_profile(profile_id)
832
833 if prev:
834 # Check if the private ID matches
835 if not prev.private_id == private_id:
836 logging.error("Private ID for profile %s does not match" % profile_id)
837 return False
838
839 # Check when the last update was
840 elif now - prev.last_updated_at < datetime.timedelta(hours=6):
841 logging.warning("Profile %s has been updated too soon" % profile_id)
842 return False
843
844 # Check if the profile has changed
845 elif prev.version == version and prev.blob == blob:
846 logging.debug("Profile %s has not changed" % profile_id)
847
848 # Update the timestamp
849 self.db.execute("UPDATE fireinfo SET last_updated_at = CURRENT_TIMESTAMP \
850 WHERE profile_id = %s AND expired_at IS NULL", profile_id)
851
852 return True
853
854 # Delete the previous profile
855 self.db.execute("UPDATE fireinfo SET expired_at = CURRENT_TIMESTAMP \
856 WHERE profile_id = %s AND expired_at IS NULL", profile_id)
857
858 # Serialise the profile
859 if profile:
860 profile = json.dumps(profile)
861
862 # Store the new profile
863 self.db.execute("""
864 INSERT INTO
865 fireinfo
866 (
867 profile_id,
868 private_id,
869 version,
870 blob,
871 country_code,
872 asn
873 )
874 VALUES
875 (
876 %s,
877 %s,
878 %s,
879 %s,
880 %s,
881 %s
882 )
883 """, profile_id, private_id, version, profile, country_code, asn,
884 )
885
886 def _validate(self, profile_id, version, blob):
887 """
888 Validate the profile
889 """
890 if not version == 0:
891 raise ValueError("Unsupported profile version")
892
893 # Validate the blob
894 try:
895 return jsonschema.validate(blob, schema=PROFILE_SCHEMA)
896
897 # Raise a ValueError instead which is easier to handle later on
898 except jsonschema.exceptions.ValidationError as e:
899 raise ValueError("%s" % e) from e
900
901 def _preprocess(self, blob):
902 """
903 Modifies the profile before storing it
904 """
905 # Remove the architecture from the release string
906 blob["system"]["release"]= self._filter_release(blob["system"]["release"])
907
908 return blob
909
910 def _filter_release(self, release):
911 """
912 Removes the arch part
913 """
914 r = [e for e in release.split() if e]
915
916 for s in ("(x86_64)", "(aarch64)", "(i586)", "(armv6l)", "(armv5tel)", "(riscv64)"):
917 try:
918 r.remove(s)
919 break
920 except ValueError:
921 pass
922
923 return " ".join(r)
924
925 # Data outputs
926
927 def get_random_profile(self, when=None):
928 if when:
929 return self._get_profile("""
930 SELECT
931 *
932 FROM
933 fireinfo
934 WHERE
935 created_at <= %s
936 AND
937 (
938 expired_at IS NULL
939 OR
940 expired_at > %s
941 )
942 ORDER BY
943 RANDOM()
944 LIMIT
945 1
946 """, when, when,
947 )
948
949 return self._get_profile("""
950 SELECT
951 *
952 FROM
953 fireinfo
954 WHERE
955 expired_at IS NULL
956 ORDER BY
957 RANDOM()
958 LIMIT
959 1
960 """)
961
962 def get_active_profiles(self, when=None):
963 if when:
964 raise NotImplementedError
965
966 else:
967 res = self.db.get("""
968 SELECT
969 COUNT(*) AS total_profiles,
970 COUNT(*) FILTER (WHERE blob IS NOT NULL) AS active_profiles
971 FROM
972 fireinfo
973 WHERE
974 expired_at IS NULL
975 """)
976
977 if res:
978 return res.active_profiles, res.total_profiles
979
980 def get_geo_location_map(self, when=None):
981 if when:
982 res = self.db.query("""
983 SELECT
984 country_code,
985 fireinfo_percentage(
986 COUNT(*), SUM(COUNT(*)) OVER ()
987 ) AS p
988 FROM
989 fireinfo
990 WHERE
991 created_at <= %s
992 AND
993 (
994 expired_at IS NULL
995 OR
996 expired_at > %s
997 )
998 AND
999 country_code IS NOT NULL
1000 GROUP BY
1001 country_code
1002 """, when, when)
1003 else:
1004 res = self.db.query("""
1005 SELECT
1006 country_code,
1007 fireinfo_percentage(
1008 COUNT(*), SUM(COUNT(*)) OVER ()
1009 ) AS p
1010 FROM
1011 fireinfo
1012 WHERE
1013 expired_at IS NULL
1014 AND
1015 country_code IS NOT NULL
1016 GROUP BY
1017 country_code
1018 """)
1019
1020 return { row.country_code : row.p for row in res }
1021
1022 def get_asn_map(self, when=None):
1023 if when:
1024 res = self.db.query("""
1025 SELECT
1026 asn,
1027 fireinfo_percentage(
1028 COUNT(*), SUM(COUNT(*)) OVER ()
1029 ) AS p,
1030 COUNT(*) AS c
1031 FROM
1032 fireinfo
1033 WHERE
1034 created_at <= %s
1035 AND
1036 (
1037 expired_at IS NULL
1038 OR
1039 expired_at > %s
1040 )
1041 AND
1042 asn IS NOT NULL
1043 GROUP BY
1044 asn
1045 """, when, when)
1046 else:
1047 res = self.db.query("""
1048 SELECT
1049 asn,
1050 fireinfo_percentage(
1051 COUNT(*), SUM(COUNT(*)) OVER ()
1052 ) AS p,
1053 COUNT(*) AS c
1054 FROM
1055 fireinfo
1056 WHERE
1057 expired_at IS NULL
1058 AND
1059 asn IS NOT NULL
1060 GROUP BY
1061 asn
1062 """)
1063
1064 return { self.backend.location.get_as(row.asn) : (row.c, row.p) for row in res }
1065
1066 @property
1067 def cpu_vendors(self):
1068 res = self.db.query("""
1069 SELECT DISTINCT
1070 blob->'cpu'->'vendor' AS vendor
1071 FROM
1072 fireinfo
1073 WHERE
1074 blob->'cpu'->'vendor' IS NOT NULL
1075 """,
1076 )
1077
1078 return sorted((CPU_VENDORS.get(row.vendor, row.vendor) for row in res))
1079
1080 def get_cpu_vendors_map(self, when=None):
1081 if when:
1082 raise NotImplementedError
1083
1084 else:
1085 res = self.db.query("""
1086 SELECT
1087 blob->'cpu'->'vendor' AS vendor,
1088 fireinfo_percentage(
1089 COUNT(*), SUM(COUNT(*)) OVER ()
1090 ) AS p
1091 FROM
1092 fireinfo
1093 WHERE
1094 expired_at IS NULL
1095 AND
1096 blob IS NOT NULL
1097 AND
1098 blob->'cpu'->'vendor' IS NOT NULL
1099 GROUP BY
1100 blob->'cpu'->'vendor'
1101 """)
1102
1103 return { CPU_VENDORS.get(row.vendor, row.vendor) : row.p for row in res }
1104
1105 def get_cpu_flags_map(self, when=None):
1106 if when:
1107 raise NotImplementedError
1108
1109 else:
1110 res = self.db.query("""
1111 WITH arch_flags AS (
1112 SELECT
1113 ROW_NUMBER() OVER (PARTITION BY blob->'cpu'->'arch') AS id,
1114 blob->'cpu'->'arch' AS arch,
1115 blob->'cpu'->'flags' AS flags
1116 FROM
1117 fireinfo
1118 WHERE
1119 expired_at IS NULL
1120 AND
1121 blob->'cpu'->'arch' IS NOT NULL
1122 AND
1123 blob->'cpu'->'flags' IS NOT NULL
1124
1125 -- Filter out virtual systems
1126 AND
1127 CAST((blob->'system'->'virtual') AS boolean) IS FALSE
1128 )
1129
1130 SELECT
1131 arch,
1132 flag,
1133 fireinfo_percentage(
1134 COUNT(*),
1135 (
1136 SELECT
1137 MAX(id)
1138 FROM
1139 arch_flags __arch_flags
1140 WHERE
1141 arch_flags.arch = __arch_flags.arch
1142 )
1143 ) AS p
1144 FROM
1145 arch_flags, jsonb_array_elements(arch_flags.flags) AS flag
1146 GROUP BY
1147 arch, flag
1148 """)
1149
1150 result = {}
1151
1152 for row in res:
1153 try:
1154 result[row.arch][row.flag] = row.p
1155 except KeyError:
1156 result[row.arch] = { row.flag : row.p }
1157
1158 return result
1159
1160 def get_average_memory_amount(self, when=None):
1161 if when:
1162 res = self.db.get("""
1163 SELECT
1164 AVG(
1165 CAST(blob->'system'->'memory' AS numeric)
1166 ) AS memory
1167 FROM
1168 fireinfo
1169 WHERE
1170 created_at <= %s
1171 AND
1172 (
1173 expired_at IS NULL
1174 OR
1175 expired_at > %s
1176 )
1177 """, when)
1178 else:
1179 res = self.db.get("""
1180 SELECT
1181 AVG(
1182 CAST(blob->'system'->'memory' AS numeric)
1183 ) AS memory
1184 FROM
1185 fireinfo
1186 WHERE
1187 expired_at IS NULL
1188 """,)
1189
1190 return res.memory if res else 0
1191
1192 def get_arch_map(self, when=None):
1193 if when:
1194 raise NotImplementedError
1195
1196 else:
1197 res = self.db.query("""
1198 SELECT
1199 blob->'cpu'->'arch' AS arch,
1200 fireinfo_percentage(
1201 COUNT(*), SUM(COUNT(*)) OVER ()
1202 ) AS p
1203 FROM
1204 fireinfo
1205 WHERE
1206 expired_at IS NULL
1207 AND
1208 blob->'cpu'->'arch' IS NOT NULL
1209 GROUP BY
1210 blob->'cpu'->'arch'
1211 """)
1212
1213 return { row.arch : row.p for row in res }
1214
1215 # Virtual
1216
1217 def get_hypervisor_map(self, when=None):
1218 if when:
1219 raise NotImplementedError
1220 else:
1221 res = self.db.query("""
1222 SELECT
1223 blob->'hypervisor'->'vendor' AS vendor,
1224 fireinfo_percentage(
1225 COUNT(*), SUM(COUNT(*)) OVER ()
1226 ) AS p
1227 FROM
1228 fireinfo
1229 WHERE
1230 expired_at IS NULL
1231 AND
1232 CAST((blob->'system'->'virtual') AS boolean) IS TRUE
1233 AND
1234 blob->'hypervisor'->'vendor' IS NOT NULL
1235 GROUP BY
1236 blob->'hypervisor'->'vendor'
1237 """)
1238
1239 return { row.vendor : row.p for row in res }
1240
1241 def get_virtual_ratio(self, when=None):
1242 if when:
1243 raise NotImplementedError
1244
1245 else:
1246 res = self.db.get("""
1247 SELECT
1248 fireinfo_percentage(
1249 COUNT(*) FILTER (
1250 WHERE CAST((blob->'system'->'virtual') AS boolean) IS TRUE
1251 ),
1252 COUNT(*)
1253 ) AS p
1254 FROM
1255 fireinfo
1256 WHERE
1257 expired_at IS NULL
1258 AND
1259 blob IS NOT NULL
1260 """)
1261
1262 return res.p if res else 0
1263
1264 # Releases
1265
1266 def get_releases_map(self, when=None):
1267 if when:
1268 raise NotImplementedError
1269
1270 else:
1271 res = self.db.query("""
1272 SELECT
1273 blob->'system'->'release' AS release,
1274 fireinfo_percentage(
1275 COUNT(*), SUM(COUNT(*)) OVER ()
1276 ) AS p
1277 FROM
1278 fireinfo
1279 WHERE
1280 expired_at IS NULL
1281 AND
1282 blob IS NOT NULL
1283 AND
1284 blob->'system'->'release' IS NOT NULL
1285 GROUP BY
1286 blob->'system'->'release'
1287 """)
1288
1289 return { row.release : row.p for row in res }
1290
1291 # Kernels
1292
1293 def get_kernels_map(self, when=None):
1294 if when:
1295 raise NotImplementedError
1296
1297 else:
1298 res = self.db.query("""
1299 SELECT
1300 blob->'system'->'kernel' AS kernel,
1301 fireinfo_percentage(
1302 COUNT(*), SUM(COUNT(*)) OVER ()
1303 ) AS p
1304 FROM
1305 fireinfo
1306 WHERE
1307 expired_at IS NULL
1308 AND
1309 blob IS NOT NULL
1310 AND
1311 blob->'system'->'kernel' IS NOT NULL
1312 GROUP BY
1313 blob->'system'->'kernel'
1314 """)
1315
1316 return { row.kernel : row.p for row in res }
1317
1318 subsystem2class = {
1319 "pci" : hwdata.PCI(),
1320 "usb" : hwdata.USB(),
1321 }
1322
1323 def get_vendor_string(self, subsystem, vendor_id):
1324 try:
1325 cls = self.subsystem2class[subsystem]
1326 except KeyError:
1327 return ""
1328
1329 return cls.get_vendor(vendor_id) or ""
1330
1331 def get_model_string(self, subsystem, vendor_id, model_id):
1332 try:
1333 cls = self.subsystem2class[subsystem]
1334 except KeyError:
1335 return ""
1336
1337 return cls.get_device(vendor_id, model_id) or ""
1338
1339 def get_vendor_list(self, when=None):
1340 if when:
1341 raise NotImplementedError
1342
1343 else:
1344 res = self.db.query("""
1345 WITH devices AS (
1346 SELECT
1347 jsonb_array_elements(blob->'devices') AS device
1348 FROM
1349 fireinfo
1350 WHERE
1351 expired_at IS NULL
1352 AND
1353 blob IS NOT NULL
1354 AND
1355 blob->'devices' IS NOT NULL
1356 AND
1357 jsonb_typeof(blob->'devices') = 'array'
1358 )
1359
1360 SELECT
1361 devices.device->'subsystem' AS subsystem,
1362 devices.device->'vendor' AS vendor
1363 FROM
1364 devices
1365 WHERE
1366 devices.device->'subsystem' IS NOT NULL
1367 AND
1368 devices.device->'vendor' IS NOT NULL
1369 AND
1370 NOT devices.device->>'driver' = 'usb'
1371 GROUP BY
1372 subsystem, vendor
1373 """)
1374
1375 vendors = {}
1376
1377 for row in res:
1378 vendor = self.get_vendor_string(row.subsystem, row.vendor) or row.vendor
1379
1380 # Drop if vendor could not be determined
1381 if vendor is None:
1382 continue
1383
1384 try:
1385 vendors[vendor].append((row.subsystem, row.vendor))
1386 except KeyError:
1387 vendors[vendor] = [(row.subsystem, row.vendor)]
1388
1389 return vendors
1390
1391 def _get_devices(self, query, *args, **kwargs):
1392 res = self.db.query(query, *args, **kwargs)
1393
1394 return [Device(self.backend, blob) for blob in res]
1395
1396 def get_devices_by_vendor(self, subsystem, vendor, when=None):
1397 if when:
1398 raise NotImplementedError
1399
1400 else:
1401 return self._get_devices("""
1402 WITH devices AS (
1403 SELECT
1404 jsonb_array_elements(blob->'devices') AS device
1405 FROM
1406 fireinfo
1407 WHERE
1408 expired_at IS NULL
1409 AND
1410 blob IS NOT NULL
1411 AND
1412 blob->'devices' IS NOT NULL
1413 AND
1414 jsonb_typeof(blob->'devices') = 'array'
1415 )
1416
1417 SELECT
1418 device.deviceclass,
1419 device.subsystem,
1420 device.vendor,
1421 device.model,
1422 device.driver
1423 FROM
1424 devices,
1425 jsonb_to_record(devices.device) AS device(
1426 deviceclass text,
1427 subsystem text,
1428 vendor text,
1429 sub_vendor text,
1430 model text,
1431 sub_model text,
1432 driver text
1433 )
1434 WHERE
1435 devices.device->>'subsystem' = %s
1436 AND
1437 devices.device->>'vendor' = %s
1438 AND
1439 NOT devices.device->>'driver' = 'usb'
1440 GROUP BY
1441 device.deviceclass,
1442 device.subsystem,
1443 device.vendor,
1444 device.model,
1445 device.driver
1446 """, subsystem, vendor,
1447 )
1448
1449 def get_devices_by_driver(self, driver, when=None):
1450 if when:
1451 raise NotImplementedError
1452
1453 else:
1454 return self._get_devices("""
1455 WITH devices AS (
1456 SELECT
1457 jsonb_array_elements(blob->'devices') AS device
1458 FROM
1459 fireinfo
1460 WHERE
1461 expired_at IS NULL
1462 AND
1463 blob IS NOT NULL
1464 AND
1465 blob->'devices' IS NOT NULL
1466 AND
1467 jsonb_typeof(blob->'devices') = 'array'
1468 )
1469
1470 SELECT
1471 device.deviceclass,
1472 device.subsystem,
1473 device.vendor,
1474 device.model,
1475 device.driver
1476 FROM
1477 devices,
1478 jsonb_to_record(devices.device) AS device(
1479 deviceclass text,
1480 subsystem text,
1481 vendor text,
1482 sub_vendor text,
1483 model text,
1484 sub_model text,
1485 driver text
1486 )
1487 WHERE
1488 devices.device->>'driver' = '%s'
1489 GROUP BY
1490 device.deviceclass,
1491 device.subsystem,
1492 device.vendor,
1493 device.model,
1494 device.driver
1495 """, driver,
1496 )