OSDManager.py 30.2 KB
Newer Older
1
2
3
import os
import pickle
import subprocess
Felix Seibert's avatar
Felix Seibert committed
4
5
from urllib import request
import urllib.error
6
import shutil
7
import time
8

Felix Seibert's avatar
Felix Seibert committed
9
10
11
12
import dataDistribution
import div_util
import folder
import dir_status_page_parser
13
14
15
16

'''
xOSDManager - a python module to manage OSD selection in XtreemFS
currently only depth (level) 2 subdirectories can be managed
17
only unix-based OSs are supported
18
19
20
'''


Felix Seibert's avatar
Felix Seibert committed
21
22
# TODO add support for arbitrary subdirectory level
# (currently depth=2 is hardcoded, which is fine for GeoMultiSens purposes)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

class OSDManager(object):
    def __init__(self, path_to_managed_folder, config_file='.das_config', value_map=None, debug=False):

        self.managedFolder = path_to_managed_folder
        self.configFile = config_file
        self.debug = debug

        if value_map is None:

            if not div_util.check_for_executable('xtfsutil'):
                raise ExecutableNotFoundException("No xtfsutil found. Please make sure it is contained in your PATH.")

            output_1 = subprocess.run(["xtfsutil", self.managedFolder], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                      universal_newlines=True)

            if output_1.stderr.startswith("xtfsutil failed: Path doesn't point to an entity on an XtreemFS volume!"):
                raise NotAXtreemFSVolume("The specified folder '" + path_to_managed_folder +
                                         "' is not part of an XtreemFS volume!")

            if len(output_1.stderr) > 0:
                raise Exception("xtfsutil produced some error: " + output_1.stderr)

Felix Seibert's avatar
Felix Seibert committed
46
            self.pathOnVolume = div_util.remove_leading_trailing_slashes(
47
48
49
50
51
52
                str(output_1.stdout).split("\n")[0].split()[-1])
            self.pathToMountPoint = self.managedFolder[0:(len(self.managedFolder) - len(self.pathOnVolume) - 1)]

            output_2 = subprocess.run(["xtfsutil", self.pathToMountPoint],
                                      stdout=subprocess.PIPE, universal_newlines=True)

Felix Seibert's avatar
Felix Seibert committed
53
54
55
56
57
            self.volume_information = div_util.extract_volume_information(output_2.stdout)
            self.volumeName = self.volume_information[0]
            osd_list = list(map(lambda x: x[0], self.volume_information[1]))
            self.osdSelectionPolicy = self.volume_information[2]
            self.volumeAddress = self.volume_information[3]
58

Felix Seibert's avatar
Felix Seibert committed
59
            self.distribution = None
60
            if not self.__read_configuration():
Felix Seibert's avatar
Felix Seibert committed
61
                self.distribution = dataDistribution.DataDistribution()
62

Felix Seibert's avatar
Felix Seibert committed
63
            self.distribution.add_osd_list(osd_list)
Felix Seibert's avatar
Felix Seibert committed
64
65
66
67
68
69
70

            self.osdInformation = None

            try:
                answer = request.urlopen(div_util.get_http_address(self.volumeAddress))
                html_data = answer.read().decode('UTF-8')

71
                parser = dir_status_page_parser.dir_status_page_parser()
Felix Seibert's avatar
Felix Seibert committed
72
73
74
75
76
77
78
                parser.feed(html_data)

                # filter out data sets without last update time or wrong service type
                filtered_data_sets = list(filter(lambda x: int(x['last updated'].split()[0]) != 0, parser.dataSets))
                filtered_data_sets = list(filter(lambda x: x['type'] == 'SERVICE_TYPE_OSD', filtered_data_sets))

                self.osdInformation = {}
79

Felix Seibert's avatar
Felix Seibert committed
80
81
82
83
84
85
86
87
88
89
90
91
                for data_set in filtered_data_sets:
                    uuid = data_set['uuid']
                    current_osd = {}
                    current_osd['usable_space'] = int(data_set['usable'].split()[0])
                    current_osd['total_space'] = int(data_set['total'].split()[0])

                    self.osdInformation[uuid] = current_osd

            except urllib.error.URLError as error:
                print("osd information could not be fetched! Probably the http status page could not be found at:",
                      div_util.get_http_address(self.volumeAddress))
                print(error)
92
        else:
