utils.py 16.9 KB
Newer Older
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
#
# Copyright (C) 2009 INRA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

__author__ = 'Plateforme bioinformatique Midi Pyrenees'
__copyright__ = 'Copyright (C) 2009 INRA'
__license__ = 'GNU General Public License'
__version__ = '1.0'
__email__ = 'support.genopole@toulouse.inra.fr'
__status__ = 'beta'

import glob
import os
import string, gzip, bz2
import tarfile, tempfile
from shutil import copyfile, rmtree
import re
31
import base64
Penom Nom's avatar
Penom Nom committed
32
33
import pty
import sys
34

Penom Nom's avatar
Penom Nom committed
35

36
37
38
39
40
41
42
class Utils(object):
    """
    Class Utils: in charge to all the programme utilities
    """

    # Files with this extensions won't be compressed if asked
    UNCOMPRESS_EXTENSION = [".gz", ".zip", ".bam", ".bz", ".bz2"]
Penom Nom's avatar
Penom Nom committed
43
44
45
46
    
    # CASAVA filename format
    CASAVA_FILENAME = { 'sample' : 1, 'barcode' : 2, 'lane' : 3, 'read' : 4, 'package' : 5 }
    CASAVA_FILENAME_SEPARATOR = '_'
47

48
49
    PASS_KEY = '1234123412341234123412341234'
    
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
    @staticmethod
    def gzip(file, out_dir, delete=False):
        """
          Gzip compress the given file.
          @param file    : the file to gzip 
          @param out_dir : the out directory where to store the gziped file
          @param delete  : delete files     
          @return        : the compressed file path
        """
        # If the file is not already a compressed file
        if os.path.splitext(file)[1] not in Utils.UNCOMPRESS_EXTENSION:
            f_in = open(file, 'rb')
            f_out_name = os.path.join(out_dir, os.path.basename(file)) + ".gz"
            f_out = gzip.open(f_out_name, 'wb')
            f_out.writelines(f_in)
            f_out.close()
            f_in.close()
        # Otherwise, just copy it
        else:
            f_out_name = os.path.join(out_dir, os.path.basename(file))
            copyfile(file, f_out_name)
        
        # Finaly try to delete the original file if asked to do so
        try:
            if delete:
                os.remove(file)
        except:
            pass
        return f_out_name


    @staticmethod
    def gunzip(file, out_dir):
        """
          Gunzip given file.
          @param file    : the file to gunzip 
          @param out_dir : the out directory where to store the decompressed file 
          @return        : the uncompressed file path
        """
        f_in = gzip.open(file)
        f_out_name = os.path.join(out_dir, os.path.splitext(os.path.basename(file))[0])
        f_out = open(f_out_name, 'w')
        f_out.writelines(f_in)
        f_out.close()
        f_in.close()
        return f_out_name

97
98
99
    @staticmethod
    def get_storage_size(start_path):
        total_size = 0
Penom Nom's avatar
Penom Nom committed
100
101
        for dirpath, dirnames, filenames in os.walk(start_path):
            for f in filenames:
