-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathp4review2.py
More file actions
executable file
·1718 lines (1492 loc) · 57.6 KB
/
p4review2.py
File metadata and controls
executable file
·1718 lines (1492 loc) · 57.6 KB
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 python3
# -*- coding: utf-8 -*-
"""$Id: //guest/lester_cheung/p4review/p4review2.py#42 $
$Change: 27935 $
$DateTime: 2021/08/02 10:58:50 $
$Author: lester_cheung $
This is/will be a complete rewrite of the original Perforce review
daemon.
USAGE
--------
1. Run p4review2.py --sample-config > p4review.conf
2. Edit the file p4review.conf
3. Add a crontab similar to this:
* * * * * python3 /path/to/p4review2.py -c /path/to/p4review.conf
FEATURES
---------
* (!!) Prevent multiple copies running concurrently with a simple lock file.
* Logging support built-in.
* Takes command-line options.
* Configurable subject and email templates.
* Can (optionally) include URLs for changelists/jobs. Examples for
P4Web included.
* Use P4Python when available and use P4 (the CLI) as a fallback.
* Option to send a __single__ email per user per invocation instead of
multiple ones.
* Reads config from a INI-like file using ConfigParser
* Have command line options that overrides environment variables.
* Handles unicode-enabled server **and** non-ASCII characters on a
non-unicode-enabled server.
* Option to opt-in (--opt-in-path) reviews globally (for migration
from old review daemon).
* Configurable URLs for changes/jobs/users (for swarm).
* Able to limit the maximum email message size with a configurable.
* SMTP auth and TLS (not SSL) support.
* Handles P4 auth (optional, not recommended!).
Nice to haves (TODOs)
-----------------------
* Python3 support
* Respect protection table (for older P4D versions). See:
http://swarm.workshop.perforce.com/guest/lester_cheung/p4review/p4review.py
for a previous attempt.
* Supports hooks from the changelist description to notify additional
users/email.
* Skip review email for change authors [done] and job modifiers
[todo]. The later is not recorded in the job spec by default so it
must be a configruable...
* Also skip email notification for service/operator users.
* Run as a standalone daemon (UNIX [done] and Windows). See this recipe for
an implementation on Windows:
http://code.activestate.com/recipes/576451-how-to-create-a-windows-service-in-python/
DISCLAIMER
-----------
User contributed content on the Perforce Public Depot is not supported
by Perforce, although it may be supported by its author. This applies
to all contributions even those submitted by Perforce employees.
If you have any comments or need any help with the content of
this particular folder, please contact
https://twitter.com/p4lester
"""
import argparse
import atexit
import cgi
import email
import hashlib
import logging
log = logging
import marshal
import os, sys
import re
import shlex
import smtplib
import sqlite3
import time
import traceback
## Yucky bits to handle Python2 and Python3 differences
PY2 = sys.version_info[0] == 2 # sys.version_info.major won't work until 2.7 :(
PY3 = sys.version_info[0] == 3
if PY2:
from ConfigParser import SafeConfigParser as ConfigParser
from StringIO import StringIO
from cgi import escape as html_escape
from cPickle import loads, dumps
elif PY3:
from io import StringIO
from configparser import ConfigParser
from html import escape as html_escape
from pickle import loads, dumps
unicode = lambda *x: x[0]
from datetime import datetime, timedelta
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from getpass import getuser # works under UNIX & Windows!
from io import BytesIO
from operator import itemgetter
from pprint import pprint, pformat
from signal import SIGTERM
from subprocess import Popen, PIPE, check_output
from textwrap import TextWrapper
## FIXME: DEBUG LEVELS (make it a configurable?)
# 0 NOTSET
# 10 DEBUG
# 20 INFO
# 30 WARN, WARNING
# 40 ERROR
# 50 CRITICAL, FATAL
DEBUGLVL = log.DEBUG
CFG_SECTION_NAME = "p4review"
# Instead of changing these, store your preferences in a config file.
# See the --sample-config option.
DEFAULTS = dict(
# General
log_file = '', # optional, but recommended
debug_level = 'DEBUG',
pid_file = os.path.join(os.path.realpath('.'), 'p4review2.pid'),
dbfile = ':memory:', # an (temporary) SQLite db used to
# store review info from Perforce
opt_in_path = '',
daemon = '',
poll_interval = 300,
# Perforce
p4bin = '/usr/local/bin/p4',
p4port = os.environ.get('P4PORT', '1666'),
p4user = os.environ.get('P4USER', getuser()),
p4charset = 'utf8', # as P4CHARSET and to handle non-unicode server with non-ascii chars...
p4passwd = '', # completely optional, best to setup ticket-based auth instead.
review_counter = 'review', # Perforce counter name used to keep track of last changelist notified.
job_counter = '', # like review_counter but for jobs. Disabled by default. Set to 'jobreview' to enable.
job_datefield = 'Date',
spec_depot = 'spec',
timeoffset = 0.0, # in hours
ignored_users = ['git-fusion-reviews-*'],
# Email
smtp_server = 'smtp:25',
smtp_ssl = 'none/ssl/tls',
smtp_user = '', # optional
smtp_passwd = '', # optional
summary_email = False,
skip_author = True,
max_email_size = 1024**2, # up to ~30MB for exchange servers
max_emails = 99, # start small - people can choose to increase this
max_length = 2**12,
default_sender = 'Perforce Review Daemon <perforce-review-daemon>', # Now we can claim to be a daemon without guilt!
default_domain = 'example.org',
change_url = 'http://p4web:1680/{chgno}?ac=10',
job_url = 'http://p4web:1680/{jobno}?ac=111',
user_url = 'http://p4web:1680/{p4user}?ac=17',
subject_template = u'[{p4port} @{chgno}] {desc}',
change_template = u'''Change {chgno} by {p4user}@{p4client} on {dt}
{change_url}
{user_url}
{cldesc}
.
Jobs updated:
{jobsupdated}
.
Affected files:
{clfiles}
''',
html_change_template = u'''
<div style="font-family: sans-serif;">
Change <a style="text-decoration: none;" href="{change_url}">{chgno}</a>
by <a style="text-decoration: none;" href="{user_url}">{p4user}</a>@{p4client}
on {dt}
<br/>
<div style="margin: 1em;">{cldesc}</div>
<br/>
Jobs updated:
<ul style="margin: 1em; padding: 0; list-style-type: none;">
{jobsupdated}
</ul>
<br/>
Affected files:
<ul style="margin-left: 1em; padding: 0; list-style-type: none;">
{clfiles}
</ul>
</div>
''',
html_files_template = u'''<li style="margin:0; padding:0;">'''
u'''<a style="text-decoration: none;" href="{change_url}#{fhash}">'''
u'''{dfile}</a>#{drev} {action}</li>''',
job_template = u'''{job_url}
{jobdesc}
''',
html_job_template = u'''
<a href="{job_url}">{Job}</a>
<dl>
{jobdesc}
</dl>''',
)
def true_or_false(x):
if x in "FALSE OFF DISABLED DISABLE 0".split():
return False
return True
def parse_args():
import copy
defaults = copy.deepcopy(DEFAULTS)
confp = argparse.ArgumentParser(
add_help=False # Turn off help, so -h works with the 2nd parser below
)
confp.add_argument("-c", "--config-file")
args0, remaining_argv = confp.parse_known_args()
if args0.config_file:
if not os.path.exists(args0.config_file):
log.fatal(
"{0} does not exists! See --sample-config.".format(args0.config_file)
)
sys.exit(1)
cfgp = ConfigParser(allow_no_value=True)
cfgp.read([args0.config_file])
cfg = dict(
[
[unicode(y, "utf8", "replace") for y in x]
for x in cfgp.items(CFG_SECTION_NAME)
]
)
# now this is annoying - have to convert int(?) and bool types manually...
for (
key
) in "sample_config summary_email debug_email precached skip_author".split():
cfg[key] = true_or_false(cfg.get(key))
for key in "max_length max_emails max_email_size poll_interval".split():
if key in cfg:
cfg[key] = int(
cfg.get(key)
) # NOTE: float values cannot be used in list
# slicing notations!
# Convert the string value back into an array
cfg["ignored_users"] = [x.strip() for x in cfg["ignored_users"].split(",")]
for k in defaults:
if k in cfg:
defaults[k] = cfg.get(k)
# Allow admins to disable change/job review in the configuration file by setting the strings below
if defaults.get("review_counter", "").upper() in (
"FALSE",
"0",
"NONE",
"DISABLED",
"DISABLE",
"OFF",
):
defaults["review_counter"] = None
if defaults.get("job_counter", "").upper() in (
"FALSE",
"0",
"NONE",
"DISABLED",
"DISABLE",
"OFF",
):
defaults["job_counter"] = None
ap = argparse.ArgumentParser(
description="Perforce review daemon, take 2.",
parents=[confp], # inherit options
epilog="""Please send questions and comments via http://about.me/lestercheung. Share and enjoy!""",
)
ap.set_defaults(**defaults)
ap.add_argument(
"--sample-config",
action="store_true",
default=False,
help="output sample config with defaults",
)
ap.add_argument("-L", "--log-file", help="log file (optional)")
ap.add_argument(
"-f",
"--force",
action="store_true",
default=False,
help="continue even lock or output files exists",
)
ap.add_argument("--daemon", help="start/stop/restart")
ap.add_argument(
"--pid-file", help="stores the pid of the running p4review2 process"
)
ap.add_argument("--daemon-poll-delay", type=float, help="seconds between each poll")
debug = ap.add_argument_group("debug")
_ = "DEBUG/INFO/WARN/ERROR/FATAL"
debug.add_argument(
"--debug-level",
choices=_.split('/'),
metavar=defaults.get('debug_level'),
help=_,
)
debug.add_argument(
"-D",
"--dbfile",
metavar=defaults.get("dbfile"),
help="name of a temp SQLite3 DB file",
)
debug.add_argument(
"--precached",
action="store_true",
default=False,
help="data already in dbfile, not fetching from Perforce",
)
p4 = ap.add_argument_group("perforce")
p4.add_argument(
"-p", "--p4port", type=str, metavar=defaults.get("p4port"), help="Perforce port"
)
p4.add_argument(
"-u",
"--p4user",
type=str,
metavar=defaults.get("p4user"),
help="Perforce review user",
)
p4.add_argument(
"-r",
"--review-counter",
metavar=defaults.get("review_counter"),
help="name of review counter",
)
p4.add_argument(
"-j",
"--job-counter",
metavar=defaults.get("job_counter"),
help="name of job counter",
)
p4.add_argument(
"-J",
"--job-datefield",
metavar=defaults.get("job_datefield"),
help="""A job field used to determine which jobs
users are notified of changes to. This field needs
to appear in your jobspec as a "date" field with
persistence "always". See "p4 help jobspec" for
more information.""",
)
p4.add_argument(
"-s",
"--spec-depot",
metavar=defaults.get("spec_depot"),
help="name of spec depot",
)
p4.add_argument(
"-O",
"--timeoffset",
type=float,
help="time offset (in hours) between Perforce server and server running this script",
)
p4.add_argument(
"-C",
"--p4charset",
metavar=defaults.get("p4charset"),
help="used to handle non-unicode server with non-ascii chars",
)
p4.add_argument(
"-o",
"--opt-in-path", # metavar=defaults.get('opt_in_path'),
help="""depot path to include in the "Review" field of user spec to opt-in review emails""",
)
p4.add_argument(
"-i",
"--ignored-users",
action="append",
help="never send any email notification to the following users",
)
m = ap.add_argument_group("email")
m.add_argument(
"--smtp",
metavar=defaults.get("smtp_server"),
help="SMTP server in host:port format. See smtp_ssl in config for SSL options.",
)
m.add_argument(
"-S",
"--default-sender",
metavar=defaults.get("default_sender"),
help="default sender email",
)
m.add_argument(
"-d",
"--default-domain",
metavar=defaults.get("default_domain"),
help="default domain to qualify email address without domain",
)
m.add_argument(
"-1",
"--summary-email",
action="store_true",
default=False,
help="send one email per user",
)
m.add_argument(
"--skip-author",
type=true_or_false,
metavar=defaults.get("skip_author"),
help="whether to send email to changelist author",
)
m.add_argument(
"-l",
"--max-length",
type=int,
metavar=defaults.get("max_length"),
help="limit length of data in different places",
)
m.add_argument(
"-m",
"--max-emails",
type=int,
metavar=defaults.get("max_emails"),
help="maximum number of emails to be sent",
)
m.add_argument(
"-M",
"--max-email-size",
type=int,
metavar=defaults.get("max_email_size"),
help="maximum size of email messages (in bytes)",
)
m.add_argument(
"-P",
"--debug-email",
action="store_true",
default=False,
help="print, instead of sending email",
)
m.add_argument(
"--change-url",
metavar=defaults.get("change_url"),
help="URL template to a change",
)
m.add_argument(
"--job-url", metavar=defaults.get("job_url"), help="URL template to a job"
)
m.add_argument(
"--user-url", metavar=defaults.get("user_url"), help="URL template to a user"
)
m.add_argument(
"--subject-template",
metavar="'{}'".format(defaults.get("subject_template")),
help="customize subject line in one-email-per-change-mode",
)
args = ap.parse_args(remaining_argv)
if "cfgp" in locals().keys():
# we have a config parser defined, meaning we are reading from a config file
args.config_file = args0.config_file
if (
set(DEFAULTS.keys()) != set(cfgp.options(CFG_SECTION_NAME))
and not args.sample_config
):
log.fatal(
'There are changes in the configuration, please run "{} --sample-config -c <confile>" to generate a new one!'.format(
sys.argv[0]
)
)
sys.exit(1)
args.smtp_ssl = args.smtp_ssl.upper()
return args
class P4CLI(object):
"""Poor mans's implementation of P4Python using P4
CLI... just enough to support p4review2.py.
"""
charset = None # P4CHARSET
encoding = "utf8" # default encoding
input = None # command input
array_key_regex = re.compile(r"^(\D*)(\d*)$") # depotFile0, depotFile1...
tempfiles = []
def __init__(self):
self.user = self.env("P4USER")
self.port = self.env("P4PORT")
self.client = self.env("P4CLIENT")
if self.env("P4CHARSET") == "none":
self.charset = None # you *can* have "P4CHARSET=none" in your config...
def __repr__(self):
return "<P4CLI({u}@{c} on {p})>".format(u=self.user, c=self.client, p=self.port)
def __del__(self):
"""cleanup """
for f in self.tempfiles:
os.unlink(f)
def __getattr__(self, name):
if name.startswith("run"):
p4cmd = None
if name.startswith("run_"):
p4cmd = name[4:]
def p4runproxy(*args): # stubs for run_*() functions
cmd = self.p4pipe
if p4cmd: # command is in the argument for calls to run()
cmd += [p4cmd]
if type(args) == tuple or type(args) == list:
for arg in args:
if type(arg) == list:
cmd.extend(arg)
else:
cmd.append(arg)
else:
cmd += [args]
cmd = [str(x) for x in cmd]
if self.input:
tmpfd, tmpfname = tempfile.mkstemp()
self.tempfiles.append(tmpfname)
fd = open(tmpfname, "rb+")
m = marshal.dump(self.input, fd, 0)
fd.seek(0)
p = Popen(cmd, stdin=fd, stdout=PIPE)
else:
p = Popen(cmd, stdout=PIPE)
rv = []
while 1:
try:
rv.append(marshal.load(p.stdout))
except EOFError:
break
except Exception:
log.error("Unknown error while demarshaling data from server.")
log.error(" ".join(cmd))
break
p.stdout.close()
# log.debug(pformat(rv)) # raw data b4 decoding
self.input = None # clear any inputs after each p4 command
rv2 = [] # actual array that we will return
# magic to turn 'fieldNNN' into an array with key 'field'
for r in rv: # rv is a list if dictionaries
r2 = {}
fields_needing_sorting = set()
for key in r:
decoded_key = key
if PY3 and type(decoded_key) == bytes:
decoded_key = decoded_key.decode(self.encoding)
val = r[key]
if PY3 and type(val) == bytes:
val = val.decode(self.charset or self.encoding or "utf8")
regexmatch = self.array_key_regex.match(decoded_key)
if not regexmatch: # re.match may return None
continue
k, num = regexmatch.groups()
if num: # key in 'filedNNN' form.
v = r2.get(k, [])
if type(v) == str:
v = [v]
v.append(val)
r2[k] = v
else:
r2[k] = val
rv2.append(r2)
# log.debug(pformat(rv2)) # data after decoding
return rv2
return p4runproxy
elif name in "connect disconnect".split():
return self.noop
elif name in "p4pipe".split():
cmd = [self.p4bin] + shlex.split(
'-G -p "' + self.port + '" -u ' + self.user + " -c " + self.client
)
if self.charset:
cmd += ["-C", self.charset]
return cmd
else:
raise AttributeError("'P4CLI' object has no attribute '{}'".format(name))
def identify(self):
return "P4CLI, using " + self.p4bin
def connected(self):
return True
def run_login(self, *args):
cmd = self.p4pipe + ["login"]
if "-s" in args:
cmd += ["-s"]
proc = Popen(cmd, stdout=PIPE)
out = proc.communicate()[0]
if marshal.loads(out).get("code") == "error":
raise Exception("P4CLI exception - not logged in.")
else:
proc = Popen(cmd, stdin=PIPE, stdout=PIPE)
out = proc.communicate(input=self.password)[0]
out = "\n".join(out.splitlines()[1:]) # Skip the password prompt...
return [marshal.loads(out)]
def env(self, key):
rv = check_output([self.p4bin, "set", key]).decode("utf8")
rv = rv.split(" (config)")[0]
rv = rv.split(" (set)")[0]
rv = rv.split(
"=", 1
) # don't use the keyword "maxsplit" as it will bring in Python2
if len(rv) != 2:
rv = None
else:
rv = rv[1]
if not rv:
if key == "P4USER":
from getpass import getuser
rv = getuser()
elif key == "P4CLIENT":
from socket import gethostname
rv = gethostname()
elif key == "P4PORT":
rv = "perforce:1666"
return rv
def noop(*args, **kws):
pass # stub - it's a class method which returns None.
def run_plaintext(self, *args):
"""Run P4 commands normally and return the outputs in plaintext"""
cmd = shlex.split(
"""{bin} -p "{p4port}" -u {p4user} -c {p4client}""".format(
bin=self.p4bin, p4port=self.port, p4user=self.user, p4client=self.client
)
) + list(args)
rv = check_output(cmd)
if PY3 and type(rv) == bytes:
rv = rv.decode(self.charset or self.encoding or "utf8")
return rv
class UnixDaemon(object):
"""
A generic daemon class.
Usage: subclass the Daemon class and override the run() method
Source:
http://www.jejik.com/files/examples/daemon.py
Reference:
http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
"""
def __init__(
self, pidfile, stdin="/dev/null", stdout="/dev/null", stderr="/dev/null"
):
self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
self.pidfile = pidfile
def daemonize(self):
"""
Do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
# exit first parent
# sys.stderr.write('forked %d.\n' % pid)
sys.exit(0)
except OSError as e:
sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as e:
sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = file(self.stdin, "r")
so = file(self.stdout, "a+")
se = file(self.stderr, "a+", 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# write pidfile
atexit.register(self.delpid)
pid = str(os.getpid())
file(self.pidfile, "w+").write("%s\n" % pid)
def delpid(self):
os.remove(self.pidfile)
def start(self):
"""
Start the daemon
"""
# Check for a pidfile to see if the daemon already runs
try:
pf = file(self.pidfile, "r")
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if pid:
message = "pidfile %s already exist. Daemon already running?\n"
sys.stderr.write(message % self.pidfile)
sys.exit(1)
# Start the daemon
self.daemonize()
self.run()
def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile, "r")
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile %s does not exist. Daemon not running?\n"
sys.stderr.write(message % self.pidfile)
return # not an error in a restart
# Try killing the daemon process
try:
while 1:
os.kill(pid, SIGTERM)
time.sleep(0.1)
except OSError as err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print(str(err))
sys.exit(1)
def restart(self):
"""
Restart the daemon
"""
self.stop()
self.start()
def run(self):
"""
You should override this method when you subclass Daemon. It will be called after the process has been
daemonized by start() or restart().
"""
pass
class P4ReviewDaemon(UnixDaemon):
def __init__(self, cfg, stdin="/dev/null", stdout="/dev/null", stderr="/dev/null"):
super(P4ReviewDaemon, self).__init__(
cfg.pid_file, stdin=stdin, stdout=stdout, stderr=stderr
)
def run(self):
"""Run P4Review in a loop with a delay"""
while 1:
p4review = P4Review(cfg)
p4review.run()
time.sleep(cfg.poll_interval)
class P4Review(object):
# textwrapper - indented with 1 tab
txtwrpr_indented = TextWrapper(initial_indent="\n\t", subsequent_indent="\t")
sqlsep = "___" # separator used in sql group_concat() function
dtfmt = "%Y/%m/%d:%H:%M:%S" # for jobreview counter
html_templ = u"""<html><body>{body}</body></html>"""
subscribed = {} # keyed by user, whether the user opts-in for review emails
mail_sent = 0 # keep track of number of mails sent
def __init__(self, cfg):
if cfg.daemon:
if os.path.exists(cfg.pid_file):
pid = None
try:
pid = int(open(cfg.pid_file).read().strip())
except:
log.error(
"{} exists but does not contain a valid pid. Bailing...".format(
cfg.pid_file
)
)
sys.exit(1)
if pid != os.getpid():
log.error(
"Another p4review2 process (pid {}) is running! Bailing...".format(
pid
)
)
sys.exit(1)
else: # one-shot-mode
if cfg.force and os.path.exists(cfg.pid_file):
log.info("Removing {} on request (-f)".format(cfg.pid_file))
os.unlink(cfg.pid_file)
if cfg.force and not cfg.precached and os.path.exists(cfg.dbfile):
log.info("Removing {} on request (-f)".format(cfg.dbfile))
os.unlink(cfg.dbfile)
if os.path.exists(cfg.pid_file):
log.error("Lock file ({}) exists! Bailing...".format(cfg.pid_file))
sys.exit(1)
with open(cfg.pid_file, "w") as fd:
fd.write("{}\n".format(os.getpid()))
self.cfg = cfg
self.default_name, self.default_email = email.utils.parseaddr(
cfg.default_sender
)
p4 = P4()
p4.prog = "P4Review2"
p4.port = cfg.p4port
p4.user = cfg.p4user
p4.connect()
logged_in = False
try:
rv = p4.run_login("-s")
logged_in = True
except Exception as e:
pass
log.debug("logged in: " + str(logged_in))
if not logged_in and cfg.p4passwd:
p4.password = str(cfg.p4passwd)
p4.run_login()
if p4.run_info()[0].get("unicode") == "enabled":
p4.charset = str(self.cfg.p4charset)
self.p4 = p4 # keep a reference for future use
db = sqlite3.connect(
cfg.dbfile, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES
)
sqlite3.register_converter("spec", self.convert_spec)
self.db = db
if not cfg.precached:
sqls = """
CREATE TABLE chg (chgno INTEGER PRIMARY KEY, pickle spec);
CREATE TABLE job (job PRIMARY KEY, pickle spec);
CREATE TABLE usr (usr PRIMARY KEY, name, email);
CREATE TABLE rvw (chgno INTEGER, usr, UNIQUE(chgno, usr));
CREATE TABLE jbrvw (job, usr, UNIQUE(job, usr));
CREATE VIEW rvws AS SELECT usr.usr, group_concat(chgno, '{sep}') AS chgnos FROM usr LEFT JOIN rvw ON usr.usr = rvw.usr GROUP BY usr.usr;
CREATE VIEW jbrvws AS SELECT usr.usr, group_concat(job, '{sep}') AS jobs FROM usr LEFT JOIN jbrvw ON usr.usr = jbrvw.usr GROUP BY usr.usr;
""".format(
sep=self.sqlsep
)
db.executescript(sqls)
db.commit()
self.started = datetime.now() # mark the timestamp for jobreview counter
log.info("App (pid={}) initiated.".format(os.getpid()))
def convert_spec(self, s):
"""Convert a pickled server specification to a dictionary with unicode values."""
d = loads(s)
rv = {}
for k in d:
if type(d[k]) == str:
rv[k] = self.unicode(d[k])
elif type(d[k]) == list:
rv[k] = map(self.unicode, d[k])
else:
rv[k] = d[k]
return rv
def pull_data_from_p4(self):
p4 = self.p4
cux = self.db.cursor()
if self.cfg.opt_in_path:
reviewers = p4.run_reviews(self.cfg.opt_in_path)
if not reviewers:
log.debug("No one is subscribed to {}.".format(self.cfg.opt_in_path))
return # return early if no one is subscribed to notification
for rv in reviewers:
self.subscribed[rv["user"]] = True
if self.cfg.review_counter:
review_counter = p4.run_counter(self.cfg.review_counter)[0]["value"]
if review_counter == "0" and not self.cfg.force:
msg = """Review counter ({rc}) is unset. Either re-run the script with -f option or run "p4 counter {rc}" to set it."""
self.bail(msg.format(rc=self.cfg.review_counter))
try:
review_counter = int(review_counter)
except:
msg = """Review counter ({}) is invalid. Run "p4 counter" to correct it."""
self.bail(msg.format(self.cfg.review_counter))
log.info(
"Review counter ({}): {}".format(
self.cfg.review_counter, review_counter
)
)
log.info("Scraping for change review...")
rv = p4.run_review(["-t", self.cfg.review_counter])
log.debug("{} change(s)".format(len(rv)))
jobnames = set() # so that we can pull data lazily.
for rvw in rv:
chgno = rvw.get("change")
p4user = self.unicode(rvw.get("user"))
name = self.unicode(rvw.get("name"))
email = self.unicode(rvw.get("email"))
sql = (
"""INSERT OR IGNORE INTO usr (usr, name, email) values (?, ?, ?)"""
)
cux.execute(sql, (p4user, name, email))
# who wants to get spammed?
rvwers = p4.run_reviews(["-c", chgno])