Felix Seibert's avatar
Felix Seibert committed
93
94
95
96
97
            try:
                self.pathOnVolume = value_map['path_on_volume']
                self.pathToMountPoint = value_map['path_to_mount']
                self.volumeName = value_map['volume_name']
                self.osdSelectionPolicy = value_map['osd_selection_policy']
Felix Seibert's avatar
Felix Seibert committed
98
                self.distribution = value_map['data_distribution']
Felix Seibert's avatar
Felix Seibert committed
99
100
101
102
103
                self.volumeAddress = value_map['volume_address']
                self.osdInformation = value_map['osd_information']
            except KeyError as error:
                print('key not found:', error)
                print('leaving in OSDManager field empty!')
104
105

    def __read_configuration(self):
Felix Seibert's avatar
Felix Seibert committed
106
        assert self.distribution is None
107
108
109
        path_to_config = os.path.join(self.managedFolder, self.configFile)
        try:
            f = open(path_to_config, "rb")
Felix Seibert's avatar
Felix Seibert committed
110
            self.distribution = pickle.load(f)
111
112
113
114
115
116
117
            return True
        except IOError:
            return False

    def __write_configuration(self):
        path_to_config = os.path.join(self.managedFolder, self.configFile)
        f = open(path_to_config, "wb")
Felix Seibert's avatar
Felix Seibert committed
118
        pickle.dump(self.distribution, f)
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
    '''
    create a good data distribution out of data already present in the file system.
    the created data distribution will then be transferred to the physical layer,
    i.e., all files will be moved to their corresponding OSD,
    using XtreemFS' read-only replication strategy.
    '''

    def create_distribution_from_existing_files(self, apply_layout=True):
        if self.debug:
            print("creating distribution from existing files. osd manager: " + str(self))

        if not div_util.check_for_executable('du'):
            raise ExecutableNotFoundException("No du found. Please make sure it is contained in your PATH.")

        existing_folders = self.get_assigned_folders()
        managed_folders = []
        for one_folder in existing_folders:
            du = subprocess.run(["du", "-s", one_folder], stdout=subprocess.PIPE,
                                universal_newlines=True)
            folder_size = int(du.stdout.split()[0])
            new_folder = folder.Folder(self.path_on_volume(one_folder),
                                       folder_size,
                                       None)
            managed_folders.append(new_folder)

        new_assignments = self.distribution.add_folders(managed_folders)

        if apply_layout:
            self.apply_osd_assignments(new_assignments)
        elif self.debug:
            print("NOT applying data layout!")

        self.__write_configuration()

        if self.debug:
            print("osd manager after new folders have been added to data distribution:")
            print(str(self))

        self.fix_physical_layout()

    '''
    fixes the physical layout, such that it matches the data distribution described in self.distribution
    we use the following strategy: first, determine which files needs to be moved to another OSD, and create three lists.
    for each file to be moved, one contains the command to set the default replication policy (1), one contains the command
    to create a new replica on the target OSD (2) and one contains the command to delete the replica on the original OSD (3).
    the command-lists are executed in order: 1, 2, 3, commands of list i only being executed if all commands of list i-1
    have returned. the commands of any one list are executed in parallel, with an upper bound of 200 parallel executions
    to not violate the maximum number of processes of the OS.

    the commands of list 3 might return an error, as deleting the replica on the original OSD is not possible until
    the new replica on the target OSD is complete. theses commands are collected and re-executed after a certain delay.
    this process is repeated until no error is returned, which should eventually happen (as soon as all new replicas on
    the target OSDs are complete).

    '''

    def fix_physical_layout(self, repeat_delete_interval_secs=15):
        change_policy_command_list = []
        create_replica_command_list = []
        delete_replica_command_list = []

181
182
183
184
185
186
        managed_folders = self.get_assigned_folders()
        for managed_folder in managed_folders:
            for directory in os.walk(managed_folder):
                for filename in directory[2]:

                    absolute_file_path = os.path.join(directory[0], filename)
Felix Seibert's avatar
Felix Seibert committed
187
188
                    print("absolute file path: " + str(absolute_file_path))

189
                    osd_of_file = div_util.get_osd_uuid(absolute_file_path)