102
103
104
                fp = os.path.join(dirpath, f)
                total_size += os.path.getsize(fp)
        return total_size
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

    @staticmethod
    def bz2(file, out_dir, delete=False):
        """
          Bzip compress the given file.
          @param file    : the file to compress 
          @param out_dir : the out directory where to store the compressed file
          @param delete  : delete files     
          @return        : the compressed file path
        """
        # If the file is not already a compressed file
        if os.path.splitext(file)[1] not in Utils.UNCOMPRESS_EXTENSION:
            f_in = open(file, 'rb')
            f_out_name = os.path.join(out_dir, os.path.basename(file)) + ".bz2"
            f_out = bz2.BZ2File(f_out_name, 'wb')
            f_out.writelines(f_in)
            f_out.close()
            f_in.close()
        # Otherwise, just copy it
        else:
            f_out_name = os.path.join(out_dir, os.path.basename(file))
            copyfile(file, f_out_name)
        
        # Finaly try to delete the original file if asked to do so
        try:
            if delete:
                os.remove(file)
        except:
            pass

        return f_out_name


    @staticmethod
    def uncompress_bz2(file, out_dir):
        """
          Bzip compress the given file.
          @param file    : the file to compress 
          @param out_dir : the out directory where to store the compressed file     
          @return        : the compressed file path
        """
        f_in = bz2.BZ2File(file)
        f_out_name = os.path.join(out_dir, os.path.splitext(os.path.basename(file))[0])
        f_out = open(f_out_name, 'w')
        f_out.writelines(f_in)
        f_out.close()
        f_in.close()
        return f_out_name


    @staticmethod
    def tar_files(files, out_tar_name, delete=False):
        """
        Tar all files given.
          @param files        : table of files
          @param out_tar_name : the full output tar path (archive name included)
          @param delete       : delete files     
          @return             : the path to the tar file
        """
        tarf = tarfile.open(out_tar_name, "w")
        for file in files:
            if os.path.isfile(file) :
                (head, tail)= os.path.split(file)
                os.chdir(head)
                tarf.add(tail)
        tarf.close()
        
        for file in files:
            try:
                if delete:
                    os.remove(file)
            except:
                pass
        return out_tar_name


    @staticmethod
    def yield_files(files_tab):
        """
        yield objects to untar
        """
        for file in files_tab:
            yield file


    @staticmethod
    def untar_files(archive, pattern, out_dir):
        """
        Tar all files given.
          @param archive : the tar file
          @param pattern : the extension to search for
          @param out_dir : where should be untar the files
          @return        : a list of untared files
        """
        tarf = tarfile.open(archive)
        files = []
        files_to_return = []
        for tarinfo in tarf:
            if os.path.splitext(tarinfo.name)[1] == "."+pattern:
                files.append(tarinfo)
                files_to_return.append(os.path.join(out_dir, tarinfo.name))
        tarf.extractall(path=out_dir, members=Utils.yield_files(files))
        tarf.close()
        return files_to_return
        
        
    @staticmethod
    def tar_dir(directory, out_tar_name, delete=False):
        """
        Tar the given directory.
          @param directory    : the directory to tar
          @param out_tar_name : the full output tar path (archive name included)
          @param delete       : delete dir
          @return             : the path to the tar file
        """
        tarf = tarfile.open(out_tar_name, "w")
        os.chdir(directory)
        tarf.add(".")
        tarf.close()
        try:
            if delete:
                shutil.remove(directory)
        except:
            pass
        return out_tar_name
    
    
    @staticmethod
    def getUniqueCombinaison(items, n):
        """
        Return all combinaison for the list
          @param items : the list
          @param n : the max depth
        """
        if n==0: 
            yield []
        else:
Penom Nom's avatar
Penom Nom committed
242
            for i in range( len(items) - n+1 ):
243
244
245
246
247
248
249
250
251
252
253
                for j in Utils.getUniqueCombinaison( items[i+1:], n-1 ):
                    yield [items[i]] + j

    
    @staticmethod             
    def getSizesUniqueCombinaison(items):
        """
        Return all combinaison for the list
          @param items : the list
        """
        res = []
Penom Nom's avatar
Penom Nom committed
254
        for n in range(1,len(items)+1):
255
256
            res += Utils.getUniqueCombinaison(items,n)
        return res
Penom Nom's avatar
Penom Nom committed
257
258
259
260
261
262
263
264
265
266
267
268
269
270
 
    
    @staticmethod
    def split_pair( file_list, is_casava=False ):
        """
        Return the list of read 1 and the list of read 1 from a list
          @param file_list : the list
          @param is_casava : files names in file_list are in CASVAVA format 
        """
        read_1_list = []
        read_2_list = []
    
        if is_casava:
            for file in file_list:
Penom Nom's avatar
Penom Nom committed
271
272
                basename_without_ext = os.path.basename(file).split(".")[0]
                file_name_fields = basename_without_ext.split(Utils.CASAVA_FILENAME_SEPARATOR)
Penom Nom's avatar
Penom Nom committed
273
274
275
276
277
278
                read_tag = file_name_fields[Utils.CASAVA_FILENAME['read']-1]
                if read_tag == "R1":
                    read_1_list.append(file)
                else:
                    read_2_list.append(file)
        else:
279
            sorted_list = sorted( file_list )
Penom Nom's avatar
Penom Nom committed
280
    
281
282
283
284
            for i in range(0,len(sorted_list),2):
                read_1_list.append(sorted_list[i])
                read_2_list.append(sorted_list[i+1])
            
