summaryrefslogtreecommitdiffstats
path: root/utils/src/ooinstall/openshift_ansible.py
blob: 9afc9a644f5168b40245213a5b608faef0a3fdd6 (plain)
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
# TODO: Temporarily disabled due to importing old code into openshift-ansible
# repo. We will work on these over time.
# pylint: disable=bad-continuation,missing-docstring,no-self-use,invalid-name,global-statement,global-variable-not-assigned

import socket
import subprocess
import sys
import os
import yaml
from ooinstall.variants import find_variant

CFG = None

def set_config(cfg):
    global CFG
    CFG = cfg

def generate_inventory(hosts):
    global CFG
    masters = [host for host in hosts if host.master]
    nodes = [host for host in hosts if host.node]
    proxy = determine_proxy_configuration(hosts)
    multiple_masters = len(masters) > 1

    base_inventory_path = CFG.settings['ansible_inventory_path']
    base_inventory = open(base_inventory_path, 'w')

    write_inventory_children(base_inventory, multiple_masters, proxy)

    write_inventory_vars(base_inventory, multiple_masters, proxy)

    # Find the correct deployment type for ansible:
    ver = find_variant(CFG.settings['variant'],
        version=CFG.settings.get('variant_version', None))[1]
    base_inventory.write('deployment_type={}\n'.format(ver.ansible_key))

    if 'OO_INSTALL_ADDITIONAL_REGISTRIES' in os.environ:
        base_inventory.write('cli_docker_additional_registries={}\n'
          .format(os.environ['OO_INSTALL_ADDITIONAL_REGISTRIES']))
    if 'OO_INSTALL_INSECURE_REGISTRIES' in os.environ:
        base_inventory.write('cli_docker_insecure_registries={}\n'
          .format(os.environ['OO_INSTALL_INSECURE_REGISTRIES']))
    if 'OO_INSTALL_PUDDLE_REPO' in os.environ:
        # We have to double the '{' here for literals
        base_inventory.write("openshift_additional_repos=[{{'id': 'ose-devel', "
            "'name': 'ose-devel', "
            "'baseurl': '{}', "
            "'enabled': 1, 'gpgcheck': 0}}]\n".format(os.environ['OO_INSTALL_PUDDLE_REPO']))

    base_inventory.write('\n[masters]\n')
    for master in masters:
        write_host(master, base_inventory)

    if len(masters) > 1:
        base_inventory.write('\n[etcd]\n')
        for master in masters:
            write_host(master, base_inventory)

    base_inventory.write('\n[nodes]\n')

    # TODO: It would be much better to calculate the scheduleability elsewhere
    # and store it on the Node object.
    if set(nodes) == set(masters):
        for node in nodes:
            write_host(node, base_inventory)
    else:
        for node in nodes:
            # TODO: Until the Master can run the SDN itself we have to configure the Masters
            # as Nodes too.
            scheduleable = True
            if node in masters:
                scheduleable = False
            write_host(node, base_inventory, scheduleable)

    if not getattr(proxy, 'preconfigured', True):
        base_inventory.write('\n[lb]\n')
        write_host(proxy, base_inventory)

    base_inventory.close()
    return base_inventory_path

def determine_proxy_configuration(hosts):
    proxy = next((host for host in hosts if host.master_lb), None)
    if proxy:
        if proxy.hostname == None:
            proxy.hostname = proxy.connect_to
            proxy.public_hostname = proxy.connect_to
        return proxy

    return None

def write_inventory_children(base_inventory, multiple_masters, proxy):
    global CFG

    base_inventory.write('\n[OSEv3:children]\n')
    base_inventory.write('masters\n')
    base_inventory.write('nodes\n')
    if multiple_masters:
        base_inventory.write('etcd\n')
    if not getattr(proxy, 'preconfigured', True):
        base_inventory.write('lb\n')

def write_inventory_vars(base_inventory, multiple_masters, proxy):
    global CFG
    base_inventory.write('\n[OSEv3:vars]\n')
    base_inventory.write('ansible_ssh_user={}\n'.format(CFG.settings['ansible_ssh_user']))
    if CFG.settings['ansible_ssh_user'] != 'root':
        base_inventory.write('ansible_become=true\n')
    if multiple_masters:
        base_inventory.write('openshift_master_cluster_method=native\n')
        base_inventory.write("openshift_master_cluster_hostname={}\n".format(proxy.hostname))
        base_inventory.write("openshift_master_cluster_public_hostname={}\n".format(proxy.public_hostname))


