summaryrefslogtreecommitdiffstats
path: root/odl-pipeline/lib/odl_reinstaller/odl_reinstaller.py
blob: 9a8973f7c09fd210dac4f79010a98fd51607960b (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
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
#!/bin/python
#
# Copyright (c) 2017 All rights reserved
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
import os
import re
import time

from utils.processutils import ProcessExecutionError
from tripleo_introspector.tripleo_introspector import TripleOIntrospector
from utils import processutils
from utils.utils_log import LOG, for_all_methods, log_enter_exit
from utils.service import Service
from utils.node_manager import NodeManager
from utils import utils_yaml

ODL_SYSTEMD = '/usr/lib/systemd/system/opendaylight.service'
ODL_AAA_JAR = '/opt/opendaylight/bin/aaa-cli-jar.jar'


@for_all_methods(log_enter_exit)
class ODLReInstaller(Service):

    def __init__(self):
        self.nodes = None
        self.odl_node = None

    def run(self, sys_args, config):
        pod_config = sys_args.pod_config
        odl_artifact = sys_args.odl_artifact
        node_config = utils_yaml.read_dict_from_yaml(pod_config)
        # TODO Add validation of incoming node config
        # self.check_node_config()

        # copy ODL to all nodes where it need to be copied
        self.nodes = NodeManager(node_config['servers']).get_nodes()
        for node in self.nodes:
            node.execute('ovs-vsctl del-controller br-int', as_root=True)
        first_controller = None
        for node in self.nodes:
            if not first_controller:
                if 'controller' in node.execute('echo $HOSTNAME')[0]:
                    first_controller = node
            # Check if ODL runs on this node
            jrv, _ = node.execute('ps aux |grep -v grep |grep karaf',
                                  as_root=True, check_exit_code=[0, 1])
            rv, (_, rc) = node.execute('docker ps | grep opendaylight_api',
                                       as_root=True, check_exit_code=[0, 1])
            if rc == 0:
                LOG.info("ODL is running as docker container")
                node.execute('docker stop opendaylight_api', as_root=True)
                self.odl_node = node
            elif 'java' in jrv:
                LOG.info("ODL is running as systemd service")
                self.odl_node = node
                node.execute('systemctl stop opendaylight', as_root=True)

            if self.odl_node is not None:
                LOG.info("ODL node found: {}".format(self.odl_node.name))
                # rc 5 means the service is not there.
                # rc 4 means the service cannot be found
                node.execute('systemctl stop bgpd', as_root=True,
                             check_exit_code=[0, 4, 5])
                node.execute('systemctl stop zrpcd', as_root=True,
                             check_exit_code=[0, 4, 5])

            self.disconnect_ovs(node)

        # Upgrade ODL
        if not self.odl_node:
            self.odl_node = first_controller
        self.reinstall_odl(self.odl_node, odl_artifact)

        # Wait for ODL to come back up
        full_netvirt_url = "http://{}:8081/diagstatus".format(
            self.odl_node.config['address'])
        counter = 1
        while counter <= 10:
            try:
                self.odl_node.execute("curl --fail {}".format(
                    full_netvirt_url))
                LOG.info("New OpenDaylight NetVirt is Up")
                break
            except processutils.ProcessExecutionError:
                LOG.warning("NetVirt not up. Attempt: {}".format(counter))
                if counter >= 10:
                    LOG.warning("NetVirt not detected as up after 10 "
                                "attempts...deployment may be unstable!")
            counter += 1
            time.sleep(15)

        # Reconnect OVS instances
        LOG.info("Reconnecting OVS instances")
        for node in self.nodes:
            self.connect_ovs(node)
        # Sleep for a few seconds to allow TCP connections to come up
        time.sleep(5)
        # Validate OVS instances
        LOG.info("Validating OVS configuration")
        for node in self.nodes:
            self.validate_ovs(node)
        LOG.info("OpenDaylight Upgrade Successful!")

    def _start_service_if_enabled(self, node, service):
        # rc 3 means service inactive
        # rc 4 means service cannot be found
        # rc 5 mean no service available
        status, _ = node.execute('systemctl status {}'.
                                 format(service), check_exit_code=[0, 3,
                                                                   4, 5])
        if 'service; enabled' in status:
            LOG.info('Starting {}'.format(service))
            node.execute('systemctl start {}'.format(service), as_root=True)

    def reinstall_odl(self, node, odl_artifact):
        # Check for Quagga
        self._start_service_if_enabled(node, 'zrpcd')
        self._start_service_if_enabled(node, 'bgpd')

        # Install odl
        tar_tmp_path = '/tmp/odl-artifact/'
        node.copy('to', odl_artifact, tar_tmp_path + odl_artifact)
        node.execute('rm -rf /opt/opendaylight/', as_root=True)
        node.execute('mkdir -p /opt/opendaylight/', as_root=True)
        if 'tar.gz' in odl_artifact:
            # check if systemd service exists (may not if this was a docker
            # deployment)
            if not node.is_file(ODL_SYSTEMD):
                LOG.info("Creating odl user, group, and systemd file")
                # user/group may already exist so just ignore errors here
                node.execute('groupadd odl', as_root=True,
                             check_exit_code=False)
                node.execute('useradd -g odl odl', as_root=True,
                             check_exit_code=False)
                systemd_file = os.path.join(os.getcwd(),
                                            'opendaylight.service')
                node.copy('to', systemd_file, '/tmp/opendaylight.service',
                          check_exit_code=True)
                node.execute('mv /tmp/opendaylight.service %s' % ODL_SYSTEMD,
                             as_root=True)
                node.execute('systemctl daemon-reload', as_root=True)
            LOG.info('Extracting %s to /opt/opendaylight/ on node %s'
                     % (odl_artifact, node.name))
            node.execute('tar -zxf %s --strip-components=1 -C '
                         '/opt/opendaylight/'
                         % (tar_tmp_path + odl_artifact), as_root=True)
            # AAA CLI jar for creating ODL user will be missing in regular
            # netvirt distro. Only part of full distro.
            if not node.is_file(ODL_AAA_JAR):
                LOG.info("ODL AAA CLI jar missing, will copy")
                aaa_cli_file = os.path.join(os.getcwd(),
                                            'aaa-cli-jar.jar')
                node.copy('to', aaa_cli_file, ODL_AAA_JAR)
            node.execute('chown -R odl:odl /opt/opendaylight', as_root=True)
        if '.rpm' in odl_artifact:
            LOG.info('Installing %s on node %s'
                     % (odl_artifact, node.name))
            node.execute('yum remove -y opendaylight', as_root=True)
            node.execute('yum install -y %s'
                         % (tar_tmp_path + odl_artifact), as_root=True)
        node.execute('rm -rf ' + tar_tmp_path, as_root=True)
        LOG.info('Starting Opendaylight on node %s' % node.name)
        # we do not want puppet-odl to install the repo or the package, so we
        # use tags to ignore those resources
        node.execute('puppet apply -e "include opendaylight" '
                     '--tags file,concat,file_line,augeas,odl_user,'
                     'odl_keystore,service '
                     '--modulepath=/etc/puppet/modules/ '
                     '--verbose --debug --trace --detailed-exitcodes',
                     check_exit_code=[2], as_root=True)
        # --detailed-exitcodes: Provide extra information about the run via
        # exit codes. If enabled, 'puppet apply' will use the following exit
        # codes:
        # 0: The run succeeded with no changes or failures; the system was
        #    already in the desired state.
        # 1: The run failed.
        # 2: The run succeeded, and some resources were changed.
        # 4: The run succeeded, and some resources failed.
        # 6: The run succeeded, and included both changes and failures.

    @staticmethod
    def disconnect_ovs(node):
        LOG.info('Disconnecting OpenVSwitch from controller on node %s'
                 % node.name)
        node.execute('ovs-vsctl del-controller br-int', as_root=True)
        node.execute('ovs-vsctl del-manager', as_root=True)
        LOG.info('Deleting Tunnel and Patch interfaces')
        # Note this is required because ODL fails to reconcile pre-created
        # ports
        for br in 'br-int', 'br-ex':
            LOG.info("Checking for ports on {}".format(br))
            try:
                out, _ = node.execute('ovs-vsctl list-ports {} | grep -E '
                                      '"tun|patch"'.format(br),
                                      as_root=True, shell=True)
                ports = out.rstrip().split("\n")
                for port in ports:
                    LOG.info('Deleting port: {}'.format(port))
                    node.execute('ovs-vsctl del-port {} {}'.format(br, port),
                                 as_root=True)
            except ProcessExecutionError:
                LOG.info("No tunnel or patch ports configured")
            LOG.info("Deleting all groups from {}".format(br))
            node.execute('ovs-ofctl -OOpenFlow13 del-groups {}'.format(br),
                         as_root=True, shell=True)

    @staticmethod
    def connect_ovs(node):
        LOG.info('Connecting OpenVSwitch to controller on node %s' % node.name)
        ovs_manager_str = ' '.join(node.config['ovs-managers'])
        node.execute('ovs-vsctl set-manager %s' % ovs_manager_str,
                     as_root=True)

    @staticmethod
    def validate_ovs(node):
        LOG.info("Validating OVS configuration for node: {}".format(node.name))
        # Validate ovs manager is connected
        out, _ = node.execute('ovs-vsctl show ', as_root=True)
        mgr_search = \
            re.search('Manager\s+\"tcp:[0-9.]+:6640\"\n\s*'
                      'is_connected:\s*true', out)
        if mgr_search is None:
            raise ODLReinstallerException("OVS Manager is not connected")
        else:
            LOG.info("OVS is connected to OVSDB manager")

        # Validate ovs controller is configured
        cfg_controller = node.config['ovs-controller']
        ovs_controller = TripleOIntrospector().get_ovs_controller(node)
        if cfg_controller == '' or cfg_controller is None:
            if ovs_controller is None or ovs_controller == '':
                raise ODLReinstallerException("OVS controller is not set "
                                              "for node: {}"
                                              "".format(node.address))
        elif ovs_controller != cfg_controller:
            raise ODLReinstallerException("OVS controller is not set to the "
                                          "correct pod config value on {}. "
                                          "Config controller: {}, current "
                                          "controller: {}"
                                          "".format(node.address,
                                                    cfg_controller,
                                                    ovs_controller))
        LOG.info("OVS Controller set correctly")
        # Validate ovs controller is connected
        ctrl_search = \
            re.search('Controller\s+\"tcp:[0-9\.]+:6653\"\n\s*'
                      'is_connected:\s*true', out)
        if ctrl_search is None:
            raise ODLReinstallerException("OVS Controller is not connected")
        else:
            LOG.info("OVS is connected to OpenFlow controller")

    def create_cli_parser(self, parser):
        parser.add_argument('--pod-config',
                            help="File containing pod configuration",
                            dest='pod_config',
                            required=True)
        parser.add_argument('--odl-artifact',
                            help="Path to Opendaylight tarball to use for "
                                 "upgrade",
                            dest='odl_artifact',
                            required=True)
        return parser


class ODLReinstallerException(Exception):

    def __init__(self, value):
        self.value = value

    def __str__(self):
        return self.value


def main():
    ODLReInstaller().start()

if __name__ == '__main__':
    main()