This repository was archived by the owner on Jan 31, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathpatchbot.py
executable file
·1486 lines (1228 loc) · 55.3 KB
/
patchbot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Main script for the patchbot client.
This is the main script for the patchbot client. It pulls branches
from trac, applies them, and publishes the results of the tests to a
server running ``serve.py``. Configuration is primarily done via an
optional ``conf.json`` file (json format) passed in as a command line
argument.
"""
# -------------------------------------------------------------------
# Author: Robert Bradshaw <[email protected]>
#
# Copyright 2010-14 (C) Google, Inc.
#
# Distributed under the terms of the GNU General Public License (GPL)
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
# https://www.gnu.org/licenses/
# -------------------------------------------------------------------
from __future__ import annotations
from typing import Iterator, Any
# global python imports
import codecs
import signal
import getpass
import glob
import os
import shutil
import sys
import subprocess
import time
import traceback
import tempfile
import bz2
import json
import socket
import pprint
import multiprocessing
import pickle
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.parse import urlencode
from argparse import ArgumentParser
from datetime import datetime
from pathlib import Path
# imports from patchbot sources
import sage_patchbot
from .trac import get_ticket_info_from_trac_server, pull_from_trac, TracServer, Config, is_closed_on_trac
from .util import (now_str, prune_pending, do_or_die,
get_sage_version, current_reports, git_commit,
# branch_updates_some_package,
# branch_updates_only_ci,
describe_branch, comparable_version, temp_build_suffix,
ensure_free_space, get_python_version,
ConfigException, SkipTicket, TestsFailed)
from .http_post_file import post_multipart
from .plugins import PluginResult, plugins_available
# name of the log files
LOG_RATING = 'rating.log'
LOG_RATING_SHORT = 'rating_summary.txt'
LOG_MAIN = ('patchbot.log', sys.stdout)
LOG_MAIN_SHORT = 'history.txt'
LOG_CONFIG = 'config.txt'
def filter_on_authors(tickets: list, authors) -> Iterator:
"""
Keep only tickets with authors among the given ones.
Every ticket is a dict.
INPUT:
a list of tickets and a list of authors
OUTPUT:
a list of tickets
"""
if authors is not None:
authors = set(authors)
for ticket in tickets:
if authors is None or set(ticket['authors']).issubset(authors):
yield ticket
def compare_machines(a: list[str], b: list[str], machine_match=0) -> list[bool]:
"""
Compare two machines a and b.
Return a list.
machine_match is a number of initial things to look at.
EXAMPLES::
>>> m1 = ['Ubuntu', '14.04', 'i686', '3.13.0-40-generic', 'arando']
>>> m2 = ['Fedora', '19', 'x86_64', '3.10.4-300.fc19.x86_64', 'desktop']
>>> compare_machines(m1, m2)
"""
if machine_match:
a = a[:machine_match]
b = b[:machine_match]
diff = [x != y for x, y in zip(a, b)]
if len(a) != len(b):
diff.append(True)
return diff
class TimeOut(Exception):
pass
def alarm_handler(signum, frame):
raise TimeOut
class Tee():
def __init__(self, filepath, time=False, timeout=None, timer=None):
if timeout is None:
timeout = 60 * 60 * 24
self.filepath = filepath
self.time = time
self.timeout = timeout
self.timer = timer
def __enter__(self):
self._saved = os.dup(sys.stdout.fileno()), os.dup(sys.stderr.fileno())
self.tee = subprocess.Popen(["tee", self.filepath],
stdin=subprocess.PIPE)
os.dup2(self.tee.stdin.fileno(), sys.stdout.fileno())
os.dup2(self.tee.stdin.fileno(), sys.stderr.fileno())
if self.time:
print(now_str())
self.start_time = time.time()
def __exit__(self, exc_type, exc_val, exc_tb):
if self.timer:
self.timer.print_all()
if exc_type is not None:
traceback.print_exc()
if self.time:
print(now_str())
msg = "{} seconds".format(int(time.time() - self.start_time))
print(msg)
self.tee.stdin.close()
time.sleep(1)
os.dup2(self._saved[0], sys.stdout.fileno())
os.dup2(self._saved[1], sys.stderr.fileno())
os.close(self._saved[0])
os.close(self._saved[1])
time.sleep(1)
try:
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(self.timeout)
self.tee.wait()
signal.alarm(0)
except TimeOut:
traceback.print_exc()
raise
return False
class Timer():
def __init__(self):
self._starts = {}
self._history = []
self.start()
def start(self, label=None):
self._last_activity = self._starts[label] = time.time()
def finish(self, label=None):
try:
elapsed = time.time() - self._starts[label]
except KeyError:
elapsed = time.time() - self._last_activity
self._last_activity = time.time()
self.print_time(label, elapsed)
self._history.append((label, elapsed))
def print_time(self, label, elapsed):
msg = '{} -- {} seconds'.format(label, int(elapsed))
print(msg)
def print_all(self):
for label, elapsed in self._history:
self.print_time(label, elapsed)
status = {'started': 'ApplyFailed',
'applied': 'BuildFailed',
'built': 'TestsFailed',
'tested': 'TestsPassed',
'tests_passed_on_retry': 'TestsPassedOnRetry',
'tests_passed_plugins_failed': 'PluginFailed',
'plugins': 'PluginOnly',
'plugins_failed': 'PluginOnlyFailed',
'spkg': 'Spkg',
'network_error': 'Pending',
'skipped': 'Pending'}
def boundary(name: str, text_type: str) -> str:
"""
Return text that bound parts of the reports.
type can be 'plugin', 'plugin_end', 'ticket' and 'spkg'
"""
if text_type == 'plugin':
letter = '='
length = 10
elif text_type == 'plugin_end':
name = 'end ' + name
letter = '='
length = 10
elif text_type == 'ticket':
letter = '='
length = 30
elif text_type == 'spkg':
letter = '+'
length = 10
return ' '.join((letter * length, str(name), letter * length))
def machine_data() -> list[str]:
"""
Return the machine data as a list of strings.
This uses ``os.uname`` to find the data.
EXAMPLES::
m1 = ['Ubuntu', '14.04', 'i686', '3.13.0-40-generic', 'arando']
m2 = ['Fedora', '19', 'x86_64', '3.10.4-300.fc19.x86_64', 'desktop']
"""
first_cleanup = [txt.replace(" ", "_") for txt in os.uname()]
system, node, release, version, arch = [txt.replace("#", "")
for txt in first_cleanup]
return [system, version, arch, release, node]
def parse_time_of_day(s) -> list[tuple]:
"""
Parse the 'time_of_day' config.
Examples of syntax: default is "0-0" from midnight to midnight
"06-18" start and end hours
"22-07" idem during the night
"10-12,14-18" several time ranges
"17" for just one hour starting at given time
"""
def parse_interval(ss: str) -> tuple:
ss = ss.strip()
if '-' in ss:
start, end = ss.split('-')
return float(start), float(end)
return float(ss), float(ss) + 1
return [parse_interval(ss) for ss in s.split(',')]
def check_time_of_day(hours):
"""
Check that the time is inside the allowed running hours.
This is with respect to local time.
"""
now = datetime.now(None)
hour = now.hour + now.minute / 60.
for start, end in parse_time_of_day(hours):
if start < end:
if start <= hour <= end:
return True
elif hour <= end or start <= hour:
return True
return False
class OptionDict():
r"""
Fake option class built from a dictionary.
This used to run the patchbot in a IPython console. It contains default
values for the 10 options that can be provided from command line. These
default can be changed by passing a dictionary to the constructor.
EXAMPLES::
>>> OptionDict().sage_root
None
>>> OptionDict({'sage_root': '/path/to/sage/root/'}).sage_root
'/path/to/sage/root'
"""
sage_root = None
server = 'https://patchbot.sagemath.org'
config = None
cleanup = False
dry_run = False
no_banner = False
owner = None
plugin_only = False
safe_only = True
skip_base = True
retries = None
skip_doc_clean = False
def __init__(self, d):
for key, value in d.items():
setattr(self, key, value)
class Patchbot():
"""
Main class of the patchbot.
This can be used in an interactive python or ipython session.
INPUT:
- options -- an option class or a dictionary
EXAMPLES::
>>> from sage_patchbot.patchbot import Patchbot
>>> P = Patchbot({'sage_root': '/homes/leila/sage'})
>>> P.test_a_ticket(12345)
How to more or less ban an author: have
{"bonus":{"proust":-1000}}
written inside the config.json file passed using --config=config.json
"""
# hardcoded default config and bonus
default_config: dict[str, Any] = {
"sage_root": None,
"server": "https://patchbot.sagemath.org/",
"idle": 300,
"time_of_day": "0-0", # midnight-midnight
"parallelism": min(3, multiprocessing.cpu_count()),
"timeout": 3 * 60 * 60,
"plugins": ["commit_messages",
"coverage",
"deprecation_number",
"doctest_continuation",
"python3",
"python3_pyx",
"blocks",
"triple_colon",
"foreign_latex",
"trac_links",
"startup_time",
"startup_modules",
"docbuild",
"git_rev_list"],
"plugins_disabled": [],
"plugins_enabled": [],
"bonus": {},
"machine": machine_data(),
"machine_match": 5,
"user": getpass.getuser(),
"keep_open_branches": True,
"base_repo": "git://trac.sagemath.org/sage.git",
"base_branch": "develop",
"max_behind_commits": 0,
"max_behind_days": 1.0,
"use_ccache": True,
"tested_files": "all", # either 'all' or 'py3' or 'py3+changed'
"test_options": None, # transmitted to --optional
# 6 options that can also be changed using sage --xx
"dry_run": False,
"no_banner": False,
"owner": "unknown owner",
"plugin_only": False,
"safe_only": True,
"skip_base": False,
"retries": 0,
"cleanup": False,
"skip_doc_clean": False}
default_bonus = {"needs_review": 1000,
"positive_review": 500,
"blocker": 100,
"critical": 60,
"major": 10,
"unique": 40,
"applies": 20,
"behind": 1}
def __init__(self, options=None):
if isinstance(options, dict):
# when this is run in a IPython session
options = OptionDict(options)
self.options = options
self.reload_config()
self.trac_server = TracServer(Config())
self.__version__ = sage_patchbot.__version__
self.last_pull = 0.0
self.to_skip = {}
self.idling = False
self.write_log('Patchbot {} initialized with SAGE_ROOT={} (pid: {})'.format(
self.__version__, self.sage_root, os.getpid()), LOG_MAIN)
def idle(self):
"""
Sleep for ``idle`` seconds, where ``idle`` is the option supplied by
the patchbot configuration.
While idling, the ``idling`` attribute is set to ``True``.
"""
self.idling = True
time.sleep(self.config['idle'])
self.idling = False
def write_log(self, msg, logfile=None, date=True):
r"""
Write ``msg`` in a logfile.
INPUT:
- ``logfile`` -- (optional)
* if not provided, write on stdout
* if it is a string then append ``msg`` to the file ``logfile``
* if it is a tuple or a list, then call write_log for each member of
that list
- ``date`` -- (default ``True``) whether to write the date at the
beginning of the line
"""
if logfile is None:
logfile = sys.stdout
close = False
elif isinstance(logfile, str):
filename = self.log_dir / logfile
logfile = codecs.open(filename, 'a', encoding='utf-8')
close = True
elif isinstance(logfile, (tuple, list)):
for f in logfile:
self.write_log(msg, f, date)
return
else: # logfile is a file
close = False
try:
if date:
logfile.write("[{}] ".format(now_str()))
logfile.write(msg)
logfile.write("\n")
except AttributeError:
raise ValueError("logfile = {} must be either None, or a string or a list or a file".format(logfile))
if close:
logfile.close()
else:
logfile.flush()
def delete_log(self, logfile):
r"""
Delete ``logfile``
"""
filename = self.log_dir / logfile
if filename.is_file():
os.remove(filename)
def version(self):
"""
Return the version of the patchbot.
Something like '2.3.7'
EXAMPLES::
In [3]: P.version()
Out[3]: '2.5.3'
"""
return self.__version__
def banner(self):
"""
A banner for the patchbot
EXAMPLES::
In [7]: print(P.banner())
┌─┬──────┐
│░│ •• │ SageMath patchbot
│░│ │
│░│ ──── │ version 3.0.3
╘═╧══════╛
"""
s = '┌─┬──────┐\n'
s += '│░│ •• │ SageMath patchbot\n'
s += '│░│ │\n'
s += '│░│ ──── │ version {}\n'.format(self.version())
s += '╘═╧══════╛'
return s
def load_json_from_server(self, path, retry=1):
"""
Load a json file from the patchbot server.
This is one connection between patchbot server and clients.
INPUT:
- ``path`` -- the query for the server
- ``retry`` -- the number of times we retry to get a connection
"""
while True:
retry -= 1
try:
ad = "{}/{}".format(self.server, path)
full_str = urlopen(ad, timeout=10).read().decode('utf8')
return json.loads(full_str)
except HTTPError as err:
self.write_log(" retry {}; {}".format(retry, str(err)), [LOG_MAIN, LOG_MAIN_SHORT])
if retry == 0:
raise
except socket.timeout:
self.write_log(" retry {}; timeout while querying the patchbot server with '{}'".format(retry, path), [LOG_MAIN, LOG_MAIN_SHORT])
if retry == 0:
raise
time.sleep(30)
def lookup_ticket(self, t_id, verbose=False):
"""
Retrieve information about one ticket from the patchbot server.
(or from trac if the patchbot server does not answer)
For an example of the page it calls:
https://patchbot.sagemath.org/ticket/?raw&query={"id":11529}
For humans:
https://patchbot.sagemath.org/ticket/?raw&query={"id":11529}&pretty
"""
path = "ticket/?" + urlencode({'raw': True,
'query': json.dumps({'id': t_id})})
res = self.load_json_from_server(path, retry=3)
if res:
if verbose:
print('data retrieved from patchbot server')
return res[0]
if verbose:
print('data retrieved from trac server')
return get_ticket_info_from_trac_server(t_id)
def get_local_config(self):
"""
Return the configuration obtained from the command line option and the
local configuration file.
This is done in the following order:
1) pick default values for all parameters
2) override with values from json config file if given
3) override from the options class given in argument
"""
# start from a fresh copy of the default configuration
conf = self.default_config.copy()
# override the default by the json config file
if self.options.config is not None:
with open(self.options.config) as f:
for key, value in json.load(f).items():
conf[str(key)] = value
# complete back the default bonus if needed
for key, value in self.default_bonus.items():
if key not in conf['bonus']:
conf['bonus'][key] = value
# now override with the values of the 9 options (all except 'config')
# coming from the patchbot commandline
for opt in ('sage_root', 'server', 'cleanup', 'dry_run', 'no_banner',
'owner', 'plugin_only', 'safe_only', 'skip_base',
'retries', 'skip_doc_clean'):
value = getattr(self.options, opt)
if value is not None:
conf[opt] = value
# plugin setup
plugins_set = set(conf['plugins'])
plugins_set.update(conf.pop("plugins_enabled"))
# always use the pyflakes and pycodestyle plugins
plugins_set.add("pyflakes")
plugins_set.add("pycodestyle")
plugins_set.difference_update(conf.pop("plugins_disabled"))
# for backward compatibility (allow both plugins.X and just X)
plugins_set = set(name.split('.')[-1] for name in plugins_set)
if not conf['plugin_only']:
plugins_set.add("docbuild") # docbuild is mandatory so that tests pass
plugins = (p for p in plugins_available if p in plugins_set)
def locate_plugin(name):
plugin = getattr(__import__("sage_patchbot.plugins",
fromlist=[name]), name)
assert callable(plugin)
return plugin
conf["plugins"] = [(name, locate_plugin(name)) for name in plugins]
return conf
def reload_config(self):
"""
Reload the configuration.
This method has for main purpose to set properly the attribute
``config`` (the configuration dictionary).
"""
self.config = self.get_local_config()
# Now we set sage_root and some other attributes that depend on
# sage_root. (here might not be the right place to do it)
self.sage_root = self.config["sage_root"]
if (self.sage_root is None or
not os.path.isdir(self.sage_root) or
not os.path.isabs(self.sage_root) or
not os.path.isfile(os.path.join(self.sage_root, "sage"))):
raise ValueError("the sage_root option should be specified "
"as an absolute path to a Sage installation (either from "
"the command line option --sage-root=/path/to/sage or inside "
"the configuration file provided with "
"--config=path/to/config.json)")
self.sage_command = os.path.join(self.sage_root, "sage")
self.python_version = get_python_version(self.sage_command)
self.base = get_sage_version(self.sage_root)
# TODO: this should be configurable
self.log_dir = Path(self.sage_root) / "logs" / "patchbot"
self.server = self.config["server"]
# make sure that the log directory is writable and write the
# configuration file there
if not self.log_dir.exists():
os.makedirs(self.log_dir)
with codecs.open(self.log_dir / 'install.log', 'a',
encoding='utf8'):
pass
# write the config in logfile
self.delete_log(LOG_CONFIG)
self.write_log("Configuration for the patchbot\n{}\n".format(now_str()), LOG_CONFIG, False)
self.write_log(pprint.pformat(self.config), LOG_CONFIG, False)
return self.config
def reset_root(self):
"""
Ensure that we are in the correct SAGE_ROOT.
"""
# Don't do this is self.sage_root is None; we never want to set
# SAGE_ROOT to None
if self.sage_root is not None:
os.chdir(self.sage_root)
os.environ['SAGE_ROOT'] = self.sage_root
def check_base(self) -> bool:
"""
Check that the patchbot/base is synchro with 'base_branch'.
Usually 'base_branch' is set to 'develop'.
This will update the patchbot/base if necessary.
"""
os.chdir(self.sage_root)
self.write_log("Check base.", LOG_MAIN)
try:
do_or_die("git checkout patchbot/base")
except Exception:
do_or_die("git checkout -b patchbot/base")
do_or_die("git fetch %s --tags -f" %
self.config['base_repo'])
do_or_die("git fetch %s +%s:patchbot/base_upstream" %
(self.config['base_repo'], self.config['base_branch']))
only_in_base = int(subprocess.check_output(["git", "rev-list", "--count", "patchbot/base_upstream..patchbot/base"]))
only_in_upstream = int(subprocess.check_output(["git", "rev-list", "--count", "patchbot/base..patchbot/base_upstream"]))
max_behind_time = self.config['max_behind_days'] * 60 * 60 * 24
if (only_in_base > 0 or
only_in_upstream > self.config['max_behind_commits'] or
(only_in_upstream > 0 and
time.time() - self.last_pull < max_behind_time)):
do_or_die("git checkout patchbot/base_upstream")
do_or_die("git branch -f patchbot/base patchbot/base_upstream")
do_or_die("git checkout patchbot/base")
self.last_pull = time.time()
return False
return True
def human_readable_base(self):
"""
Return the human name of the base branch.
"""
# TODO: Is this stable?
version = get_sage_version(self.sage_root)
commit_count = int(subprocess.check_output(['git', 'rev-list',
'--count',
'%s..patchbot/base' % version]))
return "{} + {} commits".format(version, commit_count)
def get_one_ticket(self, status='open', verbose=0):
"""
Return one ticket with its rating.
If no ticket is found, return ``None``.
INPUT:
- ``verbose`` -- if set to 0 then nothing is print on stdout, if 1 then
only the summary is print on stdout and if 2 then also the details of
the rating
OUTPUT:
A pair (rating, ticket data). The rating is a tuple of integer values.
"""
query = "raw&status={}".format(status)
self.write_log("Getting ticket list...", LOG_MAIN)
if self.to_skip:
s = ', '.join('#{} (until {})'.format(k, v)
for k, v in self.to_skip.items())
self.write_log('The following tickets will be skipped: ' + s, LOG_MAIN)
all_tickets = self.load_json_from_server("ticket/?" + query, retry=10)
# rating for all tickets
self.delete_log(LOG_RATING)
self.write_log("Rating tickets...", LOG_MAIN)
all_tickets = [(self.rate_ticket(ti, verbose=(verbose == 2)), ti)
for ti in all_tickets]
# remove all tickets with None rating
all_tickets = [ti for ti in all_tickets if ti[0] is not None]
# sort tickets using their ratings
all_tickets.sort()
self.delete_log(LOG_RATING_SHORT)
if verbose >= 1:
logfile = [LOG_RATING_SHORT, sys.stdout]
else:
logfile = [LOG_RATING_SHORT]
for rating, ticket in reversed(all_tickets):
self.write_log('#{:<6}{:30}{}'.format(ticket['id'],
str(rating[:2]),
ticket['title']),
logfile, date=False)
return all_tickets[-1] if all_tickets else None
def rate_ticket(self, ticket, verbose=False):
"""
Evaluate the interest to test this ticket.
Return nothing when the ticket should not be tested.
"""
os.chdir(self.sage_root)
log_rat_path = self.log_dir / LOG_RATING
with codecs.open(log_rat_path, "a", encoding="utf-8") as log_rating:
if verbose:
logfile = [log_rating, sys.stdout]
else:
logfile = [log_rating]
if isinstance(ticket, (int, str)):
ticket = self.lookup_ticket(ticket)
rating = 0
if ticket['id'] == 0:
return ((100), 100, 0)
if not ticket.get('git_branch'):
self.write_log('#{}: no git branch'.format(ticket['id']), logfile)
return
if ticket['status'] not in ('needs_review', 'positive_review',
'needs_info', 'needs_work'):
msg = '#{}: bad status (={})'
self.write_log(msg.format(ticket['id'],
ticket['status']), logfile)
return
self.write_log("#{}: start rating".format(ticket['id']), logfile)
if ticket['milestone'] in ('sage-duplicate/invalid/wontfix',
'sage-feature', 'sage-pending',
'sage-wishlist'):
self.write_log(' do not test if the milestone is not good (got {})'.format(ticket['milestone']),
logfile, False)
return
bonus = self.config['bonus'] # load the dict of bonus
if ticket.get('git_commit', 'unknown') == 'unknown':
self.write_log(' do not test if git_commit is unknown',
logfile, False)
return
if not ticket.get('authors_fullnames', []):
self.write_log(' do not test if no author is given',
logfile, False)
return
for author in ticket['authors_fullnames']:
rating += 2 * bonus.get(author, 0) # bonus for authors
for author in ticket['authors']:
rating += 2 * bonus.get(author, 0) # bonus for authors
self.write_log(' rating {} after authors'.format(rating),
logfile, False)
for participant in ticket['participants']:
rating += bonus.get(participant, 0) # bonus for participants
self.write_log(' rating {} after participants'.format(rating),
logfile, False)
if 'component' in ticket:
rating += bonus.get(ticket['component'], 0) # bonus for components
self.write_log(' rating {} after components'.format(rating),
logfile, False)
rating += bonus.get(ticket['status'], 0)
rating += bonus.get(ticket['priority'], 0)
rating += bonus.get(str(ticket['id']), 0)
msg = ' rating {} after status ({})/priority ({})/id ({})'
self.write_log(msg.format(rating, ticket['status'],
ticket['priority'], ticket['id']),
logfile, False)
prune_pending(ticket)
retry = ticket.get('retry', False)
# by default, do not retry the ticket
uniqueness = (100,)
# now let us look at previous reports
if not retry:
self.write_log(' start report scanning', logfile, False)
for report in self.current_reports(ticket, newer=True):
if report.get('git_base'):
try:
only_in_base = int(subprocess.check_output(["git", "rev-list", "--count", "%s..patchbot/base" % report['git_base']],
stderr=subprocess.PIPE))
except (ValueError, subprocess.CalledProcessError):
# report['git_base'] not in our repo
self.write_log(' commit {} not in the local git repository'.format(report['git_base']),
logfile, date=False)
only_in_base = -1
rating += bonus['behind'] * only_in_base
self.write_log(' rating {} after behind'.format(rating),
logfile, False)
report_uniq_bool = compare_machines(report['machine'],
self.config['machine'],
self.config['machine_match'])
report_uniqueness = tuple(int(x) for x in report_uniq_bool)
if only_in_base and not any(report_uniqueness):
report_uniqueness = (0, 0, 0, 0, 1)
uniqueness = min(uniqueness, report_uniqueness)
if report['status'] != 'ApplyFailed':
rating += bonus.get("applies", 0)
self.write_log(' rating {} after applies'.format(rating),
logfile, False)
rating -= bonus.get("unique", 0)
self.write_log(' rating {} after uniqueness'.format(rating),
logfile, False)
self.write_log(' rating {} after report scanning'.format(rating),
logfile, False)
if not any(uniqueness):
self.write_log(' already done', logfile, False)
return
if ticket['id'] in self.to_skip:
if self.to_skip[ticket['id']] < time.time():
del self.to_skip[ticket['id']]
else:
self.write_log(' do not test if still in the skip delay',
logfile, False)
return
return uniqueness, rating, -int(ticket['id'])
def current_reports(self, ticket, newer=False):
"""
Return the list of current reports on a ticket.
EXAMPLES::
In [4]: P.current_reports(20240)
Out[4]: []
"""
if isinstance(ticket, (int, str)):
ticket = self.lookup_ticket(ticket)
return current_reports(ticket, base=self.base, newer=newer)
def test_some_tickets(self, ticket_list):
"""
Launch the tests of several tickets (in the given order).
Useful for manual trigger.
INPUT:
- ``ticket`` -- a list of integers
"""
for t in ticket_list:
self.test_a_ticket(t)
def test_a_ticket(self, ticket=None):
"""
Launch the test of a ticket.
INPUT:
- ``ticket``
* if ``None`` then pick a ticket using :meth:`get_one_ticket`
* if an integer or a string, use this ticket number
"""
self.reset_root()
# ------------- selection of ticket -------------
if ticket is None:
ask_for_one = self.get_one_ticket()
if ask_for_one:
rating, ticket = ask_for_one
self.write_log('testing found ticket #{}'.format(ticket['id']), LOG_MAIN)
else:
N = int(ticket)
ticket = self.lookup_ticket(N)
rating = None
self.write_log('testing given ticket #{}'.format(N), LOG_MAIN)
if not ticket:
self.write_log('no more tickets, take a nap',
[LOG_MAIN, LOG_MAIN_SHORT])
self.idle()
return
# this should be a double check and never happen
if ticket.get('status') == 'closed' or is_closed_on_trac(ticket['id']):
self.write_log('tried to test a closed ticket! shame!',
[LOG_MAIN, LOG_MAIN_SHORT])
# here call for refresh ?
self.to_skip[ticket['id']] = time.time() + 120 * 60 * 60
return
if ticket['id'] == 0:
self.write_log('testing the base', LOG_MAIN)
rating = 100
if rating is None:
self.write_log("warning: rating is None, testing #{} at your own risk".format(ticket['id']),
LOG_MAIN)
if not (ticket.get('git_branch') or ticket['id'] == 0):
self.write_log("no git branch for #{}, hence no testing".format(ticket['id']),