def write_host(host, inventory, scheduleable=True):
    global CFG

    facts = ''
    if host.ip:
        facts += ' openshift_ip={}'.format(host.ip)
    if host.public_ip:
        facts += ' openshift_public_ip={}'.format(host.public_ip)
    if host.hostname:
        facts += ' openshift_hostname={}'.format(host.hostname)
    if host.public_hostname:
        facts += ' openshift_public_hostname={}'.format(host.public_hostname)
    # TODO: For not write_host is handles both master and nodes.
    # Technically only nodes will ever need this.
    if not scheduleable:
        facts += ' openshift_scheduleable=False'
    installer_host = socket.gethostname()
    if installer_host in [host.connect_to, host.hostname, host.public_hostname]:
        facts += ' ansible_connection=local'
        if os.geteuid() != 0:
            no_pwd_sudo = subprocess.call(['sudo', '-n', 'echo', 'openshift'])
            if no_pwd_sudo == 1:
                print 'The atomic-openshift-installer requires sudo access without a password.'
                sys.exit(1)
            facts += ' ansible_become=true'

    inventory.write('{} {}\n'.format(host.connect_to, facts))


def load_system_facts(inventory_file, os_facts_path, env_vars, verbose=False):
    """
    Retrieves system facts from the remote systems.
    """
    FNULL = open(os.devnull, 'w')
    args = ['ansible-playbook', '-v'] if verbose \
        else ['ansible-playbook']
    args.extend([
        '--inventory-file={}'.format(inventory_file),
        os_facts_path])
    status = subprocess.call(args, env=env_vars, stdout=FNULL)
    if not status == 0:
        return [], 1
    callback_facts_file = open(CFG.settings['ansible_callback_facts_yaml'], 'r')
    callback_facts = yaml.load(callback_facts_file)
    callback_facts_file.close()
    return callback_facts, 0


def default_facts(hosts, verbose=False):
    global CFG
    inventory_file = generate_inventory(hosts)
    os_facts_path = '{}/playbooks/byo/openshift_facts.yml'.format(CFG.ansible_playbook_directory)

    facts_env = os.environ.copy()
    facts_env["OO_INSTALL_CALLBACK_FACTS_YAML"] = CFG.settings['ansible_callback_facts_yaml']
    facts_env["ANSIBLE_CALLBACK_PLUGINS"] = CFG.settings['ansible_plugins_directory']
    facts_env["OPENSHIFT_MASTER_CLUSTER_METHOD"] = 'native'
    if 'ansible_log_path' in CFG.settings:
        facts_env["ANSIBLE_LOG_PATH"] = CFG.settings['ansible_log_path']
    if 'ansible_config' in CFG.settings:
        facts_env['ANSIBLE_CONFIG'] = CFG.settings['ansible_config']
    return load_system_facts(inventory_file, os_facts_path, facts_env, verbose)


def run_main_playbook(hosts, hosts_to_run_on, verbose=False):
    global CFG
    inventory_file = generate_inventory(hosts_to_run_on)
    if len(hosts_to_run_on) != len(hosts):
        main_playbook_path = os.path.join(CFG.ansible_playbook_directory,
                                          'playbooks/byo/openshift-cluster/scaleup.yml')
    else:
        main_playbook_path = os.path.join(CFG.ansible_playbook_directory,
                                          'playbooks/byo/openshift-cluster/config.yml')
    facts_env = os.environ.copy()
    if 'ansible_log_path' in CFG.settings:
        facts_env['ANSIBLE_LOG_PATH'] = CFG.settings['ansible_log_path']
    if 'ansible_config' in CFG.settings:
        facts_env['ANSIBLE_CONFIG'] = CFG.settings['ansible_config']
    return run_ansible(main_playbook_path, inventory_file, facts_env, verbose)


def run_ansible(playbook, inventory, env_vars, verbose=False):
    args = ['ansible-playbook', '-v'] if verbose \
        else ['ansible-playbook']
    args.extend([
        '--inventory-file={}'.format(inventory),
        playbook])
    return subprocess.call(args, env=env_vars)


def run_uninstall_playbook(verbose=False):
    playbook = os.path.join(CFG.settings['ansible_playbook_directory'],
        'playbooks/adhoc/uninstall.yml')
    inventory_file = generate_inventory(CFG.hosts)
    facts_env = os.environ.copy()
    if 'ansible_log_path' in CFG.settings:
        facts_env['ANSIBLE_LOG_PATH'] = CFG.settings['ansible_log_path']
    if 'ansible_config' in CFG.settings:
        facts_env['ANSIBLE_CONFIG'] = CFG.settings['ansible_config']
    return run_ansible(playbook, inventory_file, facts_env, verbose)


def run_upgrade_playbook(verbose=False):
    # TODO: do not hardcode the upgrade playbook, add ability to select the
    # right playbook depending on the type of upgrade.
    playbook = os.path.join(CFG.settings['ansible_playbook_directory'],
        'playbooks/byo/openshift-cluster/upgrades/v3_0_to_v3_1/upgrade.yml')
    # TODO: Upgrade inventory for upgrade?
    inventory_file = generate_inventory(CFG.hosts)
    facts_env = os.environ.copy()
    if 'ansible_log_path' in CFG.settings:
        facts_env['ANSIBLE_LOG_PATH'] = CFG.settings['ansible_log_path']
    if 'ansible_config' in CFG.settings:
        facts_env['ANSIBLE_CONFIG'] = CFG.settings['ansible_config']
    return run_ansible(playbook, inventory_file, facts_env, verbose)