forked from Yelp/paasta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
2779 lines (2244 loc) · 94.5 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-2017 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.
import contextlib
import copy
import datetime
import errno
import fcntl
import glob
import hashlib
import io
import json
import logging
import math
import os
import pwd
import queue
import re
import shlex
import signal
import sys
import tempfile
import threading
import time
from collections import OrderedDict
from fnmatch import fnmatch
from functools import lru_cache
from functools import wraps
from subprocess import PIPE
from subprocess import Popen
from subprocess import STDOUT
from types import FrameType
from typing import Any
from typing import Callable
from typing import cast
from typing import Collection
from typing import ContextManager
from typing import Dict
from typing import FrozenSet
from typing import IO
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Mapping
from typing import Optional
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
from typing import TypeVar
from typing import Union
import choice
import dateutil.tz
import requests_cache
import service_configuration_lib
import yaml
from docker import Client
from docker.utils import kwargs_from_env
from kazoo.client import KazooClient
from mypy_extensions import TypedDict
import paasta_tools.cli.fsm
# 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"
DEFAULT_CPU_PERIOD = 100000
DEFAULT_CPU_BURST_PCT = 900
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
INSTANCE_TYPES = ('marathon', 'chronos', 'paasta_native', 'adhoc')
TimeCacheEntry = TypedDict(
'TimeCacheEntry',
{
'data': Any,
'fetch_time': float,
},
)
_CacheRetT = TypeVar('_CacheRetT')
class time_cache(object):
def __init__(self, ttl: float=0) -> None:
self.configs: Dict[Tuple, TimeCacheEntry] = {}
self.ttl = ttl
def __call__(self, f: Callable[..., _CacheRetT]) -> Callable[..., _CacheRetT]:
def cache(*args: Any, **kwargs: Any) -> _CacheRetT:
if 'ttl' in kwargs:
ttl = kwargs['ttl']
del kwargs['ttl']
else:
ttl = self.ttl
key = args
for item in kwargs.items():
key += item
if (not ttl) or (key not in self.configs) or (time.time() - self.configs[key]['fetch_time'] > ttl):
self.configs[key] = {'data': f(*args, **kwargs), 'fetch_time': time.time()}
return self.configs[key]['data']
return cache
_SortDictsT = TypeVar('_SortDictsT', bound=Mapping)
def sort_dicts(dcts: Iterable[_SortDictsT]) -> List[_SortDictsT]:
def key(dct: _SortDictsT) -> Tuple:
return tuple(sorted(dct.items()))
return sorted(dcts, key=key)
class InvalidInstanceConfig(Exception):
pass
DeployBlacklist = List[Tuple[str, str]]
DeployWhitelist = Optional[Tuple[str, List[str]]]
# The actual config files will have lists, since tuples are not expressible in base YAML, so we define different types
# here to represent that. The getter functions will convert to the safe versions above.
UnsafeDeployBlacklist = Optional[Sequence[Sequence[str]]]
UnsafeDeployWhitelist = Optional[Sequence[Union[str, Sequence[str]]]]
Constraint = Sequence[str]
# e.g. ['GROUP_BY', 'habitat', 2]. Marathon doesn't like that so we'll convert to Constraint later.
UnstringifiedConstraint = Sequence[Union[str, int, float]]
SecurityConfigDict = Dict # Todo: define me.
DockerVolume = TypedDict(
'DockerVolume',
{
'hostPath': str,
'containerPath': str,
'mode': str,
},
)
InstanceConfigDict = TypedDict(
'InstanceConfigDict',
{
'deploy_group': str,
'mem': float,
'cpus': float,
'disk': float,
'cmd': str,
'args': List[str],
'cfs_period_us': float,
'cpu_burst_pct': float,
'ulimit': Dict[str, Dict[str, Any]],
'cap_add': List,
'env': Dict[str, str],
'monitoring': Dict[str, str],
'deploy_blacklist': UnsafeDeployBlacklist,
'deploy_whitelist': UnsafeDeployWhitelist,
'monitoring_blacklist': UnsafeDeployBlacklist,
'pool': str,
'role': str,
'extra_volumes': List[DockerVolume],
'security': SecurityConfigDict,
'dependencies_reference': str,
'dependencies': Dict[str, Dict],
'constraints': List[UnstringifiedConstraint],
'extra_constraints': List[UnstringifiedConstraint],
'net': str,
'extra_docker_args': Dict[str, str],
'gpus': float,
'branch': str,
},
total=False,
)
BranchDictV1 = TypedDict(
'BranchDictV1',
{
'docker_image': str,
'desired_state': str,
'force_bounce': Optional[str],
},
total=False,
)
BranchDictV2 = TypedDict(
'BranchDictV2',
{
'git_sha': str,
'docker_image': str,
'desired_state': str,
'force_bounce': Optional[str],
},
)
DockerParameter = TypedDict(
'DockerParameter',
{
'key': str,
'value': str,
},
)
def safe_deploy_blacklist(input: UnsafeDeployBlacklist) -> DeployBlacklist:
return [(t, l) for t, l in input]
def safe_deploy_whitelist(input: UnsafeDeployWhitelist) -> DeployWhitelist:
try:
location_type, allowed_values = input
return cast(str, location_type), cast(List[str], allowed_values)
except TypeError:
return None
class InstanceConfig(object):
config_filename_prefix: str
def __init__(
self, cluster: str, instance: str, service: str, config_dict: InstanceConfigDict,
branch_dict: Optional[BranchDictV2], soa_dir: str=DEFAULT_SOA_DIR,
) -> None:
self.config_dict = config_dict
self.branch_dict = branch_dict
self.cluster = cluster
self.instance = instance
self.service = service
self.soa_dir = soa_dir
self._job_id = compose_job_id(service, instance)
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) # type: ignore
def __get_interpolation_facts(self) -> Dict[str, str]:
return {
'cluster': self.cluster,
'instance': self.instance,
'service': self.service,
}
def get_cluster(self) -> str:
return self.cluster
def get_instance(self) -> str:
return self.instance
def get_service(self) -> str:
return self.service
@property
def job_id(self) -> str:
return self._job_id
def get_docker_registry(self) -> str:
return get_service_docker_registry(self.service, self.soa_dir)
def get_branch(self) -> str:
return get_paasta_branch(cluster=self.get_cluster(), instance=self.get_instance())
def get_deploy_group(self) -> str:
return self.config_dict.get('deploy_group', self.get_branch())
def get_team(self) -> str:
return self.config_dict.get('monitoring', {}).get('team', None)
def get_mem(self) -> float:
"""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) -> str:
"""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 and add
additional 64MB for the docker executor (See PAASTA-12450).
"""
mem = self.get_mem()
mem_swap = int(math.ceil(mem + 64))
return "%sm" % mem_swap
def get_cpus(self) -> float:
"""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_cpu_burst_pct(self) -> float:
"""Returns the percent over its declared cpu usage that a container
will be allowed to go. Default to DEFAULT_CPU_PERIOD"""
return self.config_dict.get('cpu_burst_pct', DEFAULT_CPU_BURST_PCT)
def get_cpu_period(self) -> float:
"""The --cpu-period option to be passed to docker
Comes from the cfs_period_us configuration option
:returns: The number to be passed to the --cpu-period docker flag"""
return self.config_dict.get('cfs_period_us', DEFAULT_CPU_PERIOD)
def get_cpu_quota(self) -> float:
"""Gets the --cpu-quota option to be passed to docker
Calculation: cpus * cfs_period_us * (100 + cpu_burst_pct) / 100
:returns: The number to be passed to the --cpu-quota docker flag"""
cpu_burst_pct = self.get_cpu_burst_pct()
return self.get_cpus() * self.get_cpu_period() * (100 + cpu_burst_pct) / 100
def get_extra_docker_args(self) -> Dict[str, str]:
return self.config_dict.get('extra_docker_args', {})
def get_ulimit(self) -> Iterable[DockerParameter]:
"""Get the --ulimit options to be passed to docker
Generated from the ulimit configuration option, which is a dictionary
of ulimit values. Each value is a dictionary itself, with the soft
limit stored under the 'soft' key and the optional hard limit stored
under the 'hard' key.
Example configuration: {'nofile': {soft: 1024, hard: 2048}, 'nice': {soft: 20}}
:returns: A generator of ulimit options to be passed as --ulimit flags"""
for key, val in sorted(self.config_dict.get('ulimit', {}).items()):
soft = val.get('soft')
hard = val.get('hard')
if soft is None:
raise InvalidInstanceConfig(
'soft limit missing in ulimit configuration for {}.'.format(key),
)
combined_val = '%i' % soft
if hard is not None:
combined_val += ':%i' % hard
yield {"key": "ulimit", "value": "{}={}".format(key, combined_val)}
def get_cap_add(self) -> Iterable[DockerParameter]:
"""Get the --cap-add options to be passed to docker
Generated from the cap_add configuration option, which is a list of
capabilities.
Example configuration: {'cap_add': ['IPC_LOCK', 'SYS_PTRACE']}
:returns: A generator of cap_add options to be passed as --cap-add flags"""
for value in self.config_dict.get('cap_add', []):
yield {"key": "cap-add", "value": "{}".format(value)}
def format_docker_parameters(self, with_labels: bool=True) -> List[DockerParameter]:
"""Formats extra flags for running docker. Will be added in the format
`["--%s=%s" % (e['key'], e['value']) for e in list]` to the `docker run` command
Note: values must be strings
:param with_labels: Whether to build docker parameters with or without labels
:returns: A list of parameters to be added to docker run"""
parameters: List[DockerParameter] = [
{"key": "memory-swap", "value": self.get_mem_swap()},
{"key": "cpu-period", "value": "%s" % int(self.get_cpu_period())},
{"key": "cpu-quota", "value": "%s" % int(self.get_cpu_quota())},
]
if with_labels:
parameters.extend([
{"key": "label", "value": "paasta_service=%s" % self.service},
{"key": "label", "value": "paasta_instance=%s" % self.instance},
])
extra_docker_args = self.get_extra_docker_args()
if extra_docker_args:
for key, value in extra_docker_args.items():
parameters.extend([
{"key": key, "value": value},
])
parameters.extend(self.get_ulimit())
parameters.extend(self.get_cap_add())
return parameters
def get_disk(self, default: float=1024) -> float:
"""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', default)
return disk
def get_gpus(self, default: float=0) -> float:
"""Gets the number of gpus required from the service's configuration.
Default to 0 if no value is specified in the config.
:returns: The number of gpus specified by the config, 0 if not specified"""
gpus = self.config_dict.get('gpus', default)
return gpus
def get_cmd(self) -> Optional[str]:
"""Get the docker cmd specified in the service's configuration.
Defaults to None 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) -> Dict[str, str]:
"""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,
"PAASTA_DEPLOY_GROUP": self.get_deploy_group(),
"PAASTA_DOCKER_IMAGE": self.get_docker_image(),
}
team = self.get_team()
if team:
env["PAASTA_MONITORING_TEAM"] = team
user_env = self.config_dict.get('env', {})
env.update(user_env)
return env
def get_env(self) -> Dict[str, str]:
"""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) -> Optional[List[str]]:
"""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) -> Dict[str, Any]:
"""Get monitoring overrides defined for the given instance"""
return self.config_dict.get('monitoring', {})
def get_deploy_constraints(
self,
blacklist: DeployBlacklist,
whitelist: DeployWhitelist,
system_deploy_blacklist: DeployBlacklist,
system_deploy_whitelist: DeployWhitelist,
) -> List[Constraint]:
"""Return the combination of deploy_blacklist and deploy_whitelist
as a list of constraints.
"""
return (
deploy_blacklist_to_constraints(blacklist) +
deploy_whitelist_to_constraints(whitelist) +
deploy_blacklist_to_constraints(system_deploy_blacklist) +
deploy_whitelist_to_constraints(system_deploy_whitelist)
)
def get_deploy_blacklist(self) -> DeployBlacklist:
"""The deploy blacklist is a list of lists, where the lists indicate
which locations the service should not be deployed"""
return safe_deploy_blacklist(self.config_dict.get('deploy_blacklist', []))
def get_deploy_whitelist(self) -> DeployWhitelist:
"""The deploy whitelist is a tuple of (location_type, [allowed value, allowed value, ...]).
To have tasks scheduled on it, a host must be covered by the deploy whitelist (if present) and not excluded by
the deploy blacklist."""
return safe_deploy_whitelist(self.config_dict.get('deploy_whitelist'))
def get_monitoring_blacklist(self, system_deploy_blacklist: DeployBlacklist) -> DeployBlacklist:
"""The monitoring_blacklist is a list of tuples of (location type, location value), where the tuples indicate
which locations the user doesn't care to be monitored"""
return (
safe_deploy_blacklist(self.config_dict.get('monitoring_blacklist', [])) +
self.get_deploy_blacklist() +
system_deploy_blacklist
)
def get_docker_image(self) -> str:
"""Get the docker image name (with tag) for a given service branch from
a generated deployments.json file."""
if self.branch_dict is not None:
return self.branch_dict['docker_image']
else:
return ''
def get_docker_url(self) -> str:
"""Compose the docker url.
:returns: '<registry_uri>/<docker_image>'
"""
registry_uri = self.get_docker_registry()
docker_image = self.get_docker_image()
if not docker_image:
raise NoDockerImageError('Docker url not available because there is no docker_image')
docker_url = '%s/%s' % (registry_uri, docker_image)
return docker_url
def get_desired_state(self) -> str:
"""Get the desired state (either 'start' or 'stop') for a given service
branch from a generated deployments.json file."""
if self.branch_dict is not None:
return self.branch_dict['desired_state']
else:
return 'start'
def get_force_bounce(self) -> Optional[str]:
"""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.
"""
if self.branch_dict is not None:
return self.branch_dict['force_bounce']
else:
return None
def check_cpus(self) -> Tuple[bool, str]:
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) -> Tuple[bool, str]:
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) -> Tuple[bool, str]:
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_gpus(self) -> Tuple[bool, str]:
gpus = self.get_gpus()
if gpus is not None and not isinstance(gpus, (float, int)):
return False, 'The specified gpus value "%s" is not a valid float or int.' % gpus
return True, ''
def check_security(self) -> Tuple[bool, str]:
security = self.config_dict.get('security')
if security is None:
return True, ''
outbound_firewall = security.get('outbound_firewall')
if outbound_firewall is None:
return True, ''
if outbound_firewall not in ('block', 'monitor'):
return False, 'Unrecognized outbound_firewall value "%s"' % outbound_firewall
unknown_keys = set(security.keys()) - {'outbound_firewall'}
if unknown_keys:
return False, 'Unrecognized items in security dict of service config: "%s"' % ','.join(unknown_keys)
return True, ''
def check_dependencies_reference(self) -> Tuple[bool, str]:
dependencies_reference = self.config_dict.get('dependencies_reference')
if dependencies_reference is None:
return True, ''
dependencies = self.config_dict.get('dependencies')
if dependencies is None:
return False, 'dependencies_reference "%s" declared but no dependencies found' % dependencies_reference
if dependencies_reference not in dependencies:
return False, 'dependencies_reference "%s" not found in dependencies dictionary' % dependencies_reference
return True, ''
def check(self, param: str) -> Tuple[bool, str]:
check_methods = {
'cpus': self.check_cpus,
'mem': self.check_mem,
'security': self.check_security,
'dependencies_reference': self.check_dependencies_reference,
}
check_method = check_methods.get(param)
if check_method is not None:
return check_method()
else:
return False, 'Your service config specifies "%s", an unsupported parameter.' % param
def validate(self) -> List[str]:
error_msgs = []
for param in ['cpus', 'mem', 'security', 'dependencies_reference']:
check_passed, check_msg = self.check(param)
if not check_passed:
error_msgs.append(check_msg)
return error_msgs
def get_extra_volumes(self) -> List[DockerVolume]:
"""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_role(self) -> Optional[str]:
"""Which mesos role of nodes this job should run on.
"""
return self.config_dict.get('role')
def get_pool(self) -> str:
"""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) -> List[Constraint]:
pool = self.get_pool()
return [["pool", "LIKE", pool]]
def get_constraints(self) -> Optional[List[Constraint]]:
return stringify_constraints(self.config_dict.get('constraints', None))
def get_extra_constraints(self) -> List[Constraint]:
return stringify_constraints(self.config_dict.get('extra_constraints', []))
def get_net(self) -> str:
"""
:returns: the docker networking mode the container should be started with.
"""
return self.config_dict.get('net', 'bridge')
def get_volumes(self, system_volumes: Sequence[DockerVolume]) -> List[DockerVolume]:
volumes = list(system_volumes) + list(self.get_extra_volumes())
deduped = {v['containerPath'].rstrip('/') + v['hostPath'].rstrip('/'): v for v in volumes}.values()
return sort_dicts(deduped)
def get_dependencies_reference(self) -> Optional[str]:
"""Get the reference to an entry in dependencies.yaml
Defaults to None if not specified in the config.
:returns: A string specified in the config, None if not specified"""
return self.config_dict.get('dependencies_reference')
def get_dependencies(self) -> Optional[Dict]:
"""Get the contents of the dependencies_dict pointed to by the dependency_reference or
'main' if no dependency_reference exists
Defaults to None if not specified in the config.
:returns: A list of dictionaries specified in the dependencies_dict, None if not specified"""
dependencies = self.config_dict.get('dependencies')
if not dependencies:
return None
dependency_ref = self.get_dependencies_reference() or 'main'
return dependencies.get(dependency_ref)
def get_outbound_firewall(self) -> Optional[str]:
"""Return 'block', 'monitor', or None as configured in security->outbound_firewall
Defaults to None if not specified in the config
:returns: A string specified in the config, None if not specified"""
security = self.config_dict.get('security')
if not security:
return None
return security.get('outbound_firewall')
def __eq__(self, other: Any) -> bool:
if isinstance(other, type(self)):
return self.config_dict == other.config_dict and \
self.branch_dict == other.branch_dict and \
self.cluster == other.cluster and \
self.instance == other.instance and \
self.service == other.service
else:
return False
def stringify_constraint(usc: UnstringifiedConstraint) -> Constraint:
return [str(x) for x in usc]
def stringify_constraints(uscs: Optional[List[UnstringifiedConstraint]]) -> List[Constraint]:
if uscs is None:
return None
return [stringify_constraint(usc) for usc in uscs]
@time_cache(ttl=60)
def validate_service_instance(service: str, instance: str, cluster: str, soa_dir: str) -> str:
for instance_type in INSTANCE_TYPES:
services = get_services_for_cluster(cluster=cluster, instance_type=instance_type, soa_dir=soa_dir)
if (service, instance) in services:
return instance_type
else:
raise NoConfigurationForServiceError(
"Error: %s doesn't look like it has been configured to run on the %s cluster." % (
compose_job_id(service, instance), cluster,
),
)
_ComposeRetT = TypeVar('_ComposeRetT')
_ComposeInnerRetT = TypeVar('_ComposeInnerRetT')
def compose(
func_one: Callable[[_ComposeInnerRetT], _ComposeRetT],
func_two: Callable[..., _ComposeInnerRetT],
) -> Callable[..., _ComposeRetT]:
def composed(*args: Any, **kwargs: Any) -> _ComposeRetT:
return func_one(func_two(*args, **kwargs))
return composed
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: str) -> str:
"""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: str) -> str:
"""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: str) -> str:
"""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: str) -> str:
"""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: str) -> str:
"""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: str, text: str) -> str:
"""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: str) -> str:
"""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: str) -> str:
"""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: str) -> str:
return PaastaColors.color_text(PaastaColors.GREY, text)
@staticmethod
def default(text: str) -> str:
return PaastaColors.color_text(PaastaColors.DEFAULT, text)
LOG_COMPONENTS = OrderedDict([
(
'build', {
'color': PaastaColors.blue,
'help': 'Jenkins build jobs output, like the itest, promotion, security checks, etc.',
'source_env': 'devc',
},
),
(
'deploy', {
'color': PaastaColors.cyan,
'help': 'Output from the paasta deploy code. (setup_marathon_job, bounces, etc)',
'additional_source_envs': ['devc'],
},
),
(
'monitoring', {
'color': PaastaColors.green,
'help': 'Logs from Sensu checks for the service',
},
),
(
'marathon', {
'color': PaastaColors.magenta,
'help': 'Logs from Marathon for the service',
},
),
(
'chronos', {
'color': PaastaColors.red,
'help': 'Logs from Chronos for the service',
},
),
(
'app_output', {
'color': compose(PaastaColors.yellow, PaastaColors.bold),
'help': 'Stderr and stdout of the actual process spawned by Mesos. '
'Convenience alias for both the stdout and stderr components',
},
),
(
'stdout', {
'color': PaastaColors.yellow,
'help': 'Stdout from the process spawned by Mesos.',
},
),
(
'stderr', {
'color': PaastaColors.yellow,
'help': 'Stderr from the process spawned by Mesos.',
},
),
(
'security', {
'color': PaastaColors.red,
'help': 'Logs from security-related services such as firewall monitoring',
},
),
(
'oom', {
'color': PaastaColors.red,
'help': 'Kernel OOM events.',
},
),
# 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_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: str) -> bool:
if component in LOG_COMPONENTS.keys():
return True
else:
raise NoSuchLogComponent
def get_git_url(service: str, soa_dir: str=DEFAULT_SOA_DIR) -> str:
"""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.
: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' % service
return general_config.get('git_url', default_location)
def get_service_docker_registry(
service: str,
soa_dir: str=DEFAULT_SOA_DIR,
system_config: Optional['SystemPaastaConfig']=None,
) -> str:
service_configuration = service_configuration_lib.read_service_configuration(service, soa_dir)
try:
return service_configuration['docker_registry']
except KeyError:
if not system_config:
system_config = load_system_paasta_config()
return system_config.get_system_docker_registry()