Felix Seibert's avatar
Felix Seibert committed
190
191
192
193
194
195
196
197
198
199
                    print("osd_of_file: " + str(osd_of_file))

                    path_on_volume = self.path_on_volume(absolute_file_path)
                    print("path on volume: " + self.path_on_volume(absolute_file_path))

                    containing_folder_id = self.get_containing_folder_id(path_on_volume)
                    print("containing folder id: " + containing_folder_id)

                    osd_for_file = self.distribution.get_containing_osd(containing_folder_id)
                    print("osd_for_file: " + str(osd_for_file))
200
201
202
203
204
205
206
207
208
209
210
211
212
213

                    if osd_of_file != osd_for_file:
                        # create replication commands
                        # collect replication commands
                        # run replication commands - handle errors if new replica is not complete yet
                        # if no replication is used (otherwise than for moving the files from osd to osd),
                        # we should reset the replication policy to none
                        policy_command = div_util.create_replication_policy_command(absolute_file_path)
                        create_command = div_util.create_create_replica_command(absolute_file_path, osd_for_file)
                        delete_command = div_util.create_delete_replica_command(absolute_file_path, osd_of_file)

                        change_policy_command_list.append(div_util.command_list_to_single_string(policy_command))
                        create_replica_command_list.append(div_util.command_list_to_single_string(create_command))
                        delete_replica_command_list.append(div_util.command_list_to_single_string(delete_command))
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

        processes = div_util.run_commands(change_policy_command_list)
        if self.debug:
            print("executing " + str(len(processes)) + " change policy commands done. Results:")
            div_util.print_process_list(processes)

        processes = div_util.run_commands(create_replica_command_list)
        if self.debug:
            print("executing " + str(len(processes)) + " create replica commands done. Results:")
            div_util.print_process_list(processes)

        processes = div_util.run_commands(delete_replica_command_list)
        successfull_deletions = []
        errored_deletions = []
        while True:
            if self.debug:
                print("executing " + str(len(processes)) + " delete replica commands done. Results:")
                div_util.print_process_list(processes)

            for process in processes:
                stdout, stderr = process.communicate()
                if stderr == b'':
                    pass
                else:
                    errored_deletions.append(process.args)

            if len(errored_deletions) == 0:
                break

            time.sleep(repeat_delete_interval_secs)

            processes = div_util.run_commands(errored_deletions)

247
248
249
250
251
    '''
    create empty folders and assign OSDs.
    '''

    def create_empty_folders(self, folders):
Felix Seibert's avatar
Felix Seibert committed
252
        average_size = int(self.distribution.get_average_folder_size())
253
254
255
256
257
258
259
260
261
        if average_size <= 0:
            average_size = 1

        tiles = []

        for input_folder in folders:
            new_tile = folder.Folder(self.path_on_volume(input_folder), average_size, None)
            tiles.append(new_tile)

Felix Seibert's avatar
Felix Seibert committed
262
        new_tiles = self.distribution.add_folders(tiles)
263
264
265
266
267
268
269
270
271
272
273
274
275

        self.apply_osd_assignments(new_tiles)

        for input_folder in folders:
            os.makedirs(input_folder, exist_ok=True)

        self.__write_configuration()

    '''
    copy a list of given folders into the managed folder, assigning OSDs to new folders and updating
    self.dataDistribution
    '''

Felix Seibert's avatar
Felix Seibert committed
276
    def copy_folders(self, folders, environment='LOCAL', remote_source=None, sshfs_mount_dir='/tmp/sshfs_tmp_mnt',
277
278
279
280
281
282
283
284
285
286
287
                     apply_layout=True, execute_copy=True, random_osd_assignment=False):
        if self.debug:
            print("calling copy_folders with:")
            print("folders: " + str(folders))
            print("environment: " + str(environment))
            print("remote_source: " + str(remote_source))
            print("sshfs_mount_dir: " + str(sshfs_mount_dir))
            print("apply_layout: " + str(apply_layout))
            print("execute_copy: " + str(execute_copy))
            print("random_osd_assignemnt: " + str(random_osd_assignment))

288
289
290
291
292
293
294
295
296
297
298
299
        if not div_util.check_for_executable('du'):
            raise ExecutableNotFoundException("No du found. Please make sure it is contained in your PATH.")

        if remote_source is not None:
            if not div_util.check_for_executable('sshfs'):
                raise ExecutableNotFoundException("No sshfs found. Please make sure it is contained in your PATH.")
            if not div_util.check_for_executable('scp'):
                raise ExecutableNotFoundException("No scp found. Please make sure it is contained in your PATH.")
            if not div_util.check_for_executable('fusermount'):
                raise ExecutableNotFoundException("No fusermount found. Please make sure it is contained in your PATH.")

        if remote_source is not None:
