/
convert.input.R
526 lines (403 loc) · 22.3 KB
/
convert.input.R
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
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
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
##' Convert input by applying fcn and insert new record into database
##'
##'
##' @name convert.input
##' @title convert.input
##' @export
##' @author Betsy Cowdery, Michael Dietze, Ankur Desai, Tony Gardella
convert.input <- function(input.id, outfolder, formatname, mimetype, site.id, start_date,
end_date, pkg, fcn, con = con, host, browndog, write = TRUE,
format.vars, overwrite = FALSE, exact.dates = FALSE,
allow.conflicting.dates = TRUE, insert.new.file = FALSE,...) {
input.args <- list(...)
logger.debug(paste("Convert.Inputs", fcn, input.id, host$name, outfolder, formatname,
mimetype, site.id, start_date, end_date))
Rbinary <- ifelse(is.null(settings$host$Rbinary),"R",settings$host$Rbinary)
n <- nchar(outfolder)
if (substr(outfolder, n, n) != "/") {
outfolder <- paste0(outfolder, "/")
}
outname <- tail(unlist(strsplit(outfolder, "/")), n = 1)
logger.info(paste("start CHECK Convert.Inputs", fcn, input.id, host$name, outfolder,
formatname, mimetype, site.id, start_date, end_date))
##----------------------------------------------------------------------------------------------------------------##
if (exact.dates){
# Find Existing input with exact dates.
existing.dbfile <- dbfile.input.check(siteid = site.id,
mimetype = mimetype,
formatname = formatname,
parentid = input.id,
startdate = start_date,
enddate = end_date,
con = con,
hostname = host$name,
exact.dates = TRUE
)
logger.info(existing.dbfile, digits = 10)
logger.info("end CHECK for existing input record")
if (nrow(existing.dbfile) > 0){
existing.input <- db.query(paste0("SELECT * FROM inputs WHERE id=", existing.dbfile[["container_id"]]),con)
# Convert dates to Date objects and strip all time zones
# (DB values are timezone-free)
start_date <- lubridate::force_tz(lubridate::as_date(start_date), "UTC")
end_date <- lubridate::force_tz(lubridate::as_date(end_date), "UTC")
existing.input$start_date <- lubridate::force_tz(lubridate::as_date(existing.input$start_date), "UTC")
existing.input$end_date <- lubridate::force_tz(lubridate::as_date(existing.input$end_date), "UTC")
## Do overwrite if set to TRUE
if(overwrite){
# collect files to flag for deletion
files.to.delete <- remote.execute.R( paste0("list.files('",
existing.dbfile[["file_path"]],
"', full.names=TRUE)"),
host, user = NA, verbose = TRUE,R = Rbinary, scratchdir = outfolder)
file.deletion.commands <- .get.file.deletion.commands(files.to.delete)
remote.execute.R( file.deletion.commands$move.to.tmp,
host, user = NA,
verbose = TRUE,R = Rbinary, scratchdir = outfolder)
# Schedule files to be replaced or deleted on exiting the function
successful <- FALSE
on.exit(if (exists("successful") && successful) {
logger.info("Conversion successful, with overwrite=TRUE. Deleting old files.")
remote.execute.R( file.deletion.commands$delete.tmp,
host, user = NA,
verbose = TRUE, R = Rbinary, scratchdir = outfolder )
} else {
logger.info("Conversion failed. Replacing old files.")
remote.execute.R( file.deletion.commands$replace.from.tmp,
host, user = NA,
verbose = TRUE, R = Rbinary, scratchdir = outfolder )
}
)#Close on.exit
}
#Grab machine info of file that exists
existing.machine <- db.query(paste0("SELECT * from machines where id = '",
existing.dbfile$machine_id, "'"), con)
#Grab machine info of host machine
machine.host <- ifelse(host$name == "localhost", fqdn(), host$name)
machine <- db.query(paste0("SELECT * from machines where hostname = '",
machine.host, "'"), con)
if(existing.machine$id != machine$id){
logger.info("Valid Input record found that spans desired dates, but valid files do not exist on this machine.")
logger.info("Downloading all years of Valid input to ensure consistency")
insert.new.file <- TRUE
start_date <- existing.input$start_date
end_date <- existing.input$end_date
}else{
# There's an existing input that spans desired start/end dates with files on this machine
logger.info("Skipping this input conversion because files are already available.")
return(list(input.id = existing.input$id, dbfile.id = existing.dbfile$id))
}
} else{
# No existing record found. Should be good to go with regular conversion.
}
##-------------------------end of exact.dates chunk------------------------------------#
}else{
existing.dbfile <- dbfile.input.check(siteid = site.id,
mimetype = mimetype,
formatname = formatname,
parentid = input.id,
startdate = start_date,
enddate = end_date,
con = con,
hostname = host$name
)
logger.info(existing.dbfile)
logger.info("end CHECK for existing input record.")
if (nrow(existing.dbfile) > 0) {
existing.input <- db.query(paste0("SELECT * FROM inputs WHERE id=", existing.dbfile[["container_id"]]),con)
# Convert dates to Date objects and strip all time zones
# (DB values are timezone-free)
start_date <- lubridate::force_tz(lubridate::as_date(start_date), "UTC")
end_date <- lubridate::force_tz(lubridate::as_date(end_date), "UTC")
existing.input$start_date <- lubridate::force_tz(lubridate::as_date(existing.input$start_date), "UTC")
existing.input$end_date <- lubridate::force_tz(lubridate::as_date(existing.input$end_date), "UTC")
if (overwrite) {
# collect files to flag for deletion
files.to.delete <- remote.execute.R( paste0("list.files('",
existing.dbfile[["file_path"]],
"', full.names=TRUE)"),
host, user = NA, verbose = TRUE,R = Rbinary, scratchdir = outfolder)
file.deletion.commands <- .get.file.deletion.commands(files.to.delete)
remote.execute.R( file.deletion.commands$move.to.tmp,
host, user = NA,
verbose = TRUE,R = Rbinary, scratchdir = outfolder)
# Schedule files to be replaced or deleted on exiting the function
successful <- FALSE
on.exit(if (exists("successful") && successful) {
logger.info("Conversion successful, with overwrite=TRUE. Deleting old files.")
remote.execute.R( file.deletion.commands$delete.tmp,
host, user = NA,
verbose = TRUE, R = Rbinary, scratchdir = outfolder )
} else {
logger.info("Conversion failed. Replacing old files.")
remote.execute.R( file.deletion.commands$replace.from.tmp,
host, user = NA,
verbose = TRUE, R = Rbinary, scratchdir = outfolder )
}
)#close on on.exit
} else if ((start_date >= existing.input$start_date) &&
(end_date <= existing.input$end_date)) {
#Grab machine info of file that exists
existing.machine <- db.query(paste0("SELECT * from machines where id = '",
existing.dbfile$machine_id, "'"), con)
#Grab machine info of
machine.host <- ifelse(host$name == "localhost", fqdn(), host$name)
machine <- db.query(paste0("SELECT * from machines where hostname = '",
machine.host, "'"), con)
if(existing.machine$id != machine$id){
logger.info("Valid Input record found that spans desired dates, but valid files do not exist on this machine.")
logger.info("Downloading all years of Valid input to ensure consistency")
insert.new.file <- TRUE
start_date <- existing.input$start_date
end_date <- existing.input$end_date
}else{
# There's an existing input that spans desired start/end dates with files on this machine
logger.info("Skipping this input conversion because files are already available.")
return(list(input.id = existing.input$id, dbfile.id = existing.dbfile$id))
}
} else {
# Start/end dates need to be updated so that the input spans a continuous
# timeframe
start_date <- min(start_date, existing.input$start_date)
end_date <- max(end_date, existing.input$end_date)
logger.info(
paste0(
"Changed start/end dates to '",
start_date,
"'/'",
end_date,
"' ",
" so that existing input can be updated while maintaining continuous time span."
)
)
# There might be existing files for some years (but not all; checked that above)
# fcn should be smart enough not overwrite the existing ones, and hopefully won't
# waste time working on them either At the end, if convert.inputs was successful
# we'll need to update its start/end dates .
}
} else {
# No existing record found. Should be good to go.
}
}
#---------------------------------------------------------------------------------------------------------------#
# Get machine information
machine.host <- ifelse(host$name == "localhost", fqdn(), host$name)
machine <- db.query(paste0("SELECT * from machines where hostname = '",
machine.host, "'"), con)
if (nrow(machine) == 0) {
logger.error("machine not found", host$name)
return(NULL)
}
if (missing(input.id) || is.na(input.id) || is.null(input.id)) {
input <- dbfile <- NULL
} else {
input <- db.query(paste("SELECT * from inputs where id =", input.id), con)
if (nrow(input) == 0) {
logger.error("input not found", input.id)
return(NULL)
}
dbfile <- db.query(paste("SELECT * from dbfiles where container_id =", input.id,
" and container_type = 'Input' and machine_id =", machine$id), con)
if (nrow(dbfile) == 0) {
logger.error("dbfile not found", input.id)
return(NULL)
}
if (nrow(dbfile) > 1) {
logger.warning("multiple dbfile records, using last", dbfile)
dbfile <- dbfile[nrow(dbfile), ]
}
}
#--------------------------------------------------------------------------------------------------#
# Perform Conversion
conversion <- "local.remote" #default
if (!is.null(browndog) && host$name == "localhost") {
# perform conversions with Brown Dog - only works locally right now
library(RCurl)
# Determine outputtype using formatname and mimetype of output file Add issue to
# github that extension of formats table to include outputtype Convert to netcdf
# - only using localhost
if (mimetype == "application/x-netcdf") {
outputtype <- "pecan.zip"
} else {
# Convert to model specific format
if (formatname == "ed.met_driver_header_files_format" || formatname ==
"ed.met_driver_header files format") {
outputtype <- "ed.zip"
} else if (formatname == "Sipnet.climna") {
outputtype <- "clim"
} else if (formatname == "DALEC meteorology") {
outputtype <- "dalec.dat"
} else if (formatname == "LINKAGES met") {
outputtype <- "linkages.dat"
} else {
logger.severe(paste("Unknown formatname", formatname))
}
}
# create curl options
if (!is.null(browndog$username) && !is.null(browndog$password)) {
userpwd <- paste(browndog$username, browndog$password, sep = ":")
curloptions <- list(userpwd = userpwd, httpauth = 1L)
}
curloptions <- c(curloptions, followlocation = TRUE)
# check if we can do conversion
out.html <- getURL(paste0("http://dap-dev.ncsa.illinois.edu:8184/inputs/",
browndog$inputtype), .opts = curloptions)
if (outputtype %in% unlist(strsplit(out.html, "\n"))) {
logger.info(paste("Conversion from", browndog$inputtype, "to", outputtype,
"through Brown Dog"))
conversion <- "browndog"
}
}
if (conversion == "browndog") {
url <- file.path(browndog$url, outputtype)
# loop over files in localhost and zip to send to Brown Dog
files <- list.files(dbfile$file_path, pattern = dbfile$file_name)
files <- grep(dbfile$file_name, files, value = TRUE)
zipfile <- paste0(dbfile$file_name, ".", browndog$inputtype)
system(paste("cd", dbfile$file_path, "; zip", zipfile, paste(files, collapse = " ")))
zipfile <- file.path(dbfile$file_path, zipfile)
# check for and create output folder
if (!file.exists(outfolder)) {
dir.create(outfolder, showWarnings = FALSE, recursive = TRUE)
}
# post zipped file to Brown Dog
html <- postForm(url, fileData = fileUpload(zipfile), .opts = curloptions)
link <- getHTMLLinks(html)
file.remove(zipfile)
# download converted file
outfile <- file.path(outfolder, unlist(strsplit(basename(link), "_"))[2])
download.url(url = link, file = outfile, timeout = 600, .opts = curloptions, retry404 = TRUE)
# unzip downloaded file if necessary
if (file.exists(outfile)) {
if (tail(unlist(strsplit(outfile, "[.]")), 1) == "zip") {
fname <- unzip(outfile, list = TRUE)$Name
unzip(outfile, files = fname, exdir = outfolder, overwrite = TRUE)
file.remove(outfile)
} else {
fname <- list.files(outfolder)
}
}
# settings$run$inputs$path <- outputfile
# what if there is more than 1 output file?
rows <- length(fname)
result <- data.frame(file = character(rows),
host = character(rows),
mimetype = character(rows),
formatname = character(rows),
startdate = character(rows),
enddate = character(rows),
stringsAsFactors = FALSE)
for (i in seq_len(rows)) {
old.file <- file.path(dbfile$file_path, files[i])
new.file <- file.path(outfolder, fname[i])
# create array with results
result$file[i] <- new.file
result$host[i] <- fqdn()
result$startdate[i] <- paste(input$start_date, "00:00:00")
result$enddate[i] <- paste(input$end_date, "23:59:59")
result$mimetype[i] <- mimetype
result$formatname[i] <- formatname
}
} else if (conversion == "local.remote") {
# perform conversion on local or remote host
fcn.args <- input.args
fcn.args$overwrite <- overwrite
fcn.args$in.path <- dbfile$file_path
fcn.args$in.prefix <- dbfile$file_name
fcn.args$outfolder <- outfolder
fcn.args$start_date <- start_date
fcn.args$end_date <- end_date
arg.string <- listToArgString(fcn.args)
if (!missing(format.vars)) {
arg.string <- paste0(arg.string, ", format=", paste0(list(format.vars)))
}
cmdFcn <- paste0(pkg, "::", fcn, "(", arg.string, ")")
logger.debug(paste0("convert.input executing the following function:\n", cmdFcn))
result <- remote.execute.R(script = cmdFcn, host, user = NA, verbose = TRUE, R = Rbinary, scratchdir = outfolder)
}
logger.info("RESULTS: Convert.Input")
logger.info(result)
logger.info(names(result))
#--------------------------------------------------------------------------------------------------#
# Insert into Database
outlist <- unlist(strsplit(outname, "_"))
## insert new record into database
if (write) {
if (exists("existing.input") && nrow(existing.input) > 0 &&
(existing.input$start_date != start_date || existing.input$end_date != end_date)) {
# Updating record with new dates
db.query(paste0("UPDATE inputs SET start_date='", start_date, "', end_date='",
end_date, "', ", "updated_at=NOW() WHERE id=", existing.input$id),
con)
#Record has been updated and file downloaded so just return existing dbfile and input pair
return(list(input.id = existing.input$id, dbfile.id = existing.dbfile$id))
}
if (overwrite) {
# A bit hacky, but need to make sure that all fields are updated to expected
# values (i.e., what they'd be if convert.input was creating a new record)
if (exists("existing.input") && nrow(existing.input) > 0) {
db.query(paste0("UPDATE inputs SET name='", basename(dirname(result$file[1])),
"', ", "updated_at=NOW() WHERE id=", existing.input$id), con)
}
if (exists("existing.dbfile") && nrow(existing.dbfile) > 0) {
db.query(paste0("UPDATE dbfiles SET file_path='", dirname(result$file[1]),
"', ", "file_name='", result$dbfile.name[1], "', ",
"updated_at=NOW() WHERE id=", existing.dbfile$id), con)
}
}
parent.id <- ifelse(is.null(input), NA, input$id)
if ("newsite" %in% names(input.args) && !is.null(input.args[["newsite"]])) {
site.id <- input.args$newsite
}
if(insert.new.file){
dbfile.id <- dbfile.insert(in.path = dirname(result$file[1]),
in.prefix = result$dbfile.name[1],
'Input', existing.input$id,
con, reuse=TRUE, hostname = machine$hostname)
newinput <- list()
newinput$input.id <- existing.input$id
newinput$dbfile.id <- dbfile.id
}else{
newinput <- dbfile.input.insert(in.path = dirname(result$file[1]),
in.prefix = result$dbfile.name[1],
siteid = site.id,
startdate = start_date,
enddate = end_date,
mimetype,
formatname,
parentid = parent.id,
con = con,
hostname = machine$hostname,
allow.conflicting.dates = allow.conflicting.dates)
}
successful <- TRUE
return(newinput)
} else {
logger.warn("Input was not added to the database")
successful <- TRUE
return(NULL)
}
} # convert.input
.get.file.deletion.commands <- function(files.to.delete) {
if(length(files.to.delete) > 0) {
tmp.dirs <- file.path(unique(dirname(files.to.delete)), 'tmp')
tmp.paths <- file.path(dirname(files.to.delete), 'tmp', basename(files.to.delete))
tmp.dirs.string <- paste0("c(", paste(paste0("'", tmp.dirs, "'"), collapse=', '), ")")
tmp.path.string <- paste0("c(", paste(paste0("'", tmp.paths, "'"), collapse=', '), ")")
original.path.string <- paste0("c(", paste(paste0("'", files.to.delete, "'"), collapse=', '), ")")
move.to.tmp <- paste0(
"dir.create(", tmp.dirs.string, ", recursive=TRUE, showWarnings=FALSE); ",
"file.rename(from=", original.path.string, ", to=", tmp.path.string, ")"
)
replace.from.tmp <- paste0(
"file.rename(from=", tmp.path.string, ", to=", original.path.string, ");",
"unlink(", tmp.dirs.string, ", recursive=TRUE)"
)
delete.tmp <- paste0(
"unlink(", tmp.dirs.string, ", recursive=TRUE)"
)
return(list(move.to.tmp=move.to.tmp, replace.from.tmp=replace.from.tmp, delete.tmp=delete.tmp))
} else {
return(NULL)
}
} # .get.file.deletion.commands