Issues (1964)

html/inc/submit_util.inc (9 issues)

1
<?php
2
3
// This file is part of BOINC.
4
// http://boinc.berkeley.edu
5
// Copyright (C) 2011 University of California
6
//
7
// BOINC is free software; you can redistribute it and/or modify it
8
// under the terms of the GNU Lesser General Public License
9
// as published by the Free Software Foundation,
10
// either version 3 of the License, or (at your option) any later version.
11
//
12
// BOINC is distributed in the hope that it will be useful,
13
// but WITHOUT ANY WARRANTY; without even the implied warranty of
14
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15
// See the GNU Lesser General Public License for more details.
16
//
17
// You should have received a copy of the GNU Lesser General Public License
18
// along with BOINC.  If not, see <http://www.gnu.org/licenses/>.
19
20
// server-side utility functions for remote job submission and control
21
22
require_once("../inc/submit_db.inc");
23
24
// The status of a workunit.
25
// Not stored in the DB;
26
// it's computed by get_batch_params() and added to the workunit object
27
//
28
define('WU_UNSENT', 0);
29
define('WU_IN_PROGRESS', 1);
30
define('WU_SUCCESS', 2);
31
define('WU_ERROR', 3);
32
33
// write status and error messages to log
34
//
35
function log_write($x) {
36
    static $enabled, $log_file;
37
38
    if (!isset($enabled)) {
39
        $enabled = false;
40
        $filename = parse_config(get_config(), "<remote_submit_log>");
41
        if (!$filename) {
42
            return;
43
        }
44
        $log_dir = parse_config(get_config(), "<log_dir>");
45
        if (!$log_dir) {
46
            return;
47
        }
48
        $log_file = fopen("$log_dir/$filename", "a");
49
        if (!$log_file) return;
0 ignored issues
show
$log_file is of type resource, thus it always evaluated to false.
Loading history...
50
        $enabled = true;
51
    }
52
    if (!$enabled) return;
53
    fwrite($log_file, sprintf("%s: %s\n", strftime("%c"), $x));
54
    fflush($log_file);
55
}
56
57
// in remote job submission,
58
// for input files of type local, semilocal, and inline,
59
// we need to give a unique physical name based on its content.
60
// Prepend the jf_ to make the origin of the file clear
61
//
62
function job_file_name($md5) {
63
    return "jf_$md5";
64
}
65
66
// can user upload files?
67
//
68
function has_file_access($user) {
69
    $us = BoincUserSubmit::lookup_userid($user->id);
70
    if (!$us) return false;
71
    return true;
72
}
73
74
// can user submit to given app?
75
//
76
function has_submit_access($user, $app_id) {
77
    $us = BoincUserSubmit::lookup_userid($user->id);
78
    if (!$us) return false;
79
    if ($us->submit_all) return true;
80
    $usa = BoincUserSubmitApp::lookup("user_id=$user->id and app_id=$app_id");
81
    if (!$usa) return false;
82
    return true;
83
}
84
85
// can user manage given app (or all apps if zero)?
86
//
87
function has_manage_access($user, $app_id) {
88
    $us = BoincUserSubmit::lookup_userid($user->id);
89
    if (!$us) return false;
90
    if ($us->manage_all) return true;
91
    $usa = BoincUserSubmitApp::lookup("user_id=$user->id and app_id=$app_id");
92
    if (!$usa) return false;
93
    return $usa->manage;
94
}
95
96
// check whether user has permissions for a remote job submission
97
// or job file request.
98
// $r is a request message that includes an 'authenticator' field
99
// $app is the app being submitted to (or null if file op)
100
// returns user, or give XML error and quit
101
//
102
function check_remote_submit_permissions($r, $app) {
103
    $auth = (string)$r->authenticator;
104
    if (!$auth) {
105
        log_write("no authenticator");
106
        xml_error(-1, "no authenticator");
107
    }
108
    $auth = BoincDb::escape_string($auth);
109
    $user = BoincUser::lookup("authenticator='$auth'");
110
    if (!$user) {
111
        log_write("bad authenticator");
112
        xml_error(-1, "bad authenticator");
113
    }
114
115
    // check access
116
    //
117
    if ($app) {
118
        if (!has_submit_access($user, $app->id)) {
119
            log_write("no submit access");
120
            xml_error(-1, "no submit access");
121
        }
122
    } else {
123
        if (!has_file_access($user)) {
124
            log_write("no file access");
125
            xml_error(-1, "no file access");
126
        }
127
    }
128
    return $user;
129
}
130
131
// remove all of user's permissions
132
//
133
function delete_remote_submit_user($user) {
134
    BoincUserSubmit::delete_user($user->id);
135
    BoincUserSubmitApp::delete_user($user->id);
136
}
137
138
// given its WUs, compute parameters of the batch:
139
//   credit_canonical: credit granted to canonical instances
140
//   fraction_done: frac of jobs that are done (success or failed)
141
//   state: whether complete (all jobs done)
142
//   completion_time: if newly complete
143
//   nerror_jobs: # of failed jobs
144
// Update the above in DB.
145
// Also compute (not in DB):
146
//   njobs_success: # of jobs with canonical instance
147
//   njobs_in_prog: # of jobs not success or fail,
148
//      and at least one result in progress
149
//
150
// return the batch object, with these values
151
//
152
// Also add the status field to WUs
153
//
154
// TODO: update est_completion_time
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
155
//
156
function get_batch_params($batch, $wus) {
157
    if ($batch->state == BATCH_STATE_INIT) {
158
        // a batch in INIT state has no jobs
159
        //
160
        return $batch;
161
    }
162
    if (!$wus) {
163
        if ($batch->njobs) {
164
            $batch->update('njobs=0');
165
            $batch->njobs = 0;
166
        }
167
        return $batch;
168
    }
169
170
    // make list of WU IDs with an in-progress result
171
    $res_in_prog = BoincResult::enum_fields(
172
        'workunitid',
173
        sprintf('batch=%d and server_state in (%d, %d)',
174
            $batch->id,
175
            RESULT_SERVER_STATE_IN_PROGRESS, RESULT_SERVER_STATE_OVER
176
        )
177
    );
178
    $wus_in_prog = [];
179
    foreach ($res_in_prog as $res) {
180
        $wus_in_prog[$res->workunitid] = true;
181
    }
182
    unset($res_in_progress);    // does this do anything?
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $res_in_progress does not exist. Did you maybe mean $res_in_prog?
Loading history...
183
184
    $fp_total = 0;
185
    $fp_done = 0;
186
    $completed = true;
187
    $batch->nerror_jobs = 0;
188
    $batch->credit_canonical = 0;
189
    $njobs_success = 0;
190
    $njobs_in_prog = 0;
191
    foreach ($wus as $wu) {
192
        $fp_total += $wu->rsc_fpops_est;
193
        if ($wu->canonical_resultid) {
194
            $fp_done += $wu->rsc_fpops_est;
195
            $njobs_success++;
196
            $batch->credit_canonical += $wu->canonical_credit;
197
            $wu->status = WU_SUCCESS;
198
        } else if ($wu->error_mask) {
199
            $batch->nerror_jobs++;
200
            $wu->status = WU_ERROR;
201
        } else {
202
            $completed = false;
203
            if (array_key_exists($wu->id, $wus_in_prog)) {
204
                $njobs_in_prog++;
205
                $wu->status = WU_IN_PROGRESS;
206
            } else {
207
                $wu->status = WU_UNSENT;
208
            }
209
        }
210
    }
211
    $njobs = count($wus);
212
    $batch->njobs = $njobs;
213
    $batch->fraction_done = ($njobs_success + $batch->nerror_jobs)/$batch->njobs;
214
    if ($completed && $batch->state == BATCH_STATE_IN_PROGRESS) {
215
        $batch->state = BATCH_STATE_COMPLETE;
216
        $batch->completion_time = time();
217
    }
218
    $batch->update("fraction_done = $batch->fraction_done, nerror_jobs = $batch->nerror_jobs, state=$batch->state, completion_time = $batch->completion_time, credit_canonical = $batch->credit_canonical, njobs=$njobs");
219
220
    $batch->njobs_success = $njobs_success;
221
    $batch->njobs_in_prog = $njobs_in_prog;
222
    return $batch;
223
}
224
225
// get the physical names of a result's output files.
226
//
227
function get_outfile_phys_names($result) {
228
    $names = [];
229
    $xml = "<a>".$result->xml_doc_out."</a>";
230
    $r = simplexml_load_string($xml);
231
    if (!$r) return $names;
0 ignored issues
show
$r is of type SimpleXMLElement, thus it always evaluated to true.
Loading history...
232
    foreach ($r->file_info as $fi) {
233
        $names[] = (string)($fi->name);
234
    }
235
    return $names;
236
}
237
238
function get_outfile_log_names($result) {
239
    $names = [];
240
    $xml = "<a>".$result->xml_doc_in."</a>";
241
    $r = simplexml_load_string($xml);
242
    if (!$r) return $names;
0 ignored issues
show
$r is of type SimpleXMLElement, thus it always evaluated to true.
Loading history...
243
    foreach ($r->result->file_ref as $fr) {
244
        $names[] = (string)($fr->open_name);
245
    }
246
    return $names;
247
}
248
249
function get_outfile_paths($result) {
250
    $fanout = parse_config(get_config(), "<uldl_dir_fanout>");
251
    $upload_dir = parse_config(get_config(), "<upload_dir>");
252
253
    $paths = array();
254
    $xml = "<a>".$result->xml_doc_out."</a>";
255
    $r = simplexml_load_string($xml);
256
    if (!$r) return $paths;
0 ignored issues
show
$r is of type SimpleXMLElement, thus it always evaluated to true.
Loading history...
257
    foreach ($r->file_info as $fi) {
258
        $path = dir_hier_path((string)($fi->name), $upload_dir, $fanout);
259
        $paths[] = $path;
260
    }
261
    return $paths;
262
}
263
264
function abort_workunit($wu) {
265
    BoincResult::update_aux(
266
        sprintf(
267
            'server_state=%d, outcome=%d where server_state=%d and workunitid=%d',
268
            RESULT_SERVER_STATE_OVER, RESULT_OUTCOME_DIDNT_NEED,
269
            RESULT_SERVER_STATE_UNSENT,
270
            $wu->id
271
        )
272
    );
273
    $wu->update(
274
        sprintf('error_mask=error_mask|%d', WU_ERROR_CANCELLED)
275
    );
276
}
277
278
function abort_batch($batch) {
279
    $wus = BoincWorkunit::enum_fields(
280
        'id',
281
        "batch=$batch->id"
282
    );
283
    $ids = [];
284
    foreach ($wus as $wu) {
285
        $ids[] = $wu->id;
286
    }
287
    $ids = implode(',', $ids);
288
    BoincResult::update_aux(
289
        sprintf(
290
            'server_state=%d, outcome=%d where server_state=%d and workunitid in (%s)',
291
            RESULT_SERVER_STATE_OVER, RESULT_OUTCOME_DIDNT_NEED,
292
            RESULT_SERVER_STATE_UNSENT,
293
            $ids
294
        )
295
    );
296
    BoincWorkunit::update_aux(
297
        sprintf('error_mask=error_mask|%d where id in(%s)',
298
            WU_ERROR_CANCELLED, $ids
299
        )
300
    );
301
    $batch->update(
302
        sprintf('state=%d', BATCH_STATE_ABORTED)
303
    );
304
    return 0;
305
}
306
307
// mark WUs as assimilated; this lets them be purged
308
//
309
function retire_batch($batch) {
310
    $wus = BoincWorkunit::enum_fields(
311
        'id, result_template_file',
312
        "batch=$batch->id limit 100"
313
    );
314
    $now = time();
315
    $ids = [];
316
    foreach ($wus as $wu) {
317
        $ids[] = $wu->id;
318
    }
319
    $ids = implode(',', $ids);
320
    BoincWorkunit::update_aux(
321
        sprintf('assimilate_state=%d, transition_time=%d where id in(%s)',
322
            ASSIMILATE_DONE, $now, $ids
323
        )
324
    );
325
    foreach ($wus as $wu) {
326
        // remove output template if it's a temporary
327
        //
328
        if (strstr($wu->result_template_file, "templates/tmp/")) {
329
            @unlink($wu->result_template_file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

329
            /** @scrutinizer ignore-unhandled */ @unlink($wu->result_template_file);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
330
        }
331
    }
332
    $batch->update("state=".BATCH_STATE_RETIRED);
333
    system("rm -rf ../../results/$batch->id");
334
}
335
336
function expire_batch($batch) {
337
    abort_batch($batch);
338
    retire_batch($batch);
339
    $batch->update("state=".BATCH_STATE_EXPIRED);
340
}
341
342
function batch_state_string($state) {
343
    switch ($state) {
344
    case BATCH_STATE_INIT: return "new";
345
    case BATCH_STATE_IN_PROGRESS: return "in progress";
346
    case BATCH_STATE_COMPLETE: return "completed";
347
    case BATCH_STATE_ABORTED: return "aborted";
348
    case BATCH_STATE_RETIRED: return "retired";
349
    }
350
    return "unknown state $state";
351
}
352
// get the total size of output files of a batch
353
//
354
function batch_output_file_size($batchid) {
355
    $batch_td_size=0;
356
    $wus = BoincWorkunit::enum_fields(
357
        'canonical_resultid',
358
        "batch=$batchid"
359
    );
360
    $fanout = parse_config(get_config(), "<uldl_dir_fanout>");
361
    $upload_dir = parse_config(get_config(), "<upload_dir>");
362
    foreach ($wus as $wu) {
363
        if (!$wu->canonical_resultid) continue;
364
        $result = BoincResult::lookup_id($wu->canonical_resultid);
365
        $names = get_outfile_phys_names($result);
366
        foreach ($names as $name) {
367
            $path = dir_hier_path($name, $upload_dir, $fanout);
368
            if (is_file($path)) {
369
                $batch_td_size += filesize($path);
370
            }
371
        }
372
    }
373
    return $batch_td_size;
374
}
375
376
function boinc_get_output_file_url($user, $result, $i) {
377
    $name = $result->name;
378
    $auth_str = md5($user->authenticator.$name);
379
    return "get_output.php?cmd=result_file&result_name=$name&file_num=$i&auth_str=$auth_str";
380
}
381
382
function boinc_get_output_files_url($user, $batch_id) {
383
    $auth_str = md5($user->authenticator.$batch_id);
384
    return "get_output.php?cmd=batch_files&batch_id=$batch_id&auth_str=$auth_str";
385
}
386
387
function boinc_get_wu_output_files_url($user, $wu_id) {
388
    $auth_str =  md5($user->authenticator.$wu_id);
0 ignored issues
show
Expected 1 space after "="; 2 found
Loading history...
389
    return "get_output.php?cmd=workunit_files&wu_id=$wu_id&auth_str=$auth_str";
390
}
391
392
////////////////// FILE INFO FILES //////////////
393
394
// these are used:
395
// 1) in user file sandbox
396
// 2) in BUDA app variant dirs
397
// in each case a file dir/foo has an info file dir/.md5/foo
398
// containing its md5 and size
399
// (same format as .md5 files in download hierarchy)
400
401
// get the MD5 and size of a file
402
//
403
function get_file_info($path) {
404
    $md5 = md5_file($path);
405
    $s = stat($path);
406
    $size = $s['size'];
407
    return [$md5, $size];
408
}
409
410
// write a "info file" containing MD5 and size
411
//
412
function write_info_file($path, $md5, $size) {
413
    file_put_contents($path, "$md5 $size");
414
}
415
416
// parse info file and return [md5, size]
417
//
418
function parse_info_file($path) {
419
    if (!file_exists($path)) return null;
420
    $x = file_get_contents($path);
421
    $n = sscanf($x, "%s %d", $md5, $size);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $size seems to be never defined.
Loading history...
422
    if ($n != 2 || strlen($md5)!=32) {
423
        return null;
424
    }
425
    return [$md5, $size];
426
}
427
428
///////////////// TEMPLATE CREATION //////////////
429
430
function file_ref_in($fname) {
431
    return(sprintf(
432
'      <file_ref>
433
         <open_name>%s</open_name>
434
         <copy_file/>
435
      </file_ref>
436
',
437
        $fname
438
    ));
439
}
440
function file_info_out($i) {
441
    return sprintf(
442
'    <file_info>
443
        <name><OUTFILE_%d/></name>
444
        <generated_locally/>
445
        <upload_when_present/>
446
        <max_nbytes>5000000</max_nbytes>
447
        <url><UPLOAD_URL/></url>
448
    </file_info>
449
',
450
        $i
451
    );
452
}
453
454
function file_ref_out($i, $fname) {
455
    return sprintf(
456
'        <file_ref>
457
            <file_name><OUTFILE_%d/></file_name>
458
            <open_name>%s</open_name>
459
            <copy_file/>
460
        </file_ref>
461
',      $i, $fname
462
    );
463
}
464
465
?>
466