Penom Nom's avatar
Penom Nom committed
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
        return [read_1_list, read_2_list]


    @staticmethod
    def get_group_basenames( file_list, group_by ):
        """
        Return the list of prefix according to keywords. Ex : [/home/sampleA_ATGCTC_L001_R1_001.fastq.gz, /home/sampleA_ATGCTC_L001_R2_001.fastq.gz, /home/sampleB_ATGCCG_L001_R1_001.fastq.gz]  => [sampleA_ATGCTC_L001_R1, sampleA_ATGCTC_L001_R2, sampleB_ATGCCG_L001_R1]
          @param file_list : the list of files (files names are in CASVAVA format)
          @param group_by : CASAVA_FILENAME key (ex : read)
        """
        group_basenames = {}

        for file in file_list:      
            file_name_fields = os.path.basename(file).split(Utils.CASAVA_FILENAME_SEPARATOR)
        
            group_tag = Utils.CASAVA_FILENAME_SEPARATOR.join( file_name_fields[:Utils.CASAVA_FILENAME[group_by]] )
        
Penom Nom's avatar
Penom Nom committed
302
            if group_tag in group_basenames :
Penom Nom's avatar
Penom Nom committed
303
304
305
306
307
                group_basenames[group_tag].append(file)
            else:
                group_basenames[group_tag] = [file]
     
        return group_basenames
Penom Nom's avatar
Penom Nom committed
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326

    @staticmethod
    def get_filepath_by_prefix( path_list, prefixes ):
        """
        Gather files path with same prefix. Ex :
        list [/home/sample1_L002.fastq, /home/sample2_L002.fastq, /home/sample1_L003.fastq] 
        with prefixes [sample1, sample2]
        return {'sample1':[/home/sample1_L002.fastq, /home/sample1_L003.fastq], 'sample2':[/home/sample2_L002.fastq]}
          @param path_list : the list of files
          @param prefixes : prefix to gather
        """
        path_groups = {}
        
        for current_prefix in prefixes:
            path_groups[current_prefix] = []           
            for file_path in path_list:
                if os.path.basename(file_path).startswith(current_prefix):
                    path_groups[current_prefix].append(file_path)
        
327
328
        return path_groups
    
329
330
    @staticmethod
    def encode_passwd(clear):
Penom Nom's avatar
Penom Nom committed
331
332
        return base64.urlsafe_b64encode(clear.encode()).decode()
        """
333
334
335
336
337
338
        enc = []
        for i in range(len(clear)):
            key_c = Utils.PASS_KEY[i % len(Utils.PASS_KEY)]
            enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)
            enc.append(enc_c)
        return base64.urlsafe_b64encode("".join(enc))
Penom Nom's avatar
Penom Nom committed
339
        """
340
341
342
    
    @staticmethod
    def decode_passwd(enc):
Penom Nom's avatar
Penom Nom committed
343
344
        return base64.urlsafe_b64decode(enc.encode()).decode()
        """
345
346
347
348
349
350
351
        dec = []
        enc = base64.urlsafe_b64decode(enc)
        for i in range(len(enc)):
            key_c = Utils.PASS_KEY[i % len(Utils.PASS_KEY)]
            dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
            dec.append(dec_c)
        return "".join(dec)
Penom Nom's avatar
Penom Nom committed
352
        """