Felix Seibert's avatar
Felix Seibert committed
300
            os.makedirs(sshfs_mount_dir, exist_ok=True)
301
302
303
304
305
306
307
308

        new_folders = []

        for input_folder in folders:
            last_2_path_elements = os.path.join(os.path.split(os.path.split(input_folder)[0])[1],
                                                os.path.split(input_folder)[1])
            if remote_source is not None:
                mount_point = os.path.join(sshfs_mount_dir, last_2_path_elements)
Felix Seibert's avatar
Felix Seibert committed
309
                os.makedirs(mount_point, exist_ok=True)
310
311
312
313
                subprocess.run(["sshfs", remote_source + ":" + input_folder, mount_point])
                du = subprocess.run(["du", "-s", mount_point], stdout=subprocess.PIPE,
                                    universal_newlines=True)
                subprocess.run(["fusermount", "-uz", mount_point])
Felix Seibert's avatar
Felix Seibert committed
314
                shutil.rmtree(mount_point)
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
                folder_size = int(du.stdout.split()[0])
            else:
                du = subprocess.run(["du", "-s", input_folder], stdout=subprocess.PIPE,
                                    universal_newlines=True)
                folder_size = int(du.stdout.split()[0])

            new_folder = folder.Folder(os.path.join(self.volumeName, self.pathOnVolume, last_2_path_elements),
                                       folder_size,
                                       input_folder)
            if self.debug:
                print("new folder: " + str(new_folder))

            new_folders.append(new_folder)

        if remote_source is not None:
            shutil.rmtree(sshfs_mount_dir)
Felix Seibert's avatar
Felix Seibert committed
331
332
        if self.debug:
            print("OSDManager: random_osd_assignment: " + str(random_osd_assignment))
333

Felix Seibert's avatar
Felix Seibert committed
334
        new_assignments = self.distribution.add_folders(new_folders, random_osd_assignment=random_osd_assignment)
Felix Seibert's avatar
Felix Seibert committed
335
336
337
338
        if apply_layout:
            self.apply_osd_assignments(new_assignments)
        elif self.debug:
            print("NOT applying data layout!")
339
340
341
342
343
344
345

        self.__write_configuration()

        if self.debug:
            print("osd manager after new folders have been added to data distribution:")
            print(str(self))

346
347
        if execute_copy:
            self.__copy_data(new_folders, environment, remote_source)
348

Felix Seibert's avatar
Felix Seibert committed
349
350
351
352
353
354
355
356
357
358
359
360
361
    '''
    moves a folder from one OSD to another OSD. you may specify a temporary folder.
    '''

    def move_folder_to_osd(self, folder_id: str, new_osd_id: str, tmp_dir='/tmp/move_folder_tmp_dir'):
        folder_path = os.path.join(self.get_target_dir(folder_id),
                                   os.path.split(folder_id)[1])

        os.makedirs(tmp_dir)

        if not div_util.check_for_executable('xtfsutil'):
            raise ExecutableNotFoundException("No xtfsutil found. Please make sure it is contained in your PATH.")
        # step 1: add folder to new OSD, update data distribution and xtreemfs configuration
Felix Seibert's avatar
Felix Seibert committed
362
        self.distribution.assign_new_osd(folder_id, new_osd_id)
Felix Seibert's avatar
Felix Seibert committed
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
        if self.debug:
            subprocess.run(["xtfsutil",
                            "--set-pattr", "1004.filenamePrefix", "--value",
                            "add " + folder_id + " " + new_osd_id + "", self.pathToMountPoint])
        else:
            subprocess.run(["xtfsutil",
                            "--set-pattr", "1004.filenamePrefix", "--value",
                            "add " + folder_id + " " + new_osd_id + "", self.pathToMountPoint],
                           stdout=subprocess.PIPE, universal_newlines=True)

        # step 2: one by one, move files to tmp_location and then back to the folder, which means that they should now
        # be located onto the new OSD.

        for root, dirs, files in os.walk(folder_path):
            for file in files:
                current_file_path = os.path.join(root, file)
                copied_file_path = os.path.join(tmp_dir, file)
                shutil.move(current_file_path, copied_file_path)
                shutil.move(copied_file_path, current_file_path)

        shutil.rmtree(tmp_dir, ignore_errors=True)

    '''
    removes a folder from the distribution. this does NOT delete the folder from the file system.
    '''

    def remove_folder(self, folder_id):
