-
Notifications
You must be signed in to change notification settings - Fork 240
/
utils.py
1476 lines (1166 loc) · 50.8 KB
/
utils.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
# Copyright 2015-2016 Yelp Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import contextlib
import copy
import datetime
import errno
import fcntl
import glob
import hashlib
import importlib
import io
import json
import logging
import math
import os
import pwd
import re
import shlex
import signal
import sys
import tempfile
import threading
from fnmatch import fnmatch
from functools import wraps
from subprocess import PIPE
from subprocess import Popen
from subprocess import STDOUT
import dateutil.tz
import docker
import service_configuration_lib
import yaml
from docker import Client
from docker.utils import kwargs_from_env
from kazoo.client import KazooClient
# DO NOT CHANGE SPACER, UNLESS YOU'RE PREPARED TO CHANGE ALL INSTANCES
# OF IT IN OTHER LIBRARIES (i.e. service_configuration_lib).
# It's used to compose a job's full ID from its name and instance
SPACER = '.'
INFRA_ZK_PATH = '/nail/etc/zookeeper_discovery/infrastructure/'
PATH_TO_SYSTEM_PAASTA_CONFIG_DIR = os.environ.get('PAASTA_SYSTEM_CONFIG_DIR', '/etc/paasta/')
DEFAULT_SOA_DIR = service_configuration_lib.DEFAULT_SOA_DIR
DEFAULT_DOCKERCFG_LOCATION = "file:///root/.dockercfg"
DEPLOY_PIPELINE_NON_DEPLOY_STEPS = (
'itest',
'security-check',
'performance-check',
'push-to-registry'
)
# Default values for _log
ANY_CLUSTER = 'N/A'
ANY_INSTANCE = 'N/A'
DEFAULT_LOGLEVEL = 'event'
no_escape = re.compile('\x1B\[[0-9;]*[mK]')
DEFAULT_SYNAPSE_HAPROXY_URL_FORMAT = "http://{host:s}:{port:d}/;csv;norefresh"
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
class InvalidInstanceConfig(Exception):
pass
class InstanceConfig(dict):
def __init__(self, cluster, instance, service, config_dict, branch_dict):
self.config_dict = config_dict
self.branch_dict = branch_dict
self.cluster = cluster
self.instance = instance
self.service = service
config_interpolation_keys = ('deploy_group',)
interpolation_facts = self.__get_interpolation_facts()
for key in config_interpolation_keys:
if key in self.config_dict:
self.config_dict[key] = self.config_dict[key].format(**interpolation_facts)
def __get_interpolation_facts(self):
return {
'cluster': self.cluster,
'instance': self.instance,
'service': self.service,
}
def get_cluster(self):
return self.cluster
def get_instance(self):
return self.instance
def get_service(self):
return self.service
def get_branch(self):
return SPACER.join((self.get_cluster(), self.get_instance()))
def get_deploy_group(self):
return self.config_dict.get('deploy_group', self.get_branch())
def get_mem(self):
"""Gets the memory required from the service's configuration.
Defaults to 1024 (1G) if no value specified in the config.
:returns: The amount of memory specified by the config, 1024 if not specified"""
mem = self.config_dict.get('mem', 1024)
return mem
def get_mem_swap(self):
"""Gets the memory-swap value. This value is passed to the docker
container to ensure that the total memory limit (memory + swap) is the
same value as the 'mem' key in soa-configs. Note - this value *has* to
be >= to the mem key, so we always round up to the closest MB.
"""
mem = self.get_mem()
mem_swap = int(math.ceil(mem))
return "%sm" % mem_swap
def get_cpus(self):
"""Gets the number of cpus required from the service's configuration.
Defaults to .25 (1/4 of a cpu) if no value specified in the config.
:returns: The number of cpus specified in the config, .25 if not specified"""
cpus = self.config_dict.get('cpus', .25)
return cpus
def get_disk(self):
"""Gets the amount of disk space required from the service's configuration.
Defaults to 1024 (1G) if no value is specified in the config.
:returns: The amount of disk space specified by the config, 1024 if not specified"""
disk = self.config_dict.get('disk', 1024)
return disk
def get_cmd(self):
"""Get the docker cmd specified in the service's configuration.
Defaults to null if not specified in the config.
:returns: A string specified in the config, None if not specified"""
return self.config_dict.get('cmd', None)
def get_env_dictionary(self):
"""A dictionary of key/value pairs that represent environment variables
to be injected to the container environment"""
env = {
"PAASTA_SERVICE": self.service,
"PAASTA_INSTANCE": self.instance,
"PAASTA_CLUSTER": self.cluster,
}
user_env = self.config_dict.get('env', {})
env.update(user_env)
return env
def get_env(self):
"""Basic get_env that simply returns the basic env, other classes
might need to override this getter for more implementation-specific
env getting"""
return self.get_env_dictionary()
def get_args(self):
"""Get the docker args specified in the service's configuration.
If not specified in the config and if cmd is not specified, defaults to an empty array.
If not specified in the config but cmd is specified, defaults to null.
If specified in the config and if cmd is also specified, throws an exception. Only one may be specified.
:param service_config: The service instance's configuration dictionary
:returns: An array of args specified in the config,
``[]`` if not specified and if cmd is not specified,
otherwise None if not specified but cmd is specified"""
if self.get_cmd() is None:
return self.config_dict.get('args', [])
else:
args = self.config_dict.get('args', None)
if args is None:
return args
else:
# TODO validation stuff like this should be moved into a check_* like in chronos tools
raise InvalidInstanceConfig('Instance configuration can specify cmd or args, but not both.')
def get_monitoring(self):
"""Get monitoring overrides defined for the given instance"""
return self.config_dict.get('monitoring', {})
def get_deploy_blacklist(self):
"""The deploy blacklist is a list of lists, where the lists indicate
which locations the service should not be deployed"""
return self.config_dict.get('deploy_blacklist', [])
def get_deploy_whitelist(self):
"""The deploy whitelist is a list of lists, where the lists indicate
which locations are explicitly allowed. The blacklist will supersede
this if a host matches both the white and blacklists."""
return self.config_dict.get('deploy_whitelist', [])
def get_monitoring_blacklist(self):
"""The monitoring_blacklist is a list of tuples, where the tuples indicate
which locations the user doesn't care to be monitored"""
return self.config_dict.get('monitoring_blacklist', self.get_deploy_blacklist())
def get_docker_image(self):
"""Get the docker image name (with tag) for a given service branch from
a generated deployments.json file."""
return self.branch_dict.get('docker_image', '')
def get_desired_state(self):
"""Get the desired state (either 'start' or 'stop') for a given service
branch from a generated deployments.json file."""
return self.branch_dict.get('desired_state', 'start')
def get_force_bounce(self):
"""Get the force_bounce token for a given service branch from a generated
deployments.json file. This is a token that, when changed, indicates that
the instance should be recreated and bounced, even if no other
parameters have changed. This may be None or a string, generally a
timestamp.
"""
return self.branch_dict.get('force_bounce', None)
def check_cpus(self):
cpus = self.get_cpus()
if cpus is not None:
if not isinstance(cpus, (float, int)):
return False, 'The specified cpus value "%s" is not a valid float or int.' % cpus
return True, ''
def check_mem(self):
mem = self.get_mem()
if mem is not None:
if not isinstance(mem, (float, int)):
return False, 'The specified mem value "%s" is not a valid float or int.' % mem
return True, ''
def check_disk(self):
disk = self.get_disk()
if disk is not None:
if not isinstance(disk, (float, int)):
return False, 'The specified disk value "%s" is not a valid float or int.' % disk
return True, ''
def check(self, param):
check_methods = {
'cpus': self.check_cpus,
'mem': self.check_mem,
}
if param in check_methods:
return check_methods[param]()
else:
return False, 'Your Chronos config specifies "%s", an unsupported parameter.' % param
def validate(self):
error_msgs = []
for param in ['cpus', 'mem']:
check_passed, check_msg = self.check(param)
if not check_passed:
error_msgs.append(check_msg)
return error_msgs
def get_extra_volumes(self):
"""Extra volumes are a specially formatted list of dictionaries that should
be bind mounted in a container The format of the dictionaries should
conform to the `Mesos container volumes spec
<https://mesosphere.github.io/marathon/docs/native-docker.html>`_"""
return self.config_dict.get('extra_volumes', [])
def get_pool(self):
"""Which pool of nodes this job should run on. This can be used to mitigate noisy neighbors, by putting
particularly noisy or noise-sensitive jobs into different pools.
This is implemented with an attribute "pool" on each mesos slave and by adding a constraint to Marathon/Chronos
application defined by this instance config.
Eventually this may be implemented with Mesos roles, once a framework can register under multiple roles.
:returns: the "pool" attribute in your config dict, or the string "default" if not specified."""
return self.config_dict.get('pool', 'default')
def get_pool_constraints(self):
pool = self.get_pool()
return [["pool", "LIKE", pool]]
def get_constraints(self):
return self.config_dict.get('constraints', None)
def get_extra_constraints(self):
return self.config_dict.get('extra_constraints', [])
def get_net(self):
"""
:returns: the docker networking mode the container should be started with.
"""
return self.config_dict.get('net', 'bridge')
def validate_service_instance(service, instance, cluster, soa_dir):
marathon_services = get_services_for_cluster(cluster=cluster, instance_type='marathon', soa_dir=soa_dir)
chronos_services = get_services_for_cluster(cluster=cluster, instance_type='chronos', soa_dir=soa_dir)
if (service, instance) in marathon_services:
return 'marathon'
elif (service, instance) in chronos_services:
return 'chronos'
else:
print ("Error: %s doesn't look like it has been deployed to this cluster! (%s)"
% (compose_job_id(service, instance), cluster))
sys.exit(3)
class PaastaColors:
"""Collection of static variables and methods to assist in coloring text."""
# ANSI colour codes
BLUE = '\033[34m'
BOLD = '\033[1m'
CYAN = '\033[36m'
DEFAULT = '\033[0m'
GREEN = '\033[32m'
GREY = '\033[38;5;242m'
MAGENTA = '\033[35m'
RED = '\033[31m'
YELLOW = '\033[33m'
@staticmethod
def bold(text):
"""Return bolded text.
:param text: a string
:return: text colour coded with ANSI bold
"""
return PaastaColors.color_text(PaastaColors.BOLD, text)
@staticmethod
def blue(text):
"""Return text that can be printed blue.
:param text: a string
:return: text colour coded with ANSI blue
"""
return PaastaColors.color_text(PaastaColors.BLUE, text)
@staticmethod
def green(text):
"""Return text that can be printed green.
:param text: a string
:return: text colour coded with ANSI green"""
return PaastaColors.color_text(PaastaColors.GREEN, text)
@staticmethod
def red(text):
"""Return text that can be printed red.
:param text: a string
:return: text colour coded with ANSI red"""
return PaastaColors.color_text(PaastaColors.RED, text)
@staticmethod
def magenta(text):
"""Return text that can be printed magenta.
:param text: a string
:return: text colour coded with ANSI magenta"""
return PaastaColors.color_text(PaastaColors.MAGENTA, text)
@staticmethod
def color_text(color, text):
"""Return text that can be printed color.
:param color: ANSI colour code
:param text: a string
:return: a string with ANSI colour encoding"""
# any time text returns to default, we want to insert our color.
replaced = text.replace(PaastaColors.DEFAULT, PaastaColors.DEFAULT + color)
# then wrap the beginning and end in our color/default.
return color + replaced + PaastaColors.DEFAULT
@staticmethod
def cyan(text):
"""Return text that can be printed cyan.
:param text: a string
:return: text colour coded with ANSI cyan"""
return PaastaColors.color_text(PaastaColors.CYAN, text)
@staticmethod
def yellow(text):
"""Return text that can be printed yellow.
:param text: a string
:return: text colour coded with ANSI yellow"""
return PaastaColors.color_text(PaastaColors.YELLOW, text)
@staticmethod
def grey(text):
return PaastaColors.color_text(PaastaColors.GREY, text)
@staticmethod
def default(text):
return PaastaColors.color_text(PaastaColors.DEFAULT, text)
LOG_COMPONENTS = {
'build': {
'color': PaastaColors.blue,
'help': 'Jenkins build jobs output, like the itest, promotion, security checks, etc.',
'command': 'NA - TODO: tee jenkins build steps into scribe PAASTA-201',
'source_env': 'devc',
},
'deploy': {
'color': PaastaColors.cyan,
'help': 'Output from the paasta deploy code. (setup_marathon_job, bounces, etc)',
'command': 'NA - TODO: tee deploy logs into scribe PAASTA-201',
},
'monitoring': {
'color': PaastaColors.green,
'help': 'Logs from Sensu checks for the service',
'command': 'NA - TODO log mesos healthcheck and sensu stuff.',
},
'marathon': {
'color': PaastaColors.magenta,
'help': 'Logs from Marathon for the service',
'command': 'NA - TODO log marathon stuff.',
},
'chronos': {
'color': PaastaColors.magenta,
'help': 'Logs from Chronos for the service',
'command': 'NA - TODO log chronos stuff.',
},
# I'm leaving these planned components here since they provide some hints
# about where we want to go. See PAASTA-78.
#
# But I'm commenting them out so they don't delude users into believing we
# can expose logs that we cannot actually expose. See PAASTA-927.
#
# 'app_output': {
# 'color': PaastaColors.bold,
# 'help': 'Stderr and stdout of the actual process spawned by Mesos',
# 'command': 'NA - PAASTA-78',
# },
# 'app_request': {
# 'color': PaastaColors.bold,
# 'help': 'The request log for the service. Defaults to "service_NAME_requests"',
# 'command': 'scribe_reader -e ENV -f service_example_happyhour_requests',
# },
# 'app_errors': {
# 'color': PaastaColors.red,
# 'help': 'Application error log, defaults to "stream_service_NAME_errors"',
# 'command': 'scribe_reader -e ENV -f stream_service_SERVICE_errors',
# },
# 'lb_requests': {
# 'color': PaastaColors.bold,
# 'help': 'All requests from Smartstack haproxy',
# 'command': 'NA - TODO: SRV-1130',
# },
# 'lb_errors': {
# 'color': PaastaColors.red,
# 'help': 'Logs from Smartstack haproxy that have 400-500 error codes',
# 'command': 'scribereader -e ENV -f stream_service_errors | grep SERVICE.instance',
# },
}
class NoSuchLogComponent(Exception):
pass
def validate_log_component(component):
if component in LOG_COMPONENTS.keys():
return True
else:
raise NoSuchLogComponent
def get_git_url(service, soa_dir=DEFAULT_SOA_DIR):
"""Get the git url for a service. Assumes that the service's
repo matches its name, and that it lives in services- i.e.
if this is called with the string 'test', the returned
url will be git@git.yelpcorp.com:services/test.git.
:param service: The service name to get a URL for
:returns: A git url to the service's repository"""
general_config = service_configuration_lib.read_service_configuration(
service,
soa_dir=soa_dir,
)
default_location = 'git@git.yelpcorp.com:services/%s.git' % service
return general_config.get('git_url', default_location)
class NoSuchLogLevel(Exception):
pass
# The active log writer.
_log_writer = None
# The map of name -> LogWriter subclasses, used by configure_log.
_log_writer_classes = {}
def register_log_writer(name):
"""Returns a decorator that registers that bounce function at a given name
so get_log_writer_classes can find it."""
def outer(bounce_func):
_log_writer_classes[name] = bounce_func
return bounce_func
return outer
def get_log_writer_class(name):
return _log_writer_classes[name]
def list_log_writers():
return _log_writer_classes.keys()
def configure_log():
"""We will log to the yocalhost binded scribe."""
log_writer_config = load_system_paasta_config().get_log_writer()
global _log_writer
LogWriterClass = get_log_writer_class(log_writer_config['driver'])
_log_writer = LogWriterClass(**log_writer_config.get('options', {}))
def _log(*args, **kwargs):
if _log_writer is None:
configure_log()
return _log_writer.log(*args, **kwargs)
class LogWriter(object):
def log(self, line, component, level=DEFAULT_LOGLEVEL, cluster=ANY_CLUSTER, instance=ANY_INSTANCE):
raise NotImplementedError()
def _now():
return datetime.datetime.utcnow().isoformat()
def remove_ansi_escape_sequences(line):
"""Removes ansi escape sequences from the given line."""
return no_escape.sub('', line)
def format_log_line(level, cluster, service, instance, component, line, timestamp=None):
"""Accepts a string 'line'.
Returns an appropriately-formatted dictionary which can be serialized to
JSON for logging and which contains 'line'.
"""
validate_log_component(component)
if not timestamp:
timestamp = _now()
line = remove_ansi_escape_sequences(line)
message = json.dumps({
'timestamp': timestamp,
'level': level,
'cluster': cluster,
'service': service,
'instance': instance,
'component': component,
'message': line,
}, sort_keys=True)
return message
def get_log_name_for_service(service):
return 'stream_paasta_%s' % service
@register_log_writer('scribe')
class ScribeLogWriter(LogWriter):
def __init__(self, scribe_host='169.254.255.254', scribe_port=1463, scribe_disable=False, **kwargs):
self.clog = importlib.import_module('clog')
self.clog.config.configure(scribe_host=scribe_host, scribe_port=scribe_port, scribe_disable=scribe_disable)
def log(self, service, line, component, level=DEFAULT_LOGLEVEL, cluster=ANY_CLUSTER, instance=ANY_INSTANCE):
"""This expects someone (currently the paasta cli main()) to have already
configured the log object. We'll just write things to it.
"""
if level == 'event':
print(line, file=sys.stdout)
elif level == 'debug':
print(line, file=sys.stderr)
else:
raise NoSuchLogLevel
log_name = get_log_name_for_service(service)
formatted_line = format_log_line(level, cluster, service, instance, component, line)
self.clog.log_line(log_name, formatted_line)
@register_log_writer('null')
class NullLogWriter(LogWriter):
"""A LogWriter class that doesn't do anything. Primarily useful for integration tests where we don't care about
logs."""
def __init__(self, **kwargs):
pass
def log(self, service, line, component, level=DEFAULT_LOGLEVEL, cluster=ANY_CLUSTER, instance=ANY_INSTANCE):
pass
@register_log_writer('file')
class FileLogWriter(LogWriter):
def __init__(self, path_format, mode='a+', line_delimeter='\n', flock=False):
self.path_format = path_format
self.mode = mode
self.flock = flock
self.line_delimeter = line_delimeter
@contextlib.contextmanager
def maybe_flock(self, fd):
if self.flock:
try:
fcntl.flock(fd, fcntl.LOCK_EX)
yield
finally:
fcntl.flock(fd, fcntl.LOCK_UN)
else:
yield
def format_path(self, service, component, level, cluster, instance):
return self.path_format.format(
service=service,
component=component,
level=level,
cluster=cluster,
instance=instance,
)
def log(self, service, line, component, level=DEFAULT_LOGLEVEL, cluster=ANY_CLUSTER, instance=ANY_INSTANCE):
path = self.format_path(service, component, level, cluster, instance)
# We use io.FileIO here because it guarantees that write() is implemented with a single write syscall,
# and on Linux, writes to O_APPEND files with a single write syscall are atomic.
#
# https://docs.python.org/2/library/io.html#io.FileIO
# http://article.gmane.org/gmane.linux.kernel/43445
to_write = "%s%s" % (format_log_line(level, cluster, service, instance, component, line), self.line_delimeter)
with io.FileIO(path, mode=self.mode, closefd=True) as f:
with self.maybe_flock(f):
f.write(to_write)
def _timeout(process):
"""Helper function for _run. It terminates the process.
Doesn't raise OSError, if we try to terminate a non-existing
process as there can be a very small window between poll() and kill()
"""
if process.poll() is None:
try:
# sending SIGKILL to the process
process.kill()
except OSError as e:
# No such process error
# The process could have been terminated meanwhile
if e.errno != errno.ESRCH:
raise
class PaastaNotConfiguredError(Exception):
pass
class NoConfigurationForServiceError(Exception):
pass
def get_readable_files_in_glob(glob, path):
"""
Returns a sorted list of files that are readable in an input glob by recursively searching a path
"""
globbed_files = []
for root, dirs, files in os.walk(path):
for f in files:
fn = os.path.join(root, f)
if os.path.isfile(fn) and os.access(fn, os.R_OK) and fnmatch(fn, glob):
globbed_files.append(fn)
return sorted(globbed_files)
def load_system_paasta_config(path=PATH_TO_SYSTEM_PAASTA_CONFIG_DIR):
"""
Reads Paasta configs in specified directory in lexicographical order and merges duplicated keys (last file wins)
"""
config = {}
if not os.path.isdir(path):
raise PaastaNotConfiguredError("Could not find system paasta configuration directory: %s" % path)
if not os.access(path, os.R_OK):
raise PaastaNotConfiguredError("Could not read from system paasta configuration directory: %s" % path)
try:
for config_file in get_readable_files_in_glob(glob="*.json", path=path):
with open(config_file) as f:
config.update(json.load(f))
except IOError as e:
raise PaastaNotConfiguredError("Could not load system paasta config file %s: %s" % (e.filename, e.strerror))
return SystemPaastaConfig(config, path)
class SystemPaastaConfig(dict):
def __init__(self, config, directory):
self.directory = directory
super(SystemPaastaConfig, self).__init__(config)
def get_zk_hosts(self):
"""Get the zk_hosts defined in this hosts's cluster config file.
Strips off the zk:// prefix, if it exists, for use with Kazoo.
:returns: The zk_hosts specified in the paasta configuration
"""
try:
hosts = self['zookeeper']
except KeyError:
raise PaastaNotConfiguredError('Could not find zookeeper connection string in configuration directory: %s'
% self.directory)
# how do python strings not have a method for doing this
if hosts.startswith('zk://'):
return hosts[len('zk://'):]
return hosts
def get_docker_registry(self):
"""Get the docker_registry defined in this host's cluster config file.
:returns: The docker_registry specified in the paasta configuration
"""
try:
return self['docker_registry']
except KeyError:
raise PaastaNotConfiguredError('Could not find docker registry in configuration directory: %s'
% self.directory)
def get_volumes(self):
"""Get the volumes defined in this host's volumes config file.
:returns: The list of volumes specified in the paasta configuration
"""
try:
return self['volumes']
except KeyError:
raise PaastaNotConfiguredError('Could not find volumes in configuration directory: %s' % self.directory)
def get_cluster(self):
"""Get the cluster defined in this host's cluster config file.
:returns: The name of the cluster defined in the paasta configuration
"""
try:
return self['cluster']
except KeyError:
raise PaastaNotConfiguredError('Could not find cluster in configuration directory: %s' % self.directory)
def get_dashboard_links(self):
try:
return self['dashboard_links']
except KeyError:
raise PaastaNotConfiguredError(
'Could not find dashboard_links in configuration directory: %s' % self.directory)
def get_fsm_template(self):
fsm_path = os.path.dirname(sys.modules['paasta_tools.cli.fsm'].__file__)
template_path = os.path.join(fsm_path, "template")
return self.get('fsm_template', template_path)
def get_log_writer(self):
"""Get the log_writer configuration out of global paasta config
:returns: The log_writer dictionary.
"""
try:
return self['log_writer']
except KeyError:
raise PaastaNotConfiguredError('Could not find log_writer in configuration directory: %s' % self.directory)
def get_log_reader(self):
"""Get the log_reader configuration out of global paasta config
:returns: the log_reader dictionary.
"""
try:
return self['log_reader']
except KeyError:
raise PaastaNotConfiguredError('Could not find log_reader in configuration directory: %s' % self.directory)
def get_sensu_host(self):
"""Get the host that we should send sensu events to.
:returns: the sensu_host string, or localhost if not specified.
"""
return self.get('sensu_host', 'localhost')
def get_sensu_port(self):
"""Get the port that we should send sensu events to.
:returns: the sensu_port value as an integer, or 3030 if not specified.
"""
return int(self.get('sensu_port', 3030))
def get_dockercfg_location(self):
"""Get the location of the dockerfile, as a URI.
:returns: the URI specified, or file:///root/.dockercfg if not specified.
"""
return self.get('dockercfg_location', DEFAULT_DOCKERCFG_LOCATION)
def get_synapse_port(self):
"""Get the port that haproxy-synapse exposes its status on. Defaults to 3212.
:returns: the haproxy-synapse status port."""
return int(self.get('synapse_port', 3212))
def get_default_synapse_host(self):
"""Get the default host we should interrogate for haproxy-synapse state.
:returns: A hostname that is running haproxy-synapse."""
return self.get('synapse_host', 'localhost')
def get_synapse_haproxy_url_format(self):
"""Get a format string for the URL to query for haproxy-synapse state. This format string gets two keyword
arguments, host and port. Defaults to "http://{host:s}:{port:d}/;csv;norefresh".
:returns: A format string for constructing the URL of haproxy-synapse's status page."""
return self.get('synapse_haproxy_url_format', DEFAULT_SYNAPSE_HAPROXY_URL_FORMAT)
def get_cluster_autoscaling_resources(self):
return self.get('cluster_autoscaling_resources', {})
def get_cluster_fqdn_format(self):
"""Get a format string that constructs a DNS name pointing at the paasta masters in a cluster. This format
string gets one parameter: cluster. Defaults to 'paasta-{cluster:s}.yelp'.
:returns: A format string for constructing the FQDN of the masters in a given cluster."""
return self.get('cluster_fqdn_format', 'paasta-{cluster:s}.yelp')
def _run(command, env=os.environ, timeout=None, log=False, stream=False, stdin=None, **kwargs):
"""Given a command, run it. Return a tuple of the return code and any
output.
:param timeout: If specified, the command will be terminated after timeout
seconds.
:param log: If True, the _log will be handled by _run. If set, it is mandatory
to pass at least a :service: and a :component: parameter. Optionally you
can pass :cluster:, :instance: and :loglevel: parameters for logging.
We wanted to use plumbum instead of rolling our own thing with
subprocess.Popen but were blocked by
https://github.com/tomerfiliba/plumbum/issues/162 and our local BASH_FUNC
magic.
"""
output = []
if log:
service = kwargs['service']
component = kwargs['component']
cluster = kwargs.get('cluster', ANY_CLUSTER)
instance = kwargs.get('instance', ANY_INSTANCE)
loglevel = kwargs.get('loglevel', DEFAULT_LOGLEVEL)
try:
process = Popen(shlex.split(command), stdout=PIPE, stderr=STDOUT, stdin=stdin, env=env)
process.name = command
# start the timer if we specified a timeout
if timeout:
proctimer = threading.Timer(timeout, _timeout, (process,))
proctimer.start()
for line in iter(process.stdout.readline, ''):
# additional indentation is for the paasta status command only
if stream:
if ('paasta_serviceinit status' in command):
if 'instance: ' in line:
print(' ' + line.rstrip('\n'))
else:
print(' ' + line.rstrip('\n'))
else:
print(line.rstrip('\n'))
else:
output.append(line.rstrip('\n'))
if log:
_log(
service=service,
line=line.rstrip('\n'),
component=component,
level=loglevel,
cluster=cluster,
instance=instance,
)
# when finished, get the exit code
returncode = process.wait()
except OSError as e:
if log:
_log(
service=service,
line=e.strerror.rstrip('\n'),
component=component,
level=loglevel,
cluster=cluster,
instance=instance,
)
output.append(e.strerror.rstrip('\n'))
returncode = e.errno
except (KeyboardInterrupt, SystemExit):
# need to clean up the timing thread here
if timeout:
proctimer.cancel()
raise
else:
# Stop the timer
if timeout:
proctimer.cancel()
if returncode == -9:
output.append("Command '%s' timed out (longer than %ss)" % (command, timeout))
return returncode, '\n'.join(output)
def get_umask():
"""Get the current umask for this process. NOT THREAD SAFE."""
old_umask = os.umask(0022)
os.umask(old_umask)
return old_umask
@contextlib.contextmanager
def atomic_file_write(target_path):
dirname = os.path.dirname(target_path)
basename = os.path.basename(target_path)
with tempfile.NamedTemporaryFile(
dir=dirname,
prefix=('.%s-' % basename),
delete=False
) as f:
temp_target_path = f.name
yield f
mode = 0666 & (~get_umask())
os.chmod(temp_target_path, mode)
os.rename(temp_target_path, target_path)
class InvalidJobNameError(Exception):
pass
def compose_job_id(name, instance, git_hash=None, config_hash=None, spacer=SPACER):
"""Compose a job/app id by concatenating its name, instance, git hash, and config hash.
:param name: The name of the service
:param instance: The instance of the service
:param git_hash: The git_hash portion of the job_id. If git_hash is set,
config_hash must also be set.
:param config_hash: The config_hash portion of the job_id. If config_hash
is set, git_hash must also be set.
:returns: <name><SPACER><instance> if no tag, or <name><SPACER><instance><SPACER><hashes>...
if extra hash inputs are provided.
"""
composed = '%s%s%s' % (name, spacer, instance)
if git_hash and config_hash:
composed = '%s%s%s%s%s' % (composed, spacer, git_hash, spacer, config_hash)
elif git_hash or config_hash:
raise InvalidJobNameError(
'invalid job id because git_hash (%s) and config_hash (%s) must '
'both be defined or neither can be defined' % (git_hash, config_hash))
return composed
def decompose_job_id(job_id, spacer=SPACER):
"""Break a composed job id into its constituent (service name, instance,
git hash, config hash) by splitting with ``spacer``.
:param job_id: The composed id of the job/app
:returns: A tuple (service name, instance, git hash, config hash) that
comprise the job_id
"""
decomposed = job_id.split(spacer)
if len(decomposed) == 2: