/
soop_FileSort.py
288 lines (225 loc) · 12 KB
/
soop_FileSort.py
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
286
287
#!/bin/env python
# -*- coding: utf-8 -*-
import os, shutil, stat, time, grp, sys, threading
from subprocess import Popen, PIPE, STDOUT
import StorageConnection
import sendEmail
class soop_FileSort:
def __init__(self):
# run as sudo -u cron_scripts -bash
self.ships = {'VLST':'Spirit-of-Tasmania-1',
'VNSZ':'Spirit-of-Tasmania-2',
'VHW5167':'Sea-Flyte',
'VNVR':'Iron-Yandi',
'VJQ7467':'Fantasea',
'VNAH':'Portland',
'V2BJ5':'ANL-Yarrunga',
'VROB':'Highland-Chief',
'9HA2479':'Pacific-Sun',
'VNAA':'Aurora-Australis',
'VLHJ':'Southern-Surveyor',
'FHZI':'Astrolabe',
'C6FS9':'Stadacona',
'V2BF1':'Florence',
'V2BP4':'Vega-Gotland',
'A8SW3':'Buxlink',
'ZMFR':'Tangaroa',
'VRZN9': 'Pacific-Celebes',
'VHW6005':'RV-Linnaeus',
'HSB3402':'MV-Xutra-Bhum',
'HSB3403':'MV-Wana-Bhum',
'VRUB2': 'Chenan'
}
self.blackList = [
'IMOS_SOOP-SST_MT_20111103T000000Z_9HA2479_FV01_C-20120528T072251Z.nc',
'IMOS_SOOP-SST_T_20130215T005900Z_HSB3403_FV01_C-20130216T001306Z.nc',
'IMOS_SOOP-SST_MT_20140409T010000Z_VROB_FV01_C-20140413T233225Z.nc'
]
self.data_codes = {'FMT':'flux_product','MT':'meteorological_sst_observations' }
self.datasetGroup = "users" # the linux group and user must exist
# place where sorted files go
self.dataRoot = "/mnt/imos-t3/IMOS"
self.destDir = self.dataRoot + "/opendap/SOOP" # temp value only if not supplied
self.emailAddress = "pmbohm@utas.edu.au"
# place for log files. Same as FTPGetter.py
self.localBaseDir = "/home/pmbohm/script_logs/"
# Use this to convert target modified time into local time
self.timezone_offset = time.altzone
self.newCount = 0;
self.updatedCount = 0;
self.checkedCount = 0;
self.ignoredCount = 0;
self.status = []
self.errorFiles = []
def processFiles(self,useDataFabric,origDir,userDestDir,fileExtension):
if len(userDestDir) > 0:
self.destDir = userDestDir
if useDataFabric:
df = StorageConnection.StorageConnection()
if df.isStorageMounted():
print "Connected to the storage"
self.status.append("Connected to the storage")
else:
df.connectStorage()
if not df.isStorageMounted():
print "Failed to connect to the storage so exiting."
self.errorFiles.append("Failed to connect to storage")
sys.exit()
os.chdir(origDir)
print "Checking " + os.getcwd()
for root, dirs, fname in os.walk(os.getcwd()):
fname.sort()
for fname in fname:
if fname.rsplit(".",1)[1] == fileExtension:
modified = os.stat(root+"/"+fname)[stat.ST_MTIME]
#print str(time.localtime(modified)) + " " + root+"/"+fname
self.handleFiles(fname,modified,root)
else:
self.ignoredCount += 1
os.system("find " + origDir + " -name '*." + fileExtension +"' -size -5b -exec rm {\} \;")
# find crap files created on the destination
crapFiles = os.system("find " + self.destDir + " -name '*." + fileExtension +"' -size -5b -exec ls -la {\} \;")
if crapFiles > 0:
os.system("find " + self.destDir + " -name '*." + fileExtension +"' -size -5b -exec rm {\} \;")
self.errorFiles.append(str(crapFiles) + " empty ." +fileExtension +" files removed")
self.status.append("\nSummary for File Sort: " + origDir + " " + time.strftime("%a, %d %b %Y %H:%M:%S",time.localtime()) )
self.status.append(str(self.updatedCount) + " Files were updated: ")
self.status.append(str(self.newCount) + " New files: ")
self.status.append(str(len(self.errorFiles)) + " Problems: ")
for f in self.errorFiles:
self.status.append(f)
self.status.append(str(self.checkedCount)+" files up to date")
self.status.append("==============================")
self.writetoLog(self.status)
# print to console
for f in self.status:
print f
def handleFiles(self,fname,modified,root):
"""
# eg file IMOS_SOOP-SST_T_20081230T000900Z_VHW5167_FV01.nc
# IMOS_<Facility-Code>_<Data-Code>_<Start-date>_<Platform-Code>_FV<File-Version>_<Product-Type>_END-<End-date>_C-<Creation_date>_<PARTX>.nc
"""
theFile = root+"/"+fname
file = fname.split("_")
#print theFile
if file[0] != "IMOS":
self.ignoredCount += 1
return
facility = file[1] # <Facility-Code>
# the file name must have at least 6 component parts to be valid
if len(file) > 5:
year = file[3][:4] # year out of <Start-date>
# check for the code in the ships
code = file[4]
if code in self.ships:
platform = code+"_"+ self.ships[code]
if facility == "SOOP-ASF":
if file[2] in self.data_codes:
product = self.data_codes[file[2]]
targetDir = self.destDir+"/"+facility+"/"+platform+"/"+product+"/"+year
targetDirBase = self.destDir+"/"+facility
else:
err = "Unknown Data Code "+product+" for "+facilty+". Add it to this script. File ignored"
print err
self.errorFiles.append(err)
# common error that needs our attention
email = sendEmail.sendEmail()
email.sendEmail("pmbohm@utas.edu.au","SOOP Filesorter - Unrecognised Data code",err)
self.ignoredCount += 1
return False
else:
targetDir = self.destDir+"/"+facility+"/"+platform+"/"+year
targetDirBase = self.destDir+"/"+facility
# files that contain '1-min-avg.nc' get their own sub folder
if "1-min-avg" in fname:
targetDir = targetDir+ "/1-min-avg"
error = None
if(not os.path.exists(targetDir)):
try:
os.makedirs(targetDir)
#od = os.popen("chmod -R g+w " + targetDirBase)
#os.popen("chgrp -R " +self.datasetGroup+" " + targetDirBase)
except:
print "Failed to create directory " + targetDir
self.errorFiles.append("Failed to create directory " + targetDir )
error = 1
# blacklist check
if fname in self.blackList:
print "Ignoreing Blacklisted file " + fname
self.errorFiles.append("Ignoreing Blacklisted file " + fname )
error = 1
if not error:
targetFile = targetDir+'/'+fname
# see if file exists
if(not os.path.exists(targetFile)):
#try:
shutil.copy(theFile,targetFile )
print theFile +" created in -> "+ targetDir
os.popen("chmod g+w " + targetFile).readline()
#os.popen("chgrp "+self.datasetGroup +" " + targetFile).readline()
self.newCount += 1;
#except:
# print "Failed to create file (" + theFile + "). check permissions and file name"
# self.errorFiles.append("Failed to create file (" + theFile + "). check permissions and file name")
# copy if more recent or rubbish file
elif (modified > os.stat(targetFile)[stat.ST_MTIME] + self.timezone_offset) or (os.path.getsize(targetFile) == 0):
try:
if os.path.getsize(targetFile) == 0:
print "Zero sized file found: " + targetFile
#shutil.copy dosent seem to overwrite so delete then write
try:
os.remove(targetFile)
except os.error:
print "remove wasnt successfull"
try:
shutil.copy(theFile,targetFile )
print theFile +" updated in -> "+ targetDir
self.updatedCount += 1;
except:
print "copy of " + theFile + " wasnt successfull"
except Exception, e:
msg = "Failed to update file (" + theFile + " " + time.ctime() + ") " + str(e)
self.errorFiles.append(msg)
else:
#print theFile +" checked ok -> "+ targetDir
self.checkedCount += 1;
#os.popen("chmod g+w " + targetFile).readline()
#os.popen("chgrp "+self.datasetGroup +" " + targetFile).readline()
else:
if code != "SOFS": # SOFS = bogus files writen by CSIRO. ignore them
err = "Unrecognised file "+ root+"/"+ fname + " with code '" + code + "' found by the filesorter"
self.errorFiles.append(err)
# common error that needs our attention
email = sendEmail.sendEmail()
email.sendEmail(self.emailAddress,"SOOP File sorter- Unrecognised ship code",err)
else:
#print "Unrecognised file "+ root+"/"+ fname + " found by the filesorter"
err = "Ignoring file "+ root+"/"+ fname + " not in agreed format"
self.errorFiles.append(err)
def writetoLog(self, report):
filename = "SOOPFileSort_Report"
os.chdir(self.localBaseDir)
if os.path.isfile(filename+ ".txt"):
size = os.path.getsize(filename+ ".txt")
if size > 1000000:
os.rename(filename + ".txt", filename +"_"+ time.strftime('%x').replace('/','-') + ".txt")
None
#print size
log_file = open(filename+ ".txt",'a+')
log_file.write("\r\nDownload time: " + time.ctime() + "\r\n")
for line in report:
log_file.write(line + "\r\n")
log_file.close()
def close(self):
try:
self.ftp.quit()
except:
pass
if __name__ == "__main__":
df = StorageConnection.StorageConnection()
df.connectStorage()
filesort = soop_FileSort()
# processFiles(self,useDataFabric,origDir,userDestDir,fileExtension):
# Setup for dev testing below Philip
filesort.processFiles(False, "/opt/SOOP_cache/ships/","/home/pmbohm/Documents/DATA","nc")
filesort.close()