/
pony_client.py
1069 lines (810 loc) · 33.5 KB
/
pony_client.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
"""
Client library + simple command-line script for pony-build.
See http://github.com/ctb/pony-build/.
"""
import sys
import subprocess
import xmlrpclib
import tempfile
import shutil
import os, os.path
import time
import urlparse
import urllib
import traceback
from optparse import OptionParser
import pprint
import glob
import datetime
import signal
pb_servers = {
'pb-dev' : 'http://lyorn.idyll.org/ctb/pb-dev/',
'local' : 'http://localhost:8000/'
}
pb_servers['default'] = pb_servers['pb-dev']
###
DEBUG_LEVEL = 5
INFO_LEVEL = 3
WARNING_LEVEL = 2
CRITICAL_LEVEL = 1
_log_level = WARNING_LEVEL
def log_debug(*args):
log(DEBUG_LEVEL, *args)
def log_info(*args):
log(INFO_LEVEL, *args)
def log_warning(*args):
log(WARNING_LEVEL, *args)
def log_critical(*args):
log(CRITICAL_LEVEL, *args)
def log(level, *what):
if level <= _log_level:
sys.stdout.write(" ".join([ str(x) for x in what]) + "\n")
def set_log_level(level):
global _log_level
_log_level = level
###
DEFAULT_CACHE_DIR='~/.pony-build'
def guess_cache_dir(dirname):
"""Return the full path of the VCS cache directory for the given pkg."""
parent = os.environ.get('PONY_BUILD_CACHE', DEFAULT_CACHE_DIR)
parent = os.path.expanduser(parent)
result = os.path.join(parent, dirname)
return (parent, result)
def create_cache_dir(cache_dir, dirname):
# trim the pkg name so we can create the main cache_dir and not the
# repo dir. I believe it has to be done this way to handle different
# user PATH setup (OS's, custom stuff etc)
# @CTB can't we use os.path.split here, instead?
# @CTB refactor create_cache_dir to check to see if it exists, maybe?
pkglen = len(dirname)
cache_dir = cache_dir[:-pkglen]
if os.path.isdir(cache_dir):
log_info('VCS cache_dir %s exists already!' % cache_dir)
else:
try:
log_info('created new VCS cache dir: %s' % cache_dir)
os.mkdir(cache_dir)
except OSError:
log_critical('Unable to create VCS cache_dir: %s' % cache_dir)
raise
###
def _replace_variables(cmd, variables_d):
if cmd.startswith('PB:'):
cmd = variables_d[cmd[3:]]
return cmd
def _run_command(command_list, cwd=None, variables=None, extra_kwargs={},
verbose=False):
if variables:
x = []
for cmd in command_list:
cmd = _replace_variables(cmd, variables)
x.append(cmd)
command_list = x
default_kwargs = dict(shell=False, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if extra_kwargs:
default_kwargs.update(extra_kwargs)
log_debug('_run_command cwd', os.getcwd())
log_debug('_run_command running in ->', cwd)
log_debug('_run_command command list:', command_list)
log_debug('_run_command default kwargs:', default_kwargs)
try:
p = subprocess.Popen(command_list, cwd=cwd, **default_kwargs)
out, err = p.communicate()
ret = p.returncode
except:
out = ''
err = traceback.format_exc()
ret = -1
log_debug('_run_command status', str(ret))
log_debug('_run_command stdout', out)
log_debug('_run_command stderr', err)
return (ret, out, err)
class FileToUpload(object):
def __init__(self, filename, location, description, visible):
"""
filename - name to publish as
location - full location on build system (not sent to server)
description - brief description of file/arch for server
"""
self.data = open(location, 'rb').read()
self.filename = filename
self.description = description
self.visible = visible
def __repr__(self):
return "<FileToUpload('%s', '%s')>" % (self.filename,
self.description)
class Context(object):
def __init__(self):
self.history = []
self.start_time = self.end_time = None
self.build_dir = None
self.files = []
def initialize(self):
self.start_time = time.time()
def finish(self):
self.end_time = time.time()
def start_command(self, command):
if self.build_dir:
os.chdir(self.build_dir)
def end_command(self, command):
self.history.append(command)
def update_client_info(self, info):
info['duration'] = self.end_time - self.start_time
def add_file_to_upload(self, name, location, description, visible):
o = FileToUpload(name, location, description, visible)
self.files.append(o)
class TempDirectoryContext(Context):
def __init__(self, cleanup=True):
Context.__init__(self)
self.cleanup = cleanup
def initialize(self):
Context.initialize(self)
self.tempdir = tempfile.mkdtemp()
self.cwd = os.getcwd()
log_info('changing to temp directory:', self.tempdir)
os.chdir(self.tempdir)
def finish(self):
os.chdir(self.cwd)
try:
Context.finish(self)
finally:
if self.cleanup:
log_info('removing', self.tempdir)
shutil.rmtree(self.tempdir, ignore_errors=True)
def update_client_info(self, info):
Context.update_client_info(self, info)
info['tempdir'] = self.tempdir
class VirtualenvContext(Context):
"""
A context that works within a new virtualenv.
VirtualenvContext works by modifying the path to the Python executable.
"""
def __init__(self, always_cleanup=True, dependencies=[], optional=[],
python='python', include_site_packages=False):
Context.__init__(self)
self.cleanup = always_cleanup
self.dependencies = dependencies
self.optional = optional # optional dependencies
self.python = python
# Create the virtualenv. Have to do this here so that commands can use
# VirtualenvContext.python (etc) to get at the right python.
import virtualenv
self.tempdir = tempfile.mkdtemp()
log_info('creating virtualenv')
cmdlist = list([python, '-m', 'virtualenv'])
if not include_site_packages:
cmdlist.append('--no-site-packages')
cmdlist.append(self.tempdir)
(ret, out, err) = _run_command(cmdlist)
if ret != 0:
raise Exception("error in running virtualenv: %s, %s" % (out, err))
# calculate where a few things live so we can easily shell out to 'em
bindir = os.path.join(self.tempdir, 'bin')
self.python = os.path.join(bindir, 'python')
self.easy_install = os.path.join(bindir, 'easy_install')
self.pip = os.path.join(bindir, 'pip')
os.environ['PATH'] = bindir + os.pathsep + os.environ['PATH']
log_debug("modified PATH to include virtualenv bindir: '%s'" % bindir)
def initialize(self):
Context.initialize(self)
log_info('changing to temp directory:', self.tempdir)
self.cwd = os.getcwd()
os.chdir(self.tempdir)
# install pip, then use it to install any packages desired
log_info('installing pip')
(ret, out, err) = _run_command([self.easy_install, '-U', 'pip'])
if ret != 0:
raise Exception("error in installing pip: %s, %s" % (out, err))
for dep in self.dependencies:
log_info('installing dependency:', dep)
(ret, out, err) = _run_command([self.pip, 'install', '-U', '-I',
dep])
if ret != 0:
raise Exception("pip cannot install req dependency: %s" % dep)
for dep in self.optional:
log_info("installing optional dependency:", dep)
(ret, out, err) = _run_command([self.pip, 'install', '-U', '-I',
dep])
# @CTB should record failed installs of optional packages
# to client?
if ret != 0:
log_warning("pip cannot install optional dependency: %s" % dep)
def finish(self):
os.chdir(self.cwd)
try:
Context.finish(self)
finally:
if self.cleanup:
log_info("VirtualenvContext: removing", self.tempdir)
shutil.rmtree(self.tempdir, ignore_errors=True)
def update_client_info(self, info):
Context.update_client_info(self, info)
info['tempdir'] = self.tempdir
info['virtualenv'] = True
info['dependencies'] = self.dependencies
info['optional'] = self.optional
class UploadAFile(object):
"""
A build command that arranges to upload a specific file to the server.
@CTB add glob support!
"""
def __init__(self, filepath, public_name, description, visible=True):
self.filepath = os.path.realpath(filepath)
self.public_name = public_name
self.description = description
self.visible = visible
def success(self):
return os.path.exists(self.filepath)
def run(self, context):
context.add_file_to_upload(self.public_name, self.filepath,
self.description, self.visible)
def get_results(self):
try:
filesize = os.path.getsize(self.filepath)
except OSError:
filesize = -1
results = dict(type='file_upload',
description=self.description,
filesize=filesize,
errout="", # @CTB should be unnecessary!
status=0) # @CTB should be unnecessary!
return results
class BaseCommand(object):
def __init__(self, command_list, name='', run_cwd=None,
subprocess_kwargs=None, ignore_failure=False):
self.command_list = command_list
if name:
self.command_name = name
self.run_cwd = run_cwd
self.status = None
self.output = None
self.errout = None
self.duration = None
self.variables = None
self.subprocess_kwargs = {}
if subprocess_kwargs:
self.subprocess_kwargs = dict(subprocess_kwargs)
self.ignore_failure = ignore_failure
def __repr__(self):
return "%s (%s)" % (self.command_name, self.command_type)
def set_variables(self, v):
self.variables = dict(v)
def run(self, context):
start = time.time()
(ret, out, err) = _run_command(self.command_list, cwd=self.run_cwd,
variables=self.variables,
extra_kwargs=self.subprocess_kwargs)
self.status = ret
self.output = out
self.errout = err
end = time.time()
self.duration = end - start
def success(self):
return self.ignore_failure or (self.status == 0)
def get_results(self):
results = dict(status=self.status,
output=self.output,
errout=self.errout,
command=str(self.command_list),
type=self.command_type,
name=self.command_name,
duration=self.duration)
return results
class SetupCommand(BaseCommand):
command_type = 'setup'
command_name = 'setup'
class BuildCommand(BaseCommand):
command_type = 'build'
command_name = 'build'
class TestCommand(BaseCommand):
command_type = 'test'
command_name = 'test'
class CopyLocalDir(BuildCommand):
def __init__(self, fromdir, to_name):
self.ignore_failure = False
self.fromdir = fromdir
self.to_name = to_name
self.results_dict = dict(fromdir=fromdir, to_name=to_name)
def run(self, context):
self.results_dict['out'] = self.results_dict['errout'] = ''
try:
shutil.copytree(self.fromdir, self.to_name)
context.build_dir = os.path.join(os.getcwd(), 'Caper')
self.status = 0
except Exception, e:
self.errout = str(e)
self.status = 1
def get_results(self):
self.results_dict['status'] = self.status
self.results_dict['type'] = self.command_type
self.results_dict['name'] = self.command_name
return self.results_dict
class PythonPackageEgg(BaseCommand):
command_type = 'package'
command_name = 'package_egg'
def __init__(self, python_exe='python'):
BaseCommand.__init__(self, [python_exe, 'setup.py', 'bdist_egg'],
name='build an egg')
def run(self, context):
BaseCommand.run(self, context)
if self.status == 0: # success?
eggfiles = os.path.join('dist', '*.egg')
eggfiles = glob.glob(eggfiles)
for filename in eggfiles:
context.add_file_to_upload(os.path.basename(filename),
filename,
'an egg installation file',
visible=True)
class _VersionControlClientBase(SetupCommand):
"""
Base class for version control clients.
Subclasses should define:
- get_dirname()
- update_repository()
- create_repository(url, dirname, step='stepname')
- record_repository_info(dirname)
and optionally override 'get_results()'.
"""
def __init__(self, use_cache=True, **kwargs):
SetupCommand.__init__(self, [], **kwargs)
self.use_cache = use_cache
self.duration = -1
self.version_info = ''
self.results_dict = {}
def run(self, context):
# dirname is the directory created by a succesful checkout.
dirname = self.get_dirname()
# cwd is the directory we're going to ultimately put dirname under.
cwd = os.getcwd()
# NOTE: we flat out don't like the situation where the
# directory already exists. Force a clean checkout.
assert not os.path.exists(dirname)
if self.use_cache:
# 'repo_dir' is the full cache directory containing the repo.
# this will be something like '~/.pony-build/<dirname>'.
#
# 'cache_dir' is the parent dir.
cache_dir, repo_dir = guess_cache_dir(dirname)
# does the repo already exist?
if os.path.exists(repo_dir): # YES
os.chdir(repo_dir)
log_info('changed to: ', repo_dir, 'to do fetch.')
self.update_repository()
else: # NO
# do a clone to create the repo dir
log_info('changing to: ' + cache_dir + ' to make new repo dir')
os.chdir(cache_dir)
self.create_repository(self.repository, dirname,
step='create cache')
assert os.path.isdir(repo_dir)
os.chdir(cwd)
log_info('Using the local cache at %s for cloning' % repo_dir)
location = repo_dir
else:
location = self.repository
self.create_repository(location, dirname, step='clone')
if not os.path.exists(dirname) and os.path.isdir(dirname):
log_critical('wrong guess; %s does not exist. whoops' % (dirname,))
raise Exception
# get some info on what our repository version is
self.record_repository_info(dirname)
# record the build directory, too.
context.build_dir = os.path.join(os.getcwd(), dirname)
# signal success!
self.status = 0
def get_results(self):
self.results_dict['out'] = self.results_dict['errout'] = ''
self.results_dict['status'] = self.status
self.results_dict['type'] = self.command_type
self.results_dict['name'] = self.command_name
return self.results_dict
class GitClone(_VersionControlClientBase):
"""Check out and/or update a git repository."""
command_name = 'checkout'
def __init__(self, repository, branch='master', use_cache=True, **kwargs):
_VersionControlClientBase.__init__(self, use_cache=use_cache, **kwargs)
self.repository = repository
self.branch = branch
def get_dirname(self):
"Calculate the directory name resulting from a successful checkout."
p = urlparse.urlparse(self.repository)
path = p[2] # urlparse -> path
dirname = path.rstrip('/').split('/')[-1]
if dirname.endswith('.git'):
dirname = dirname[:-4]
log_info('git checkout dirname guessed as: %s' % (dirname,))
return dirname
def update_repository(self):
branchspec = '%s:%s' % (self.branch, self.branch)
cmdlist = ['git', 'fetch', '-ufv', self.repository, branchspec]
print '***', cmdlist
(ret, out, err) = _run_command(cmdlist)
self.results_dict['cache_update'] = dict(status=ret, output=out,
errout=err,
command=str(cmdlist))
if ret != 0:
raise Exception("cannot update cache: %s" % repo_dir)
cmdlist = ['git', 'checkout', '-f', self.branch]
(ret, out, err) = _run_command(cmdlist)
self.results_dict['cache_checkout_head'] = dict(status=ret, output=out,
errout=err,
command=str(cmdlist))
if ret != 0:
raise Exception("cannot reset cache: %s" % repo_dir)
def create_repository(self, url, dirname, step='clone'):
cmdlist = ['git', 'clone', url]
(ret, out, err) = _run_command(cmdlist)
self.results_dict[step] = dict(status=ret, output=out, errout=err,
command=str(cmdlist))
if ret != 0:
cwd = os.getcwd()
raise Exception("cannot clone repository %s in %s" % (url, cwd))
if self.branch != 'master':
# fetch the right branch
branchspec = '%s:%s' % (self.branch, self.branch)
cmdlist = ['git', 'fetch', '-ufv', self.repository, branchspec]
(ret, out, err) = _run_command(cmdlist, dirname)
assert ret == 0, (out, err)
# check out the right branch
cmdlist = ['git', 'checkout', '-f', self.branch]
(ret, out, err) = _run_command(cmdlist, dirname)
assert ret == 0, (out, err)
def record_repository_info(self, repo_dir):
cmdlist = ['git', 'log', '-1', '--pretty=oneline']
(ret, out, err) = _run_command(cmdlist, repo_dir)
assert ret == 0, (cmdlist, ret, out, err)
self.version_info = out.strip()
def get_results(self):
# first, update basic
_VersionControlClientBase.get_results(self)
self.results_dict['version_type'] = 'git'
if self.version_info:
self.results_dict['version_info'] = self.version_info
self.results_dict['command'] = 'GitClone(%s, %s)' % (self.repository,
self.branch)
return self.results_dict
class HgClone(_VersionControlClientBase):
"""Check out or update an Hg (Mercurial) repository."""
command_name = 'checkout'
def __init__(self, repository, branch='default', use_cache=True, **kwargs):
_VersionControlClientBase.__init__(self, use_cache=use_cache, **kwargs)
self.repository = repository
self.branch = branch
assert branch == 'default'
def get_dirname(self):
"Calculate the directory name resulting from a successful checkout."
p = urlparse.urlparse(self.repository)
path = p[2] # urlparse -> path
dirname = path.rstrip('/').split('/')[-1]
log_info('hg checkout dirname guessed as: %s' % (dirname,))
return dirname
def update_repository(self):
cmdlist = ['hg', 'pull', self.repository]
(ret, out, err) = _run_command(cmdlist)
self.results_dict['cache_pull'] = dict(status=ret, output=out,
errout=err,
command=str(cmdlist))
if ret != 0:
raise Exception, "cannot pull from %s" % self.repository
cmdlist = ['hg', 'update', '-C']
(ret, out, err) = _run_command(cmdlist)
self.results_dict['cache_update'] = \
dict(status=ret, output=out, errout=err,
command=str(cmdlist))
assert ret == 0, (out, err)
def create_repository(self, url, dirname, step='clone'):
cmdlist = ['hg', 'clone', url]
(ret, out, err) = _run_command(cmdlist)
self.results_dict[step] = dict(status=ret, output=out, errout=err,
command=str(cmdlist))
if ret != 0:
cwd = os.getcwd()
raise Exception("cannot clone repository %s in %s" % (url, cwd))
if self.branch != 'default':
# update to the right branch
branchspec = '%s:%s' % (self.branch, self.branch)
cmdlist = ['hg', 'update', branchspec]
(ret, out, err) = _run_command(cmdlist, dirname)
assert ret == 0, (out, err)
def record_repository_info(self, repo_dir):
# get some info on what our HEAD is
cmdlist = ['hg', 'id', '-nib']
(ret, out, err) = _run_command(cmdlist, repo_dir)
assert ret == 0, (cmdlist, ret, out, err)
self.version_info = out.strip()
def get_results(self):
# first, update basic
_VersionControlClientBase.get_results(self)
self.results_dict['command'] = 'HgCheckout(%s, %s)' % (self.repository,
self.branch)
self.results_dict['version_type'] = 'hg'
if self.version_info:
self.results_dict['version_info'] = self.version_info
return self.results_dict
class SvnCheckout(_VersionControlClientBase):
"""Check out or update a subversion repository."""
command_name = 'checkout'
def __init__(self, dirname, repository, use_cache=True, **kwargs):
_VersionControlClientBase.__init__(self, use_cache=use_cache)
self.dirname = dirname
self.repository = repository
def get_dirname(self):
return self.dirname
def update_repository(self):
# adding '--accept', 'theirs-full' is a good idea for newer versions
# of svn; this automatically accepts dodgy security certs.
cmdlist = ['svn', 'update']
(ret, out, err) = _run_command(cmdlist)
self.results_dict['svn update'] = dict(status=ret, output=out,
errout=err,
command=str(cmdlist))
if ret != 0:
log_critical("cannot svn update")
raise Exception, (cmdlist, ret, out, err)
def create_repository(self, url, dirname, step='clone'):
if os.path.isdir(url): # local dir? COPY.
shutil.copytree(url, dirname)
else: # remote repo? CO.
cmdlist = ['svn', 'co', url, dirname]
(ret, out, err) = _run_command(cmdlist)
self.results_dict[step] = dict(status=ret, output=out, errout=err,
command=str(cmdlist))
if ret != 0:
log_critical("cannot svn checkout %s into %s" % (url, dirname))
raise Exception, "cannot svn checkout %s into %s" % (url, dirname)
def record_repository_info(self, repo_dir):
cmdlist = ['svnversion']
(ret, out, err) = _run_command(cmdlist, repo_dir)
assert ret == 0, (cmdlist, ret, out, err)
self.version_info = out.strip()
def get_results(self):
# first, update basic
_VersionControlClientBase.get_results(self)
self.results_dict['command'] = 'SvnCheckout(%s, %s)' %(self.repository,
self.dirname)
self.results_dict['version_type'] = 'hg'
if self.version_info:
self.results_dict['version_info'] = self.version_info
return self.results_dict
###
def get_hostname():
import socket
return socket.gethostname()
def get_arch():
import distutils.util
return distutils.util.get_platform()
###
def _send(server, info, results):
log_info('connecting to', server)
s = xmlrpclib.ServerProxy(server, allow_none=True)
(result_key, auth_key) = s.add_results(info, results)
return str(auth_key)
def _upload_file(server_url, fileobj, auth_key):
# @CTB make sure files can't be uploaded from elsewhere on system?
# @CTB hack hack
assert server_url.endswith('xmlrpc')
upload_url = server_url[:-6] + 'upload'
if fileobj.visible:
visible='yes'
else:
visible = 'no'
qs = urllib.urlencode(dict(description=fileobj.description,
filename=fileobj.filename,
auth_key=str(auth_key),
visible=visible))
upload_url += '?' + qs
try:
http_result = urllib.urlopen(upload_url, fileobj.data)
except:
log_warning('file upload failed:', str(fileobj))
log_warning(traceback.format_exc())
def do(name, commands, context=None, arch=None, stop_if_failure=True):
reslist = []
init_status = True
if context:
try:
context.initialize()
except:
init_status = False
if init_status:
for c in commands:
log_debug('running:', str(c))
if context:
context.start_command(c)
try:
c.run(context)
except:
break
if context:
context.end_command(c)
reslist.append(c.get_results())
if stop_if_failure and not c.success():
break
if context:
context.finish()
if arch is None:
arch = get_arch()
success = True
for c in commands:
if not c.success():
success = False
break
client_info = dict(package=name, arch=arch, success=success)
files_to_upload = None
if context:
context.update_client_info(client_info)
if context.files:
files_to_upload = context.files
return (client_info, reslist, files_to_upload)
def send(server_url, x, hostname=None, tags=()):
client_info, reslist, files_to_upload = x
if hostname is None:
import socket
hostname = socket.gethostname()
client_info['host'] = hostname
client_info['tags'] = tags
server_url = get_server_url(server_url)
log_info('using server URL:', server_url)
auth_key = _send(server_url, client_info, reslist)
if files_to_upload:
for fileobj in files_to_upload:
log_debug('uploading', str(fileobj))
_upload_file(server_url, fileobj, auth_key)
def check(name, server_url, tags=(), hostname=None, arch=None, reserve_time=0):
import socket
if hostname is None:
hostname = get_hostname()
if arch is None:
arch = get_arch()
client_info = dict(package=name, host=hostname, arch=arch, tags=tags)
server_url = get_server_url(server_url)
s = xmlrpclib.ServerProxy(server_url, allow_none=True)
try:
(flag, reason) = s.check_should_build(client_info, True, reserve_time)
except socket.error:
log_critical('cannot connect to pony-build server: %s' % server_url)
sys.exit(-1)
return flag
def get_server_url(server_name):
try_url = urlparse.urlparse(server_name)
if try_url[0]: # urlparse -> scheme
server_url = urlparse.urljoin(server_name, 'xmlrpc')
else: # not a URL?
server_temp = pb_servers[server_name]
server_url = urlparse.urljoin(server_temp, 'xmlrpc')
return server_url
def get_tagsets_for_package(server, package):
server = get_server_url(server)
s = xmlrpclib.ServerProxy(server, allow_none=True)
return s.get_tagsets_for_package(package)
###
def parse_cmdline(argv=[]):
cmdline = OptionParser()
cmdline.add_option('-f', '--force-build', dest='force_build',
action='store_true', default=False,
help="run a build whether or not it's stale")
cmdline.add_option('-n', '--no-report', dest='report',
action='store_false', default=True,
help="do not report build results to server")
cmdline.add_option('-N', '--no-clean-temp', dest='cleanup_temp',
action='store_false', default=True,
help='do not clean up the temp directory')
cmdline.add_option('-s', '--server-url', dest='server_url',
action='store', default='pb-dev',
help='set pony-build server URL for reporting results')
cmdline.add_option('-v', '--verbose', dest='verbose',
action='store_true', default=False,
help='set verbose reporting')
cmdline.add_option('--debug', dest='debug',
action='store_true', default=False,
help='set debug reporting')
cmdline.add_option('-e', '--python-executable', dest='python_executable',
action='store', default='python',
help='override the version of python used to build with')
cmdline.add_option('-t', '--tagset', dest='tagset',
action='store', default=[],
help='comma-delimited list of tags to be applied')
if not argv:
(options, args) = cmdline.parse_args()
else:
(options, args) = cmdline.parse_args(argv)
# parse the tagset
if options.tagset:
options.tagset = options.tagset.split(',')
# there should be nothing in args.
# if there is, print a warning, then crash and burn.
#if args:
# print "Error--unknown arguments detected. Failing..."
# sys.exit(0)
if options.verbose:
set_log_level(INFO_LEVEL)
if options.debug:
set_log_level(DEBUG_LEVEL)
if not options.report:
options.force_build = True
return options, args
###
class PythonVersionNotFound(Exception):
def __init__(self, python_exe):
self.python_exe = python_exe
def __str__(self):
return repr(self.python_exe + " not found on system.")
def get_python_version(python_exe='python'):
"""
Return the major.minor number for the given Python executable.
"""
cmd = python_exe + " -c \"import sys \nprint" \
" str(sys.version_info[0]) + '.' + str(sys.version_info[1])\""
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
(stdout, stderr) = p.communicate()
if not stdout:
raise PythonVersionNotFound(python_exe)
return stdout.strip()
###
def get_python_config(options, args):
if not len(args):
python_ver = 'python2.5'
else:
python_ver = args[0]
print 'setting python version:', python_ver
tags = [python_ver]
if len(args) > 1:
tags.extend(args[1:])
return dict(python_exe=python_ver, tags=tags)
# PYTHON: generic recipe elements
PYTHON_EXE = 'PB:python_exe'