summaryrefslogtreecommitdiff
path: root/azurelinuxagent/pa/deprovision/default.py
blob: 90d16c72cfa091df94dd245d107290b244bf4362 (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
# Microsoft Azure Linux Agent
#
# Copyright 2014 Microsoft Corporation
#
# 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.
#
# Requires Python 2.4+ and Openssl 1.0+
#

import glob
import os.path
import signal
import sys

import azurelinuxagent.common.conf as conf
import azurelinuxagent.common.utils.fileutil as fileutil
import azurelinuxagent.common.utils.shellutil as shellutil

from azurelinuxagent.common.exception import ProtocolError
from azurelinuxagent.common.future import read_input
from azurelinuxagent.common.osutil import get_osutil
from azurelinuxagent.common.protocol import get_protocol_util

class DeprovisionAction(object):
    def __init__(self, func, args=[], kwargs={}):
        self.func = func
        self.args = args
        self.kwargs = kwargs

    def invoke(self):
        self.func(*self.args, **self.kwargs)

class DeprovisionHandler(object):
    def __init__(self):
        self.osutil = get_osutil()
        self.protocol_util = get_protocol_util()
        self.actions_running = False
        signal.signal(signal.SIGINT, self.handle_interrupt_signal)

    def del_root_password(self, warnings, actions):
        warnings.append("WARNING! root password will be disabled. "
                        "You will not be able to login as root.")

        actions.append(DeprovisionAction(self.osutil.del_root_password))

    def del_user(self, warnings, actions):

        try:
            ovfenv = self.protocol_util.get_ovf_env()
        except ProtocolError:
            warnings.append("WARNING! ovf-env.xml is not found.")
            warnings.append("WARNING! Skip delete user.")
            return

        username = ovfenv.username
        warnings.append(("WARNING! {0} account and entire home directory "
                         "will be deleted.").format(username))
        actions.append(DeprovisionAction(self.osutil.del_account, 
                                         [username]))


    def regen_ssh_host_key(self, warnings, actions):
        warnings.append("WARNING! All SSH host key pairs will be deleted.")
        actions.append(DeprovisionAction(fileutil.rm_files,
                        [conf.get_ssh_key_glob()]))

    def stop_agent_service(self, warnings, actions):
        warnings.append("WARNING! The waagent service will be stopped.")
        actions.append(DeprovisionAction(self.osutil.stop_agent_service))

    def del_dirs(self, warnings, actions):
        dirs = [conf.get_lib_dir(), conf.get_ext_log_dir()]
        actions.append(DeprovisionAction(fileutil.rm_dirs, dirs))

    def del_files(self, warnings, actions):
        files = ['/root/.bash_history', '/var/log/waagent.log']
        actions.append(DeprovisionAction(fileutil.rm_files, files))

    def del_resolv(self, warnings, actions):
        warnings.append("WARNING! /etc/resolv.conf will be deleted.")
        files_to_del = ["/etc/resolv.conf"]
        actions.append(DeprovisionAction(fileutil.rm_files, files_to_del))

    def del_dhcp_lease(self, warnings, actions):
        warnings.append("WARNING! Cached DHCP leases will be deleted.")
        dirs_to_del = ["/var/lib/dhclient", "/var/lib/dhcpcd", "/var/lib/dhcp"]
        actions.append(DeprovisionAction(fileutil.rm_dirs, dirs_to_del))

        # For Freebsd, NM controlled
        actions.append(DeprovisionAction(fileutil.rm_files, ["/var/db/dhclient.leases.hn0",
                                                             "/var/lib/NetworkManager/dhclient-*.lease"]))


    def del_lib_dir_files(self, warnings, actions):
        known_files = [
            'HostingEnvironmentConfig.xml',
            'Incarnation',
            'Protocol',
            'SharedConfig.xml',
            'WireServerEndpoint'
        ]
        known_files_glob = [
            'Extensions.*.xml',
            'ExtensionsConfig.*.xml',
            'GoalState.*.xml'
        ]

        lib_dir = conf.get_lib_dir()
        files = [f for f in \
                    [os.path.join(lib_dir, kf) for kf in known_files] \
                        if os.path.isfile(f)]
        for p in known_files_glob:
            files += glob.glob(os.path.join(lib_dir, p))

        if len(files) > 0:
            actions.append(DeprovisionAction(fileutil.rm_files, files))

    def cloud_init_dirs(self, include_once=True):
        dirs = [
            "/var/lib/cloud/instance",
            "/var/lib/cloud/instances/",
            "/var/lib/cloud/data"
        ]
        if include_once:
            dirs += [
                "/var/lib/cloud/scripts/per-once"
            ]
        return dirs
    
    def cloud_init_files(self, include_once=True):
        files = [
            "/etc/sudoers.d/90-cloud-init-users"
        ]
        if include_once:
            files += [
                "/var/lib/cloud/sem/config_scripts_per_once.once"
            ]
        return files

    def del_cloud_init(self, warnings, actions, include_once=True):
        dirs = [d for d in self.cloud_init_dirs(include_once=include_once) \
                    if os.path.isdir(d)]
        if len(dirs) > 0:
            actions.append(DeprovisionAction(fileutil.rm_dirs, dirs))

        files = [f for f in self.cloud_init_files(include_once=include_once) \
                    if os.path.isfile(f)]
        if len(files) > 0:
            actions.append(DeprovisionAction(fileutil.rm_files, files))

    def reset_hostname(self, warnings, actions):
        localhost = ["localhost.localdomain"]
        actions.append(DeprovisionAction(self.osutil.set_hostname, 
                                         localhost))
        actions.append(DeprovisionAction(self.osutil.set_dhcp_hostname, 
                                         localhost))

    def setup(self, deluser):
        warnings = []
        actions = []

        self.stop_agent_service(warnings, actions)
        if conf.get_regenerate_ssh_host_key():
            self.regen_ssh_host_key(warnings, actions)

        self.del_dhcp_lease(warnings, actions)
        self.reset_hostname(warnings, actions)

        if conf.get_delete_root_password():
            self.del_root_password(warnings, actions)

        self.del_cloud_init(warnings, actions)
        self.del_dirs(warnings, actions)
        self.del_files(warnings, actions)
        self.del_resolv(warnings, actions)

        if deluser:
            self.del_user(warnings, actions)

        return warnings, actions

    def setup_changed_unique_id(self):
        warnings = []
        actions = []

        self.del_cloud_init(warnings, actions, include_once=False)
        self.del_dhcp_lease(warnings, actions)
        self.del_lib_dir_files(warnings, actions)
        self.del_resolv(warnings, actions)

        return warnings, actions

    def run(self, force=False, deluser=False):
        warnings, actions = self.setup(deluser)

        self.do_warnings(warnings)
        self.do_confirmation(force=force)
        self.do_actions(actions)

    def run_changed_unique_id(self):
        '''
        Clean-up files and directories that may interfere when the VM unique
        identifier has changed.

        While users *should* manually deprovision a VM, the files removed by
        this routine will help keep the agent from getting confused
        (since incarnation and extension settings, among other items, will 
        no longer be monotonically increasing).
        '''
        warnings, actions = self.setup_changed_unique_id()

        self.do_warnings(warnings)
        self.do_actions(actions)

    def do_actions(self, actions):
        self.actions_running = True
        for action in actions:
            action.invoke()
        self.actions_running = False

    def do_confirmation(self, force=False):
        if force:
            return True

        confirm = read_input("Do you want to proceed (y/n)")
        return True if confirm.lower().startswith('y') else False
    
    def do_warnings(self, warnings):
        for warning in warnings:
            print(warning)

    def handle_interrupt_signal(self, signum, frame):
        if not self.actions_running:
            print("Deprovision is interrupted.")
            sys.exit(0)

        print ('Deprovisioning may not be interrupted.')
        return