Penom Nom's avatar
Penom Nom committed
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
    
    @staticmethod
    def get_directories_structure_and_content(ng6_username, data_folder, output_folder, prefixed_ids):
        from ng6.t3MySQLdb import t3MySQLdb
        src_directories = []
        dest_directories = []
        t3mysql = t3MySQLdb()
        
        user_id = None
        try : user_id = t3mysql.get_user_id(ng6_username)
        except : pass
        
        for prefixed_id in prefixed_ids.split(';') :
            vals = prefixed_id.split('_')
            prefix = vals[0]
            id = vals[1]
            
            if prefix == "data" or prefix == "run" :
                run = t3mysql.select_run_informations(id)
                source_dir = data_folder +'/'+ run['directory']
                
                project_name = "Project_%s.%s" % ( re.sub( r"[\s\/]", "_", run['project_name']), run['project_id'] )
                run_name = "Run_%s.%s" %( run['name'].replace(' ', '_').replace('/', '_'), id )
                
                raw_data_dir = os.path.join( output_folder, project_name, run_name, "RawData"  )
                if source_dir not in src_directories :
                    src_directories.append(source_dir)
                if raw_data_dir not in dest_directories :
                    dest_directories.append(raw_data_dir)
                
                if prefix == "run" :
                    for analyse_id, analyse_values in t3mysql.get_user_run_analysis(user_id, id, 'tx_nG6_analyze.name').items() :
                        analysis_dir = data_folder + '/' + analyse_values["directory"]
                        analysis_name = "Analyse_%s.%s"%( re.sub( r"[\s\/]", "_", analyse_values['name']), analyse_id )
                        dest_analysis_dir = os.path.join( output_folder, project_name, run_name, analysis_name  )
                        if analysis_dir not in src_directories :
                            src_directories.append(analysis_dir)
                        if dest_analysis_dir not in dest_directories :
                            dest_directories.append(dest_analysis_dir)
                        
            elif prefix == "analyse" :
                analyse = t3mysql.select_analysis_informations(id)
                source_dir = data_folder +'/'+ analyse["directory"]
                
                if source_dir not in src_directories :
                    src_directories.append(source_dir)
                
                project_name = "Project_%s.%s" % ( re.sub( r"[\s\/]", "_", analyse["project_name"]), analyse["project_id"])
                
                # it's a run analysis
                if analyse["run_id"]:
                    run_name = "Run_%s.%s" % ( re.sub( r"[\s\/]", "_", analyse["run_name"]), analyse["run_id"])
                    analysis_name = "Analyse_%s.%s" % ( re.sub( r"[\s\/]", "_", analyse["name"]), id)
                    dest_analysis_dir = os.path.join( output_folder, project_name, run_name, analysis_name )
                    if dest_analysis_dir not in dest_directories :
                        dest_directories.append(dest_analysis_dir)
                # it's a project analysis
                else :
                    analysis_name = "Project_analyses/%s.%s" % ( re.sub( r"[\s\/]", "_", analyse["name"]), id)
                    dest_analysis_dir = os.path.join( output_folder, project_name, analysis_name )
                    if dest_analysis_dir not in dest_directories :
                        dest_directories.append(dest_analysis_dir)
        
        if len(src_directories) != len(dest_directories) :
            raise Exception("Error while retrieveing directory structure and content")
        
        sources, destinations = [], []
        
        for i, e in enumerate(src_directories):
            if os.path.isdir(e) :
                sources.append(e)
                destinations.append(dest_directories[i])
        
        return sources, destinations 

class SSH(object): 
    def __init__(self, user, passwd, hostname, port=22):
        self.username = user
        self.password = passwd
        self.hostname = hostname
        self.port = port

    def run_cmd(self, c):
        (pid, f) = pty.fork()
        if pid == 0:
            os.execlp('ssh', 'ssh', '-p %d' % self.port, '-o StrictHostKeyChecking=no' ,
                      self.username + '@' + self.hostname, c)
        else:
            return (pid, f)     
    
    def _read(self, f):
Penom Nom's avatar
Penom Nom committed
444
        x = b''
Penom Nom's avatar
Penom Nom committed
445
446
        try:
            x = os.read(f, 1024)
Penom Nom's avatar
Penom Nom committed
447
        except Exception as e:
Penom Nom's avatar
Penom Nom committed
448
449
            # this always fails with io error
            pass
Penom Nom's avatar
Penom Nom committed
450
        return x.decode()
Penom Nom's avatar
Penom Nom committed
451
452
453
454
455
456
457

    def ssh_results(self, pid, f):
        output = ''
        got = self._read(f)         # check for authenticity of host request
        m = re.search( 'assword:', got)
        if m:
            # send passwd
Penom Nom's avatar
Penom Nom committed
458
            os.write(f, (self.password + '\n').encode() )
Penom Nom's avatar
Penom Nom committed
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
            # read two lines
            tmp = self._read(f)
            tmp += self._read(f)
            m = re.search('Permission denied', tmp)
            if m:
                raise Exception( 'Invalid password')
            # passwd was accepted
            got = tmp
        while got and len(got) > 0:
            output += got
            got = self._read(f)
        os.waitpid(pid, 0)
        os.close(f)
        return output

    def cmd(self, c):
        (pid, f) = self.run_cmd(c)
        return self.ssh_results(pid, f)


Penom Nom's avatar
Penom Nom committed
479