-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy path_install.py
More file actions
1452 lines (1226 loc) · 49.5 KB
/
_install.py
File metadata and controls
1452 lines (1226 loc) · 49.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.provision.test.test_install -*-
"""
Install flocker on a remote node.
"""
from pipes import quote
import posixpath
from textwrap import dedent
from urlparse import urljoin, urlparse
from effect import Func, Effect, parallel
import yaml
from zope.interface import implementer
from characteristic import attributes
from pyrsistent import PRecord, field
from twisted.internet.error import ProcessTerminated
from ._libcloud import INode
from ._common import PackageSource, Variants
from ._ssh import (
run, run_from_args, Run,
sudo_from_args, Sudo,
put,
run_remotely,
)
from ._effect import sequence
from flocker import __version__ as version
from flocker.cli import configure_ssh
from flocker.common.version import (
get_installable_version, get_package_key_suffix, is_release,
)
# A systemctl sub-command to start or restart a service. We use restart here
# so that if it is already running it gets restart (possibly necessary to
# respect updated configuration) and because restart will also start it if it
# is not running.
START = "restart"
ZFS_REPO = {
'centos-7': "https://s3.amazonaws.com/archive.zfsonlinux.org/"
"epel/zfs-release.el7.noarch.rpm",
}
ARCHIVE_BUCKET = 'clusterhq-archive'
def is_centos(distribution):
"""
Determine whether the named distribution is a version of CentOS.
:param bytes distribution: The name of the distribution to inspect.
:return: ``True`` if the distribution named is a version of CentOS,
``False`` otherwise.
"""
return distribution.startswith("centos-")
def is_ubuntu(distribution):
"""
Determine whether the named distribution is a version of Ubuntu.
:param bytes distribution: The name of the distribution to inspect.
:return: ``True`` if the distribution named is a version of Ubuntu,
``False`` otherwise.
"""
return distribution.startswith("ubuntu-")
def get_repository_url(distribution, flocker_version):
"""
Return the URL for the repository of a given distribution.
For ``yum``-using distributions this gives the URL to a package that adds
entries to ``/etc/yum.repos.d``. For ``apt``-using distributions, this
gives the URL for a repo containing a Packages(.gz) file.
:param bytes distribution: The Linux distribution to get a repository for.
:param bytes flocker_version: The version of Flocker to get a repository
for.
:return bytes: The URL pointing to a repository of packages.
:raises: ``UnsupportedDistribution`` if the distribution is unsupported.
"""
distribution_to_url = {
# TODO instead of hardcoding keys, use the _to_Distribution map
# and then choose the name
'centos-7': "https://{archive_bucket}.s3.amazonaws.com/"
"{key}/clusterhq-release$(rpm -E %dist).noarch.rpm".format(
archive_bucket=ARCHIVE_BUCKET,
key='centos',
),
# This could hardcode the version number instead of using
# ``lsb_release`` but that allows instructions to be shared between
# versions, and for earlier error reporting if you try to install on a
# separate version. The $(ARCH) part must be left unevaluated, hence
# the backslash escapes (one to make shell ignore the $ as a
# substitution marker, and then doubled to make Python ignore the \ as
# an escape marker). The output of this value then goes into
# /etc/apt/sources.list which does its own substitution on $(ARCH)
# during a subsequent apt-get update
'ubuntu-14.04': 'https://{archive_bucket}.s3.amazonaws.com/{key}/'
'$(lsb_release --release --short)/\\$(ARCH)'.format(
archive_bucket=ARCHIVE_BUCKET,
key='ubuntu' + get_package_key_suffix(
flocker_version),
),
'ubuntu-15.04': 'https://{archive_bucket}.s3.amazonaws.com/{key}/'
'$(lsb_release --release --short)/\\$(ARCH)'.format(
archive_bucket=ARCHIVE_BUCKET,
key='ubuntu' + get_package_key_suffix(
flocker_version),
),
}
try:
return distribution_to_url[distribution]
except KeyError:
raise UnsupportedDistribution()
def get_repo_options(flocker_version):
"""
Get a list of options for enabling necessary yum repositories.
:param bytes flocker_version: The version of Flocker to get options for.
:return: List of bytes for enabling (or not) a testing repository.
"""
is_dev = not is_release(flocker_version)
if is_dev:
return ['--enablerepo=clusterhq-testing']
else:
return []
class UnsupportedDistribution(Exception):
"""
Raised if trying to support a distribution which is not supported.
"""
@attributes(['distribution'])
class DistributionNotSupported(NotImplementedError):
"""
Raised when the provisioning step is not supported on the given
distribution.
:ivar bytes distribution: The distribution that isn't supported.
"""
def __str__(self):
return "Distribution not supported: %s" % (self.distribution,)
@implementer(INode)
class ManagedNode(PRecord):
"""
A node managed by some other system (eg by hand or by another piece of
orchestration software).
"""
address = field(type=bytes, mandatory=True)
private_address = field(type=(bytes, type(None)),
initial=None, mandatory=True)
distribution = field(type=bytes, mandatory=True)
def ensure_minimal_setup(package_manager):
"""
Get any system into a reasonable state for installation.
Although we could publish these commands in the docs, they add a lot
of noise for many users. Ensure that systems have sudo enabled.
:param bytes package_manager: The package manager (apt, dnf, yum).
:return: a sequence of commands to run on the distribution
"""
if package_manager in ('dnf', 'yum'):
# Fedora/CentOS sometimes configured to require tty for sudo
# ("sorry, you must have a tty to run sudo"). Disable that to
# allow automated tests to run.
return sequence([
run_from_args([
'su', 'root', '-c', [package_manager, '-y', 'install', 'sudo']
]),
run_from_args([
'su', 'root', '-c', [
'sed', '--in-place', '-e',
's/Defaults.*requiretty/Defaults !requiretty/',
'/etc/sudoers'
]]),
])
elif package_manager == 'apt':
return sequence([
run_from_args(['su', 'root', '-c', ['apt-get', 'update']]),
run_from_args([
'su', 'root', '-c', ['apt-get', '-y', 'install', 'sudo']
]),
])
else:
raise UnsupportedDistribution()
def cli_pkg_test(package_source=PackageSource()):
"""
Check that the Flocker CLI is working and has the expected version.
:param PackageSource package_source: The source from which to install the
package.
:return: An ``Effect`` to pass to a ``Dispatcher`` that supports
``Sequence``, ``Run``, ``Sudo``, ``Comment``, and ``Put``.
"""
expected = package_source.version
if not expected:
if package_source.branch:
# If branch is set but version isn't, we don't know the
# latest version. In this case, just check that the version
# can be displayed.
return run('flocker-deploy --version')
else:
# If neither branch nor version is set, the latest
# installable release will be installed.
expected = get_installable_version(version)
return run('test `flocker-deploy --version` = {}'.format(quote(expected)))
def wipe_yum_cache(repository):
"""
Force yum to update the metadata for a particular repository.
:param bytes repository: The name of the repository to clear.
"""
return run_from_args([
b"yum",
b"--disablerepo=*",
b"--enablerepo=" + repository,
b"clean",
b"expire-cache"
])
def install_commands_yum(package_name, distribution, package_source, base_url):
"""
Install Flocker package on CentOS.
The ClusterHQ repo is added for downloading latest releases. If
``package_source`` contains a branch, then a BuildBot repo will also
be added to the package search path, to use in-development packages.
Note, the ClusterHQ repo is always enabled, to provide dependencies.
:param str package_name: The name of the package to install.
:param bytes distribution: The distribution the node is running.
:param PackageSource package_source: The source from which to install the
package.
:param base_url: URL of repository, or ``None`` if we're not using
development branch.
:return: a sequence of commands to run on the distribution
"""
flocker_version = package_source.version
if not flocker_version:
# support empty values other than None, as '' sometimes used to
# indicate latest version, due to previous behaviour
flocker_version = get_installable_version(version)
repo_package_name = 'clusterhq-release'
commands = [
# If package has previously been installed, 'yum install' fails,
# so check if it is installed first.
run(
command="yum list installed {} || yum install -y {}".format(
quote(repo_package_name),
get_repository_url(
distribution=distribution,
flocker_version=flocker_version))),
]
if base_url is not None:
repo = dedent(b"""\
[clusterhq-build]
name=clusterhq-build
baseurl=%s
gpgcheck=0
enabled=0
# There is a distinct clusterhq-build repository for each branch.
# The metadata across these different repositories varies. Version
# numbers are not comparable. A version which exists in one likely
# does not exist in another. In order to support switching between
# branches (and therefore between clusterhq-build repositories),
# tell yum to always update metadata for this repository.
metadata_expire=0
""") % (base_url,)
commands.append(put(content=repo,
path='/tmp/clusterhq-build.repo'))
commands.append(run_from_args([
'cp', '/tmp/clusterhq-build.repo',
'/etc/yum.repos.d/clusterhq-build.repo']))
repo_options = ['--enablerepo=clusterhq-build']
else:
repo_options = get_repo_options(
flocker_version=get_installable_version(version))
os_version = package_source.os_version()
if os_version:
package_name += '-%s' % (os_version,)
# Install package and all dependencies:
commands.append(run_from_args(
["yum", "install"] + repo_options + ["-y", package_name]))
return sequence(commands)
def install_commands_ubuntu(package_name, distribution, package_source,
base_url):
"""
Install Flocker package on Ubuntu.
The ClusterHQ repo is added for downloading latest releases. If
``package_source`` contains a branch, then a BuildBot repo will also
be added to the package search path, to use in-development packages.
Note, the ClusterHQ repo is always enabled, to provide dependencies.
:param bytes distribution: The distribution the node is running.
:param PackageSource package_source: The source from which to install the
package.
:param base_url: URL of repository, or ``None`` if we're not using
development branch.
:return: a sequence of commands to run on the distribution
"""
flocker_version = package_source.version
if not flocker_version:
# support empty values other than None, as '' sometimes used to
# indicate latest version, due to previous behaviour
flocker_version = get_installable_version(version)
commands = [
# Minimal images often have cleared apt caches and are missing
# packages that are common in a typical release. These commands
# ensure that we start from a good base system with the required
# capabilities, particularly that the add-apt-repository command
# is available, and HTTPS URLs are supported.
run_from_args(["apt-get", "update"]),
run_from_args([
"apt-get", "-y", "install", "apt-transport-https",
"software-properties-common"]),
# Add ClusterHQ repo for installation of Flocker packages.
run(command='add-apt-repository -y "deb {} /"'.format(
get_repository_url(
distribution=distribution,
flocker_version=flocker_version)))
]
if base_url is not None:
# Add BuildBot repo for running tests
commands.append(run_from_args([
"add-apt-repository", "-y", "deb {} /".format(base_url)]))
# During a release, the ClusterHQ repo may contain packages with
# a higher version number than the Buildbot repo for a branch.
# Use a pin file to ensure that any Buildbot repo has higher
# priority than the ClusterHQ repo. We only add the Buildbot
# repo when a branch is specified, so it wil not interfere with
# attempts to install a release (when no branch is specified).
buildbot_host = urlparse(package_source.build_server).hostname
commands.append(put(dedent('''\
Package: *
Pin: origin {}
Pin-Priority: 700
'''.format(buildbot_host)), '/tmp/apt-pref'))
commands.append(run_from_args([
'mv', '/tmp/apt-pref', '/etc/apt/preferences.d/buildbot-700']))
# Update to read package info from new repos
commands.append(run_from_args(["apt-get", "update"]))
os_version = package_source.os_version()
if os_version:
# Set the version of the top-level package
package_name += '=%s' % (os_version,)
# If a specific version is required, ensure that the version for
# all ClusterHQ packages is consistent. This prevents conflicts
# between the top-level package, which may depend on a lower
# version of a dependency, and apt, which wants to install the
# most recent version. Note that this trumps the Buildbot
# pinning above.
commands.append(put(dedent('''\
Package: clusterhq-*
Pin: version {}
Pin-Priority: 900
'''.format(os_version)), '/tmp/apt-pref'))
commands.append(run_from_args([
'mv', '/tmp/apt-pref', '/etc/apt/preferences.d/clusterhq-900']))
# Install package and all dependencies
commands.append(run_from_args([
'apt-get', '-y', '--force-yes', 'install', package_name]))
return sequence(commands)
def task_package_install(package_name, distribution,
package_source=PackageSource()):
"""
Install Flocker package on a distribution.
The ClusterHQ repo is added for downloading latest releases. If
``package_source`` contains a branch, then a BuildBot repo will also
be added to the package search path, to use in-development packages.
Note, the ClusterHQ repo is always enabled, to provide dependencies.
:param str package_name: The name of the package to install.
:param bytes distribution: The distribution the node is running.
:param PackageSource package_source: The source from which to install the
package.
:return: a sequence of commands to run on the distribution
"""
if package_source.branch:
# A development branch has been selected - add its Buildbot repo
result_path = posixpath.join(
'/results/omnibus/', package_source.branch, distribution)
base_url = urljoin(package_source.build_server, result_path)
else:
base_url = None
if is_centos(distribution):
installer = install_commands_yum
elif is_ubuntu(distribution):
installer = install_commands_ubuntu
else:
raise UnsupportedDistribution()
return installer(package_name, distribution, package_source,
base_url)
def task_cli_pkg_install(distribution, package_source=PackageSource()):
"""
Install the Flocker CLI package.
:param bytes distribution: The distribution the node is running.
:param PackageSource package_source: The source from which to install the
package.
:return: a sequence of commands to run on the distribution
"""
commands = task_package_install("clusterhq-flocker-cli", distribution,
package_source)
# Although client testing is currently done as root.e want to use
# sudo for better documentation output.
return sequence([
(Effect(Sudo(command=e.intent.command,
log_command_filter=e.intent.log_command_filter))
if isinstance(e.intent, Run) else e)
for e in commands.intent.effects])
PIP_CLI_PREREQ_APT = [
'gcc',
'libffi-dev',
'libssl-dev',
'python2.7',
'python2.7-dev',
'python-virtualenv',
]
PIP_CLI_PREREQ_YUM = [
'gcc',
'libffi-devel',
'openssl-devel',
'python',
'python-devel',
'python-virtualenv',
]
def task_cli_pip_prereqs(package_manager):
"""
Install the pre-requisites for pip installation of the Flocker client.
:param bytes package_manager: The package manager (apt, dnf, yum).
:return: an Effect to install the pre-requisites.
"""
if package_manager in ('dnf', 'yum'):
return sudo_from_args(
[package_manager, '-y', 'install'] + PIP_CLI_PREREQ_YUM
)
elif package_manager == 'apt':
return sequence([
sudo_from_args(['apt-get', 'update']),
sudo_from_args(['apt-get', '-y', 'install'] + PIP_CLI_PREREQ_APT),
])
else:
raise UnsupportedDistribution()
def _get_wheel_version(package_source):
"""
Get the latest available wheel version for the specified package source.
If package source version is not set, the latest installable release
will be installed. Note, branch is never used for wheel
installations, since the wheel file is not created for branches.
:param PackageSource package_source: The source from which to install the
package.
:return: a string containing the previous installable version of
either the package version, or, if that is not specified, of the
current version.
"""
return get_installable_version(package_source.version or version)
def task_cli_pip_install(
venv_name='flocker-client', package_source=PackageSource()):
"""
Install the Flocker client into a virtualenv using pip.
:param bytes venv_name: Name for the virtualenv.
:param package_source: Package source description
:return: an Effect to install the client.
"""
url = (
'https://{bucket}.s3.amazonaws.com/{key}/'
'Flocker-{version}-py2-none-any.whl'.format(
bucket=ARCHIVE_BUCKET, key='python',
version=_get_wheel_version(package_source))
)
return sequence([
run_from_args(
['virtualenv', '--python=/usr/bin/python2.7', venv_name]),
run_from_args(['source', '{}/bin/activate'.format(venv_name)]),
run_from_args(['pip', 'install', '--upgrade', 'pip']),
run_from_args(
['pip', 'install', url]),
])
def cli_pip_test(venv_name='flocker-client', package_source=PackageSource()):
"""
Test the Flocker client installed in a virtualenv.
:param bytes venv_name: Name for the virtualenv.
:return: an Effect to test the client.
"""
return sequence([
run_from_args(['source', '{}/bin/activate'.format(venv_name)]),
run('test `flocker-deploy --version` = {}'.format(
quote(_get_wheel_version(package_source))))
])
def task_configure_brew_path():
"""
Configure non-interactive shell to use all paths.
By default, OSX provides a minimal $PATH, for programs run via SSH. In
particular /usr/local/bin (which contains `brew`) isn't in the path. This
configures the path to have it there.
"""
return put(
path='.bashrc',
content=dedent("""\
if [ -x /usr/libexec/path_helper ]; then
eval `/usr/libexec/path_helper -s`
fi
"""))
def task_test_homebrew(recipe):
"""
The commands used to install a Homebrew recipe for Flocker and test it.
This taps the ClusterHQ/tap tap, which means that Homebrew looks in the
ClusterHQ/homebrew-tap GitHub repository for any recipe name given.
:param bytes recipe: The name of a recipe in a either the official Homebrew
tap or ClusterHQ/tap, or a URL pointing to a recipe.
:return Effect: Commands used to install a Homebrew recipe for Flocker and
test it.
"""
return sequence([
run_from_args(['brew', 'tap', 'ClusterHQ/tap']),
run("brew update"),
run("brew install {recipe}".format(recipe=recipe)),
run("brew test {recipe}".format(recipe=recipe)),
])
def task_install_ssh_key():
"""
Install the authorized ssh keys of the current user for root as well.
"""
return sequence([
sudo_from_args(['cp', '.ssh/authorized_keys',
'/root/.ssh/authorized_keys']),
])
def task_upgrade_kernel(distribution):
"""
Upgrade kernel.
"""
if is_centos(distribution):
return sequence([
run_from_args([
"yum", "install", "-y", "kernel-devel", "kernel"]),
run_from_args(['sync']),
])
elif distribution == 'ubuntu-14.04':
# Not required.
return sequence([])
else:
raise DistributionNotSupported(distribution=distribution)
def _remove_private_key(content):
"""
Remove most of the contents of a private key file for logging.
"""
prefix = '-----BEGIN PRIVATE KEY-----'
suffix = '-----END PRIVATE KEY-----'
start = content.find(prefix)
if start < 0:
# no private key
return content
# Keep prefix, subsequent newline, and 4 characters at start of key
trim_start = start + len(prefix) + 5
end = content.find(suffix, trim_start)
if end < 0:
end = len(content)
# Keep suffix and previous 4 characters and newline at end of key
trim_end = end - 5
if trim_end <= trim_start:
# strangely short key, keep all content
return content
return content[:trim_start] + '...REMOVED...' + content[trim_end:]
def task_install_control_certificates(ca_cert, control_cert, control_key):
"""
Install certificates and private key required by the control service.
:param FilePath ca_cert: Path to CA certificate on local machine.
:param FilePath control_cert: Path to control service certificate on
local machine.
:param FilePath control_key: Path to control service private key
local machine.
"""
# Be better if permissions were correct from the start.
# https://clusterhq.atlassian.net/browse/FLOC-1922
return sequence([
run('mkdir -p /etc/flocker'),
run('chmod u=rwX,g=,o= /etc/flocker'),
put(path="/etc/flocker/cluster.crt", content=ca_cert.getContent()),
put(path="/etc/flocker/control-service.crt",
content=control_cert.getContent()),
put(path="/etc/flocker/control-service.key",
content=control_key.getContent(),
log_content_filter=_remove_private_key),
])
def task_install_node_certificates(ca_cert, node_cert, node_key):
"""
Install certificates and private key required by a node.
:param FilePath ca_cert: Path to CA certificate on local machine.
:param FilePath node_cert: Path to node certificate on
local machine.
:param FilePath node_key: Path to node private key
local machine.
"""
# Be better if permissions were correct from the start.
# https://clusterhq.atlassian.net/browse/FLOC-1922
return sequence([
run('mkdir -p /etc/flocker'),
run('chmod u=rwX,g=,o= /etc/flocker'),
put(path="/etc/flocker/cluster.crt", content=ca_cert.getContent()),
put(path="/etc/flocker/node.crt",
content=node_cert.getContent()),
put(path="/etc/flocker/node.key",
content=node_key.getContent(),
log_content_filter=_remove_private_key),
])
def task_install_api_certificates(api_cert, api_key):
"""
Install certificate and private key required by Docker plugin to
access the Flocker REST API.
:param FilePath api_cert: Path to API certificate on local machine.
:param FilePath api_key: Path to API private key local machine.
"""
# Be better if permissions were correct from the start.
# https://clusterhq.atlassian.net/browse/FLOC-1922
return sequence([
run('mkdir -p /etc/flocker'),
run('chmod u=rwX,g=,o= /etc/flocker'),
put(path="/etc/flocker/plugin.crt",
content=api_cert.getContent()),
put(path="/etc/flocker/plugin.key",
content=api_key.getContent(),
log_content_filter=_remove_private_key),
])
def task_enable_docker(distribution):
"""
Configure docker.
We don't actually start it (or on Ubuntu, restart it) at this point
since the certificates it relies on have yet to be installed.
"""
# Use the Flocker node TLS certificate, since it's readily
# available.
docker_tls_options = (
'--tlsverify --tlscacert=/etc/flocker/cluster.crt'
' --tlscert=/etc/flocker/node.crt --tlskey=/etc/flocker/node.key'
' -H=0.0.0.0:2376')
if is_centos(distribution):
conf_path = (
"/etc/systemd/system/docker.service.d/01-TimeoutStartSec.conf"
)
return sequence([
# Give Docker a long time to start up. On the first start, it
# initializes a 100G filesystem which can take a while. The
# default startup timeout is frequently too low to let this
# complete.
run("mkdir -p /etc/systemd/system/docker.service.d"),
put(
path=conf_path,
content=dedent(
"""\
[Service]
TimeoutStartSec=10min
"""
),
),
put(path="/etc/systemd/system/docker.service.d/02-TLS.conf",
content=dedent(
"""\
[Service]
ExecStart=
ExecStart=/usr/bin/docker daemon -H fd:// {}
""".format(docker_tls_options))),
run_from_args(["systemctl", "enable", "docker.service"]),
])
elif distribution == 'ubuntu-14.04':
return sequence([
put(path="/etc/default/docker",
content=(
'DOCKER_OPTS="-H unix:///var/run/docker.sock {}"'.format(
docker_tls_options))),
])
else:
raise DistributionNotSupported(distribution=distribution)
def open_firewalld(service):
"""
Open firewalld port for a service.
:param str service: Name of service.
"""
return sequence([run_from_args(['firewall-cmd', '--reload'])] + [
run_from_args(command + [service])
for command in [['firewall-cmd', '--permanent', '--add-service'],
['firewall-cmd', '--add-service']]])
def open_ufw(service):
"""
Open ufw port for a service.
:param str service: Name of service.
"""
return sequence([
run_from_args(['ufw', 'allow', service])
])
def task_enable_flocker_control(distribution):
"""
Enable flocker-control service.
"""
if is_centos(distribution):
return sequence([
run_from_args(['systemctl', 'enable', 'flocker-control']),
run_from_args(['systemctl', START, 'flocker-control']),
])
elif distribution == 'ubuntu-14.04':
# Since the flocker-control service is currently installed
# alongside the flocker-dataset-agent service, the default control
# service configuration does not automatically start the
# service. Here, we provide an override file to start it.
return sequence([
put(
path='/etc/init/flocker-control.override',
content=dedent('''\
start on runlevel [2345]
stop on runlevel [016]
'''),
),
run("echo 'flocker-control-api\t4523/tcp\t\t\t# Flocker Control API port' >> /etc/services"), # noqa
run("echo 'flocker-control-agent\t4524/tcp\t\t\t# Flocker Control Agent port' >> /etc/services"), # noqa
run_from_args(['service', 'flocker-control', 'start']),
])
else:
raise DistributionNotSupported(distribution=distribution)
def task_enable_docker_plugin(distribution):
"""
Enable the Flocker Docker plugin.
:param bytes distribution: The distribution name.
"""
if is_centos(distribution):
return sequence([
run_from_args(['systemctl', 'enable', 'flocker-docker-plugin']),
run_from_args(['systemctl', START, 'flocker-docker-plugin']),
run_from_args(['systemctl', START, 'docker']),
])
elif distribution == 'ubuntu-14.04':
return sequence([
run_from_args(['service', 'flocker-docker-plugin', 'restart']),
run_from_args(['service', 'docker', 'restart']),
])
else:
raise DistributionNotSupported(distribution=distribution)
def task_open_control_firewall(distribution):
"""
Open the firewall for flocker-control.
"""
if is_centos(distribution):
open_firewall = open_firewalld
elif distribution == 'ubuntu-14.04':
open_firewall = open_ufw
else:
raise DistributionNotSupported(distribution=distribution)
return sequence([
open_firewall(service)
for service in ['flocker-control-api', 'flocker-control-agent']
])
def catch_exit_code(expected_exit_code):
"""
:param int expected_exit_code: The expected exit code of the process.
:returns: An error handler function which accepts a 3-tuple(exception_type,
exception, None) and re-raises ``exception`` if the exit code is not
``expected_exit_code`.
"""
def error_handler(result):
exception_type, exception = result[:2]
if((exception_type is not ProcessTerminated) or
(exception.exitCode != expected_exit_code)):
raise exception
return error_handler
def if_firewall_available(distribution, commands):
"""
Open the firewall for remote access to control service if firewall command
is available.
"""
if is_centos(distribution):
firewall_command = b'firewall-cmd'
elif distribution == 'ubuntu-14.04':
firewall_command = b'ufw'
else:
raise DistributionNotSupported(distribution=distribution)
# Only run the commands if the firewall command is available.
return run_from_args([b'which', firewall_command]).on(
success=lambda result: commands,
error=catch_exit_code(1),
)
def open_firewall_for_docker_api(distribution):
"""
Open the firewall for remote access to Docker API.
"""
if is_centos(distribution):
upload = put(path="/usr/lib/firewalld/services/docker.xml",
content=dedent(
"""\
<?xml version="1.0" encoding="utf-8"?>
<service>
<short>Docker API Port</short>
<description>The Docker API, over TLS.</description>
<port protocol="tcp" port="2376"/>
</service>
"""))
open_firewall = open_firewalld
elif distribution == 'ubuntu-14.04':
upload = put(path="/etc/ufw/applications.d/docker",
content=dedent(
"""
[docker]
title=Docker API
description=Docker API.
ports=2376/tcp
"""))
open_firewall = open_ufw
else:
raise DistributionNotSupported(distribution=distribution)
# Only configure the firewall if the firewall command line is available.
return sequence([upload, open_firewall('docker')])
# Set of dataset fields which are *not* sensitive. Only fields in this
# set are logged. This should contain everything except usernames and
# passwords (or equivalents). Implemented as a whitelist in case new
# security fields are added.
_ok_to_log = frozenset((
'auth_plugin',
'auth_url',
'backend',
'region',
'zone',
))
def _remove_dataset_fields(content):
"""
Remove non-whitelisted fields from dataset for logging.
"""
content = yaml.safe_load(content)
dataset = content['dataset']
for key in dataset:
if key not in _ok_to_log:
dataset[key] = 'REMOVED'
return yaml.safe_dump(content)
def task_configure_flocker_agent(control_node, dataset_backend,
dataset_backend_configuration,
public_ip=None):
"""
Configure the flocker agents by writing out the configuration file.
:param bytes control_node: The address of the control agent.
:param DatasetBackend dataset_backend: The volume backend the nodes are
configured with.
:param dict dataset_backend_configuration: The backend specific
configuration options.
"""
dataset_backend_configuration = dataset_backend_configuration.copy()
dataset_backend_configuration.update({
u"backend": dataset_backend.name,
})
agent_config = {
"version": 1,
"control-service": {
"hostname": control_node,
"port": 4524,
},
"dataset": dataset_backend_configuration,
}
if public_ip is not None:
agent_config['hostname'] = public_ip
put_config_file = put(
path='/etc/flocker/agent.yml',
content=yaml.safe_dump(agent_config),
log_content_filter=_remove_dataset_fields
)
return sequence([put_config_file])
def task_enable_flocker_agent(distribution):
"""
Enable the flocker agents.
:param bytes distribution: The distribution name.
"""
if is_centos(distribution):
return sequence([
run_from_args(['systemctl', 'enable', 'flocker-dataset-agent']),
run_from_args(['systemctl', START, 'flocker-dataset-agent']),