Felix Seibert's avatar
Felix Seibert committed
390
        containing_osd = self.distribution.get_containing_osd(folder_id)
Felix Seibert's avatar
Felix Seibert committed
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
        if containing_osd is not None:
            if not div_util.check_for_executable('xtfsutil'):
                raise ExecutableNotFoundException("No xtfsutil found. Please make sure it is contained in your PATH.")

            containing_osd.remove_folder(folder_id)
            if self.debug:
                subprocess.run(["xtfsutil",
                                "--set-pattr", "1004.filenamePrefix", "--value",
                                "remove " + folder_id + "", self.pathToMountPoint])
            else:
                subprocess.run(["xtfsutil",
                                "--set-pattr", "1004.filenamePrefix", "--value",
                                "remove " + folder_id + "", self.pathToMountPoint],
                               stdout=subprocess.PIPE, universal_newlines=True)

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
    '''
    update the given (by absolute path) folders, such that the values held by self.dataDistribution
    matches their size on disk.
    if no argument is given, all folders are updated.
    '''

    def update(self, arg_folders=None):

        if arg_folders is not None:
            for folder_for_update in arg_folders:
                if not folder_for_update.startswith(self.managedFolder):
                    raise PathNotManagedException(
                        "The path :" + folder_for_update + "is not managed by this instance of the XtreemFS OSD"
                                                           "manager!")

        folder_size_updates = {}

        folders = arg_folders
        if arg_folders is None:
            folders = self.get_assigned_folders()

        for folder_for_update in folders:
            folder_id = self.path_on_volume(folder_for_update)
            command = ["du", "-s", folder_for_update]
            if self.debug:
                print("executing: " + str(command))
            du = subprocess.run(command, stdout=subprocess.PIPE, universal_newlines=True)
            folder_disk_size = int(du.stdout.split()[0])
            folder_size_updates[folder_id] = folder_disk_size

        for folder_for_update, size in folder_size_updates.items():
Felix Seibert's avatar
Felix Seibert committed
437
            self.distribution.update_folder(folder_for_update, size)
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

        self.__write_configuration()

        if self.debug:
            print(str(self))

    '''
    apply the given assignments to the XtreemFS volume, using xtfsutil.
    the assignments are given as a list containing tuples (tile_id, osd),
    where tile_id is given by applying path_on_volume() onto the absolute path of the folder.
    '''

    def apply_osd_assignments(self, assignments):
        if not div_util.check_for_executable('xtfsutil'):
            raise ExecutableNotFoundException("No xtfsutil found. Please make sure it is contained in your PATH.")

        if self.osdSelectionPolicy is not "1000,1004":
            if self.debug:
                subprocess.run(["xtfsutil", "--set-osp", "prefix", self.pathToMountPoint])
            else:
                subprocess.run(["xtfsutil", "--set-osp", "prefix", self.pathToMountPoint],
                               stdout=subprocess.PIPE, universal_newlines=True)

        for new_tile in assignments:
            if self.debug:
                subprocess.run(["xtfsutil",
                                "--set-pattr", "1004.filenamePrefix", "--value",
                                "add " + new_tile[0] + " " + new_tile[1] + "",
                                self.pathToMountPoint])
            else:
                subprocess.run(["xtfsutil",
                                "--set-pattr", "1004.filenamePrefix", "--value",
                                "add " + new_tile[0] + " " + new_tile[1] + "",
                                self.pathToMountPoint],
                               stdout=subprocess.PIPE, universal_newlines=True)

    '''
    copy data onto XtreemFS volume
    '''

    def __copy_data(self, input_folders, environment, remote_source):
Felix Seibert's avatar
Felix Seibert committed
479
480
        if self.debug:
            print('calling copy_data with: ', input_folders, environment, remote_source)
Felix Seibert's avatar
Felix Seibert committed
481
        osd_list = self.distribution.get_osd_list()
482
483
484
485
        osd_to_folders_map = {}
        for osd in osd_list:
            osd_to_folders_map[osd] = []
        for input_folder in input_folders:
