Issues (1963)

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
    if ($ids) {
288
        $ids = implode(',', $ids);
289
        BoincResult::update_aux(
290
            sprintf(
291
                'server_state=%d, outcome=%d where server_state=%d and workunitid in (%s)',
292
                RESULT_SERVER_STATE_OVER, RESULT_OUTCOME_DIDNT_NEED,
293
                RESULT_SERVER_STATE_UNSENT,
294
                $ids
295
            )
296
        );
297
        BoincWorkunit::update_aux(
298
            sprintf('error_mask=error_mask|%d where id in(%s)',
299
                WU_ERROR_CANCELLED, $ids
300
            )
301
        );
302
    }
303
    $batch->update(
304
        sprintf('state=%d', BATCH_STATE_ABORTED)
305
    );
306
    return 0;
307
}
308
309
// mark WUs as assimilated; this lets them be purged
310
//
311
function retire_batch($batch) {
312
    $wus = BoincWorkunit::enum_fields(
313
        'id, result_template_file',
314
        "batch=$batch->id limit 100"
315
    );
316
    $now = time();
317
    $ids = [];
318
    foreach ($wus as $wu) {
319
        $ids[] = $wu->id;
320
    }
321
    if ($ids) {
322
        $ids = implode(',', $ids);
323
        BoincWorkunit::update_aux(
324
            sprintf('assimilate_state=%d, transition_time=%d where id in(%s)',
325
                ASSIMILATE_DONE, $now, $ids
326
            )
327
        );
328
        foreach ($wus as $wu) {
329
            // remove output template if it's a temporary
330
            //
331
            if (strstr($wu->result_template_file, "templates/tmp/")) {
332
                @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

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