]> git.ipfire.org Git - ipfire.org.git/blob - src/backend/fireinfo.py
fireinfo: Show ASN map
[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, 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 # 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 asn
868 )
869 VALUES
870 (
871 %s,
872 %s,
873 %s,
874 %s,
875 %s,
876 %s
877 )
878 """, profile_id, private_id, version, json.dumps(profile), country_code, asn,
879 )
880
881 def _validate(self, profile_id, version, blob):
882 """
883 Validate the profile
884 """
885 if not version == 0:
886 raise ValueError("Unsupported profile version")
887
888 # Validate the blob
889 try:
890 return jsonschema.validate(blob, schema=PROFILE_SCHEMA)
891
892 # Raise a ValueError instead which is easier to handle later on
893 except jsonschema.exceptions.ValidationError as e:
894 raise ValueError("%s" % e) from e
895
896 def _preprocess(self, blob):
897 """
898 Modifies the profile before storing it
899 """
900 # Remove the architecture from the release string
901 blob["system"]["release"]= self._filter_release(blob["system"]["release"])
902
903 return blob
904
905 def _filter_release(self, release):
906 """
907 Removes the arch part
908 """
909 r = [e for e in release.split() if e]
910
911 for s in ("(x86_64)", "(aarch64)", "(i586)", "(armv6l)", "(armv5tel)", "(riscv64)"):
912 try:
913 r.remove(s)
914 break
915 except ValueError:
916 pass
917
918 return " ".join(r)
919
920 # Data outputs
921
922 def get_random_profile(self, when=None):
923 if when:
924 return self._get_profile("""
925 SELECT
926 *
927 FROM
928 fireinfo
929 WHERE
930 created_at <= %s
931 AND
932 (
933 expired_at IS NULL
934 OR
935 expired_at > %s
936 )
937 ORDER BY
938 RANDOM()
939 LIMIT
940 1
941 """, when, when,
942 )
943
944 return self._get_profile("""
945 SELECT
946 *
947 FROM
948 fireinfo
949 WHERE
950 expired_at IS NULL
951 ORDER BY
952 RANDOM()
953 LIMIT
954 1
955 """)
956
957 def get_active_profiles(self, when=None):
958 if when:
959 raise NotImplementedError
960
961 else:
962 res = self.db.get("""
963 SELECT
964 COUNT(*) AS total_profiles,
965 COUNT(*) FILTER (WHERE blob IS NOT NULL) AS active_profiles
966 FROM
967 fireinfo
968 WHERE
969 expired_at IS NULL
970 """)
971
972 if res:
973 return res.active_profiles, res.total_profiles
974
975 def get_geo_location_map(self, when=None):
976 if when:
977 res = self.db.query("""
978 SELECT
979 country_code,
980 fireinfo_percentage(
981 COUNT(*), SUM(COUNT(*)) OVER ()
982 ) AS p
983 FROM
984 fireinfo
985 WHERE
986 created_at <= %s
987 AND
988 (
989 expired_at IS NULL
990 OR
991 expired_at > %s
992 )
993 AND
994 country_code IS NOT NULL
995 GROUP BY
996 country_code
997 """, when, when)
998 else:
999 res = self.db.query("""
1000 SELECT
1001 country_code,
1002 fireinfo_percentage(
1003 COUNT(*), SUM(COUNT(*)) OVER ()
1004 ) AS p
1005 FROM
1006 fireinfo
1007 WHERE
1008 expired_at IS NULL
1009 AND
1010 country_code IS NOT NULL
1011 GROUP BY
1012 country_code
1013 """)
1014
1015 return { row.country_code : row.p for row in res }
1016
1017 def get_asn_map(self, when=None):
1018 if when:
1019 res = self.db.query("""
1020 SELECT
1021 asn,
1022 fireinfo_percentage(
1023 COUNT(*), SUM(COUNT(*)) OVER ()
1024 ) AS p,
1025 COUNT(*) AS c
1026 FROM
1027 fireinfo
1028 WHERE
1029 created_at <= %s
1030 AND
1031 (
1032 expired_at IS NULL
1033 OR
1034 expired_at > %s
1035 )
1036 AND
1037 asn IS NOT NULL
1038 GROUP BY
1039 asn
1040 """, when, when)
1041 else:
1042 res = self.db.query("""
1043 SELECT
1044 asn,
1045 fireinfo_percentage(
1046 COUNT(*), SUM(COUNT(*)) OVER ()
1047 ) AS p,
1048 COUNT(*) AS c
1049 FROM
1050 fireinfo
1051 WHERE
1052 expired_at IS NULL
1053 AND
1054 asn IS NOT NULL
1055 GROUP BY
1056 asn
1057 """)
1058
1059 return { self.backend.location.get_as(row.asn) : (row.c, row.p) for row in res }
1060
1061 @property
1062 def cpu_vendors(self):
1063 res = self.db.query("""
1064 SELECT DISTINCT
1065 blob->'cpu'->'vendor' AS vendor
1066 FROM
1067 fireinfo
1068 WHERE
1069 blob->'cpu'->'vendor' IS NOT NULL
1070 """,
1071 )
1072
1073 return sorted((CPU_VENDORS.get(row.vendor, row.vendor) for row in res))
1074
1075 def get_cpu_vendors_map(self, when=None):
1076 if when:
1077 raise NotImplementedError
1078
1079 else:
1080 res = self.db.query("""
1081 SELECT
1082 blob->'cpu'->'vendor' AS vendor,
1083 fireinfo_percentage(
1084 COUNT(*), SUM(COUNT(*)) OVER ()
1085 ) AS p
1086 FROM
1087 fireinfo
1088 WHERE
1089 expired_at IS NULL
1090 AND
1091 blob IS NOT NULL
1092 AND
1093 blob->'cpu'->'vendor' IS NOT NULL
1094 GROUP BY
1095 blob->'cpu'->'vendor'
1096 """)
1097
1098 return { CPU_VENDORS.get(row.vendor, row.vendor) : row.p for row in res }
1099
1100 def get_cpu_flags_map(self, when=None):
1101 if when:
1102 raise NotImplementedError
1103
1104 else:
1105 res = self.db.query("""
1106 WITH arch_flags AS (
1107 SELECT
1108 ROW_NUMBER() OVER (PARTITION BY blob->'cpu'->'arch') AS id,
1109 blob->'cpu'->'arch' AS arch,
1110 blob->'cpu'->'flags' AS flags
1111 FROM
1112 fireinfo
1113 WHERE
1114 expired_at IS NULL
1115 AND
1116 blob->'cpu'->'arch' IS NOT NULL
1117 AND
1118 blob->'cpu'->'flags' IS NOT NULL
1119
1120 -- Filter out virtual systems
1121 AND
1122 CAST((blob->'system'->'virtual') AS boolean) IS FALSE
1123 )
1124
1125 SELECT
1126 arch,
1127 flag,
1128 fireinfo_percentage(
1129 COUNT(*),
1130 (
1131 SELECT
1132 MAX(id)
1133 FROM
1134 arch_flags __arch_flags
1135 WHERE
1136 arch_flags.arch = __arch_flags.arch
1137 )
1138 ) AS p
1139 FROM
1140 arch_flags, jsonb_array_elements(arch_flags.flags) AS flag
1141 GROUP BY
1142 arch, flag
1143 """)
1144
1145 result = {}
1146
1147 for row in res:
1148 try:
1149 result[row.arch][row.flag] = row.p
1150 except KeyError:
1151 result[row.arch] = { row.flag : row.p }
1152
1153 return result
1154
1155 def get_average_memory_amount(self, when=None):
1156 if when:
1157 res = self.db.get("""
1158 SELECT
1159 AVG(
1160 CAST(blob->'system'->'memory' AS numeric)
1161 ) AS memory
1162 FROM
1163 fireinfo
1164 WHERE
1165 created_at <= %s
1166 AND
1167 (
1168 expired_at IS NULL
1169 OR
1170 expired_at > %s
1171 )
1172 """, when)
1173 else:
1174 res = self.db.get("""
1175 SELECT
1176 AVG(
1177 CAST(blob->'system'->'memory' AS numeric)
1178 ) AS memory
1179 FROM
1180 fireinfo
1181 WHERE
1182 expired_at IS NULL
1183 """,)
1184
1185 return res.memory if res else 0
1186
1187 def get_arch_map(self, when=None):
1188 if when:
1189 raise NotImplementedError
1190
1191 else:
1192 res = self.db.query("""
1193 SELECT
1194 blob->'cpu'->'arch' AS arch,
1195 fireinfo_percentage(
1196 COUNT(*), SUM(COUNT(*)) OVER ()
1197 ) AS p
1198 FROM
1199 fireinfo
1200 WHERE
1201 expired_at IS NULL
1202 AND
1203 blob->'cpu'->'arch' IS NOT NULL
1204 GROUP BY
1205 blob->'cpu'->'arch'
1206 """)
1207
1208 return { row.arch : row.p for row in res }
1209
1210 # Virtual
1211
1212 def get_hypervisor_map(self, when=None):
1213 if when:
1214 raise NotImplementedError
1215 else:
1216 res = self.db.query("""
1217 SELECT
1218 blob->'hypervisor'->'vendor' AS vendor,
1219 fireinfo_percentage(
1220 COUNT(*), SUM(COUNT(*)) OVER ()
1221 ) AS p
1222 FROM
1223 fireinfo
1224 WHERE
1225 expired_at IS NULL
1226 AND
1227 CAST((blob->'system'->'virtual') AS boolean) IS TRUE
1228 AND
1229 blob->'hypervisor'->'vendor' IS NOT NULL
1230 GROUP BY
1231 blob->'hypervisor'->'vendor'
1232 """)
1233
1234 return { row.vendor : row.p for row in res }
1235
1236 def get_virtual_ratio(self, when=None):
1237 if when:
1238 raise NotImplementedError
1239
1240 else:
1241 res = self.db.get("""
1242 SELECT
1243 fireinfo_percentage(
1244 COUNT(*) FILTER (
1245 WHERE CAST((blob->'system'->'virtual') AS boolean) IS TRUE
1246 ),
1247 COUNT(*)
1248 ) AS p
1249 FROM
1250 fireinfo
1251 WHERE
1252 expired_at IS NULL
1253 AND
1254 blob IS NOT NULL
1255 """)
1256
1257 return res.p if res else 0
1258
1259 # Releases
1260
1261 def get_releases_map(self, when=None):
1262 if when:
1263 raise NotImplementedError
1264
1265 else:
1266 res = self.db.query("""
1267 SELECT
1268 blob->'system'->'release' AS release,
1269 fireinfo_percentage(
1270 COUNT(*), SUM(COUNT(*)) OVER ()
1271 ) AS p
1272 FROM
1273 fireinfo
1274 WHERE
1275 expired_at IS NULL
1276 AND
1277 blob IS NOT NULL
1278 AND
1279 blob->'system'->'release' IS NOT NULL
1280 GROUP BY
1281 blob->'system'->'release'
1282 """)
1283
1284 return { row.release : row.p for row in res }
1285
1286 # Kernels
1287
1288 def get_kernels_map(self, when=None):
1289 if when:
1290 raise NotImplementedError
1291
1292 else:
1293 res = self.db.query("""
1294 SELECT
1295 blob->'system'->'kernel' AS kernel,
1296 fireinfo_percentage(
1297 COUNT(*), SUM(COUNT(*)) OVER ()
1298 ) AS p
1299 FROM
1300 fireinfo
1301 WHERE
1302 expired_at IS NULL
1303 AND
1304 blob IS NOT NULL
1305 AND
1306 blob->'system'->'kernel' IS NOT NULL
1307 GROUP BY
1308 blob->'system'->'kernel'
1309 """)
1310
1311 return { row.kernel : row.p for row in res }
1312
1313 subsystem2class = {
1314 "pci" : hwdata.PCI(),
1315 "usb" : hwdata.USB(),
1316 }
1317
1318 def get_vendor_string(self, subsystem, vendor_id):
1319 try:
1320 cls = self.subsystem2class[subsystem]
1321 except KeyError:
1322 return ""
1323
1324 return cls.get_vendor(vendor_id) or ""
1325
1326 def get_model_string(self, subsystem, vendor_id, model_id):
1327 try:
1328 cls = self.subsystem2class[subsystem]
1329 except KeyError:
1330 return ""
1331
1332 return cls.get_device(vendor_id, model_id) or ""
1333
1334 def get_vendor_list(self, when=None):
1335 if when:
1336 raise NotImplementedError
1337
1338 else:
1339 res = self.db.query("""
1340 WITH devices AS (
1341 SELECT
1342 jsonb_array_elements(blob->'devices') AS device
1343 FROM
1344 fireinfo
1345 WHERE
1346 expired_at IS NULL
1347 AND
1348 blob IS NOT NULL
1349 AND
1350 blob->'devices' IS NOT NULL
1351 AND
1352 jsonb_typeof(blob->'devices') = 'array'
1353 )
1354
1355 SELECT
1356 devices.device->'subsystem' AS subsystem,
1357 devices.device->'vendor' AS vendor
1358 FROM
1359 devices
1360 WHERE
1361 devices.device->'subsystem' IS NOT NULL
1362 AND
1363 devices.device->'vendor' IS NOT NULL
1364 AND
1365 NOT devices.device->>'driver' = 'usb'
1366 GROUP BY
1367 subsystem, vendor
1368 """)
1369
1370 vendors = {}
1371
1372 for row in res:
1373 vendor = self.get_vendor_string(row.subsystem, row.vendor) or row.vendor
1374
1375 # Drop if vendor could not be determined
1376 if vendor is None:
1377 continue
1378
1379 try:
1380 vendors[vendor].append((row.subsystem, row.vendor))
1381 except KeyError:
1382 vendors[vendor] = [(row.subsystem, row.vendor)]
1383
1384 return vendors
1385
1386 def _get_devices(self, query, *args, **kwargs):
1387 res = self.db.query(query, *args, **kwargs)
1388
1389 return [Device(self.backend, blob) for blob in res]
1390
1391 def get_devices_by_vendor(self, subsystem, vendor, when=None):
1392 if when:
1393 raise NotImplementedError
1394
1395 else:
1396 return self._get_devices("""
1397 WITH devices AS (
1398 SELECT
1399 jsonb_array_elements(blob->'devices') AS device
1400 FROM
1401 fireinfo
1402 WHERE
1403 expired_at IS NULL
1404 AND
1405 blob IS NOT NULL
1406 AND
1407 blob->'devices' IS NOT NULL
1408 AND
1409 jsonb_typeof(blob->'devices') = 'array'
1410 )
1411
1412 SELECT
1413 device.deviceclass,
1414 device.subsystem,
1415 device.vendor,
1416 device.model,
1417 device.driver
1418 FROM
1419 devices,
1420 jsonb_to_record(devices.device) AS device(
1421 deviceclass text,
1422 subsystem text,
1423 vendor text,
1424 sub_vendor text,
1425 model text,
1426 sub_model text,
1427 driver text
1428 )
1429 WHERE
1430 devices.device->>'subsystem' = %s
1431 AND
1432 devices.device->>'vendor' = %s
1433 AND
1434 NOT devices.device->>'driver' = 'usb'
1435 GROUP BY
1436 device.deviceclass,
1437 device.subsystem,
1438 device.vendor,
1439 device.model,
1440 device.driver
1441 """, subsystem, vendor,
1442 )
1443
1444 def get_devices_by_driver(self, driver, when=None):
1445 if when:
1446 raise NotImplementedError
1447
1448 else:
1449 return self._get_devices("""
1450 WITH devices AS (
1451 SELECT
1452 jsonb_array_elements(blob->'devices') AS device
1453 FROM
1454 fireinfo
1455 WHERE
1456 expired_at IS NULL
1457 AND
1458 blob IS NOT NULL
1459 AND
1460 blob->'devices' IS NOT NULL
1461 AND
1462 jsonb_typeof(blob->'devices') = 'array'
1463 )
1464
1465 SELECT
1466 device.deviceclass,
1467 device.subsystem,
1468 device.vendor,
1469 device.model,
1470 device.driver
1471 FROM
1472 devices,
1473 jsonb_to_record(devices.device) AS device(
1474 deviceclass text,
1475 subsystem text,
1476 vendor text,
1477 sub_vendor text,
1478 model text,
1479 sub_model text,
1480 driver text
1481 )
1482 WHERE
1483 devices.device->>'driver' = '%s'
1484 GROUP BY
1485 device.deviceclass,
1486 device.subsystem,
1487 device.vendor,
1488 device.model,
1489 device.driver
1490 """, driver,
1491 )