Felix Seibert's avatar
Felix Seibert committed
486
            osd_for_tile = self.distribution.get_containing_osd(input_folder.id).uuid
487
488
489
490
491
492
493
494
495
496
497
            osd_to_folders_map[osd_for_tile].append(input_folder)

        if self.debug:
            print("osd to folders map:")
            for key, value in osd_to_folders_map.items():
                print("osd: " + key)
                print("assigned folders:")
                for input_folder in value:
                    print(str(input_folder))

        # trigger the copying!
Felix Seibert's avatar
Felix Seibert committed
498
        if environment == "SLURM":
499
500
            assert remote_source is not None
            copy_commands = self.__generate_copy_commands_slurm(osd_to_folders_map, remote_source)
Felix Seibert's avatar
Felix Seibert committed
501
        elif environment == "HU_CLUSTER":
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
            copy_commands = self.__generate_copy_commands_hu_cluster(osd_to_folders_map)
        else:
            copy_commands = self.__generate_copy_commands_local(osd_to_folders_map)

        for input_folder in input_folders:
            path_to_target_dir = self.get_target_dir(input_folder.id)
            os.makedirs(path_to_target_dir, exist_ok=True)

        self.__execute_copy_commands(copy_commands)

    '''
    generates a list of copy commands, one command for each OSD that receives new data.
    the copy commands are constructed such that they can be executed in a slurm environment (that is, within a slurm job
    allocation) at ZIB.
    each command is a copy command including all new folders for the corresponding OSD, preceded by a srun command
    to execute the copy command locally on the slurm node on which the target OSD resides.
    '''

    def __generate_copy_commands_slurm(self, osd_to_folders_map, remote_source):
        if self.debug:
            print("Using SLURM mode for copying...")

Felix Seibert's avatar
Felix Seibert committed
524
525
526
527
528
529
530
531
532
        slurm_hosts = div_util.get_slurm_hosts()

        if self.debug:
            print('slurm_hosts: ', slurm_hosts)

        osd_to_host_map = div_util.get_osd_to_hostname_map(self.volume_information[1], slurm_hosts)

        if self.debug:
            print('osd_to_host_map: ', osd_to_host_map)
533
534
535

        command_list = []

536
        host_name = ""
537
        # command = ""
538
        for key in osd_to_folders_map.keys():
539
540
            if host_name == "":
                host_name = osd_to_host_map[key]
541
542
543
544
545
546
547
548
            command = ""
            for copy_folder in osd_to_folders_map[key]:
                command += "srun -N1-1 --nodelist=" + host_name
                command += " scp -rq " + remote_source + ":" + copy_folder.origin
                command += " " + self.get_target_dir(copy_folder.id)
                command += " ;"
            if len(osd_to_folders_map[key]) > 0:
                command_list.append(command)
549
        # command_list.append(command)
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
        return command_list

    '''
    generates a list of copy commands, one command for each OSD that receives new data.
    the copy commands are constructed such that they can be executed on the GeoMultiSens cluster at HU Berlin.
    each command is a copy command including all new folders for the corresponding OSD, preceded by a ssh command
    to execute the copy command locally on the node of the target OSD.
    '''

    def __generate_copy_commands_hu_cluster(self, osd_to_folders_map):
        if self.debug:
            print("Using HU_CLUSTER mode for copying...")

        if not div_util.check_for_executable('xtfsutil'):
            raise ExecutableNotFoundException("No xtfsutil found. Please make sure it is contained in your PATH.")

        xtfsutil = subprocess.run(["xtfsutil", self.pathToMountPoint],
                                  stdout=subprocess.PIPE, universal_newlines=True)
Felix Seibert's avatar
Felix Seibert committed
568
        volume_information = div_util.extract_volume_information(xtfsutil.stdout)
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
        osd_to_ip_address = {}
        for (osd, ip) in volume_information[1]:
            osd_to_ip_address[osd] = ip

        command_list = []

        for key in osd_to_folders_map.keys():
            ip_address = osd_to_ip_address[key]
            command = "ssh " + ip_address + " \'"
            for copy_folder in osd_to_folders_map[key]:
                command += " cp -r"
                command += " " + copy_folder.origin
                command += " " + self.get_target_dir(copy_folder.id)
                command += " ;"
            command += " \' "
            if len(osd_to_folders_map[key]) > 0:
                command_list.append(command)

        return command_list

    '''
    generates a list of copy commands, one command for each OSD that receives new data.
    plain old cp is used for the actual copying.
    '''

    def __generate_copy_commands_local(self, osd_to_folders_map):
        if self.debug:
            print("Using local cp for copying...")

        command_list = []

        for key in osd_to_folders_map.keys():
            command = ""
            for copy_folder in osd_to_folders_map[key]:
                command += "cp -r "
                command += copy_folder.origin
                command += " " + self.get_target_dir(copy_folder.id)
                command += " ; "

            if len(osd_to_folders_map[key]) > 0:
                command_list.append(command)

        return command_list

    '''
    execute, in parallel, a given set of commands. note that the degree of parallelism will match the length of
    command_list.
    '''

    def __execute_copy_commands(self, command_list):
        if self.debug:
            print("Executing copy commands: ")
            for command in command_list:
                print(str(command))
            print("in total " + str(len(command_list)) + " commands.")
        processes = []
        for command in command_list:
Felix Seibert's avatar
Felix Seibert committed
626
            process = subprocess.Popen(command, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
627
            time.sleep(5)
628
629
630
631
632
633
            processes.append(process)

        for p in processes:
            p.wait()

        if self.debug:
Felix Seibert's avatar
Felix Seibert committed
634
635
            for terminated_process in processes:
                print(str(terminated_process.communicate()))
636
637
638
            print("Executing copy commands done.")

    '''
639
640
641
    creates a list of all folders, managed by this XtreemFS OSD manager, that have an assigned OSD
    TODO this actually just returns a list of all level 2 subdirectories, independently of whether they are actually
    assigned to some OSD or not. i think that this is not the expected behaviour.
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
    '''

    def get_assigned_folders(self):
        assigned_folders = []
        for depth_1_folder in os.listdir(self.managedFolder):
            depth_1_path = os.path.join(self.managedFolder, depth_1_folder)
            if os.path.isdir(depth_1_path):
                for depth_2_folder in os.listdir(depth_1_path):
                    depth_2_path = os.path.join(self.managedFolder, depth_1_folder, depth_2_folder)
                    if os.path.isdir(depth_2_path):
                        assigned_folders.append(depth_2_path)

        return assigned_folders

    '''
    gets the path to the target dir, given the folder_id
    '''
Felix Seibert's avatar
Felix Seibert committed
659

660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
    def get_target_dir(self, folder_id):
        path_on_mount_point = folder_id[len(self.volumeName) + 1:]
        return os.path.split(os.path.join(self.pathToMountPoint, path_on_mount_point))[0]

    '''
    remove the leading part of the path, such that only the part onto the xtreemfs volume remains, including
    the volume itself.
    throws an exception when the path is not managed by this XtreemFS OSD manager.
    '''

    def path_on_volume(self, path):
        if not path.startswith(self.managedFolder):
            raise PathNotManagedException("Path " + path + " is not managed by this instance of the XtreemFS OSD"
                                                           "manager!")
        return os.path.join(self.volumeName, path[len(self.pathToMountPoint) + 1:])

676
677
678
    '''
    search for the assigned folder that is a prefix of the given path on volume
    '''
679

680
    def get_containing_folder_id(self, path_on_volume):
Felix Seibert's avatar
Felix Seibert committed
681
        for osd in self.distribution.OSDs.values():
682
            for a_folder in osd.folders:
Felix Seibert's avatar
Felix Seibert committed
683
                if path_on_volume.startswith(a_folder.id):
684
685
686
                    return a_folder.id
        return None

687
688
689
690
    def __str__(self):
        representation = "pathToMountPoint: " + self.pathToMountPoint + " volumeName: " + self.volumeName + " pathOnVolume: " \
                         + self.pathOnVolume
        representation += ("\nconfigFile: " + self.configFile + "\n")
Felix Seibert's avatar
Felix Seibert committed
691
        representation += self.distribution.description()
692
693
694
695
696
697
698
699
700
701
702
703
704
        return representation


class ExecutableNotFoundException(Exception):
    """raise this when an external executable can not be found"""


class NotAXtreemFSVolume(Exception):
    """raise this when a path does not point to a folder on a xtreemfs volume"""


class PathNotManagedException(Exception):
    """raise this when a path is handled, that is not managed by xOSDManager"""