Passed
Pull Request — master (#6611)
by David
14:52 queued 05:45
created

n_jobs_in_progress()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 12
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 16
rs 9.8666
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', 1);
29
define('WU_IN_PROGRESS', 2);
30
define('WU_SUCCESS', 3);
31
define('WU_ERROR', 4);
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
introduced by
$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
// return # of in-progress jobs for user
58
//
59
function n_jobs_in_progress($user_id) {
60
    $batches = BoincBatch::enum(
61
        sprintf(
62
            'user_id=%d and state=%d',
63
            $user_id, BATCH_STATE_IN_PROGRESS
64
        )
65
    );
66
    $ids = [];
67
    foreach ($batches as $batch) {
68
        $ids[] = $batch->id;
69
    }
70
    if (!$ids) return 0;
71
    $ids = implode(',', $ids);
72
    return BoincWorkunit::count(
73
        sprintf('error_mask=0 and canonical_resultid=0 and batch in (%s)',
74
            $ids
75
        )
76
    );
77
}
78
79
// in remote job submission,
80
// for input files of type local, semilocal, and inline,
81
// we need to give a unique physical name based on its content.
82
// Prepend the jf_ to make the origin of the file clear
83
//
84
function job_file_name($md5) {
85
    return "jf_$md5";
86
}
87
88
// can user upload files?
89
//
90
function has_file_access($user) {
91
    $us = BoincUserSubmit::lookup_userid($user->id);
92
    if (!$us) return false;
93
    return true;
94
}
95
96
// can user submit to given app?
97
//
98
function has_submit_access($user, $app_id) {
99
    $us = BoincUserSubmit::lookup_userid($user->id);
100
    if (!$us) return false;
101
    if ($us->submit_all) return true;
102
    $usa = BoincUserSubmitApp::lookup("user_id=$user->id and app_id=$app_id");
103
    if (!$usa) return false;
104
    return true;
105
}
106
107
// can user manage given app (or all apps if zero)?
108
//
109
function has_manage_access($user, $app_id) {
110
    $us = BoincUserSubmit::lookup_userid($user->id);
111
    if (!$us) return false;
112
    if ($us->manage_all) return true;
113
    $usa = BoincUserSubmitApp::lookup("user_id=$user->id and app_id=$app_id");
114
    if (!$usa) return false;
115
    return $usa->manage;
116
}
117
118
// check whether user has permissions for a remote job submission
119
// or job file request.
120
// $r is a request message that includes an 'authenticator' field
121
// $app is the app being submitted to (or null if file op)
122
// returns user, or give XML error and quit
123
//
124
function check_remote_submit_permissions($r, $app) {
125
    $auth = (string)$r->authenticator;
126
    if (!$auth) {
127
        log_write("no authenticator");
128
        xml_error(-1, "no authenticator");
129
    }
130
    $auth = BoincDb::escape_string($auth);
131
    $user = BoincUser::lookup("authenticator='$auth'");
132
    if (!$user) {
133
        log_write("bad authenticator");
134
        xml_error(-1, "bad authenticator");
135
    }
136
137
    // check access
138
    //
139
    if ($app) {
140
        if (!has_submit_access($user, $app->id)) {
141
            log_write("no submit access");
142
            xml_error(-1, "no submit access");
143
        }
144
    } else {
145
        if (!has_file_access($user)) {
146
            log_write("no file access");
147
            xml_error(-1, "no file access");
148
        }
149
    }
150
    return $user;
151
}
152
153
// remove all of user's permissions
154
//
155
function delete_remote_submit_user($user) {
156
    BoincUserSubmit::delete_user($user->id);
157
    BoincUserSubmitApp::delete_user($user->id);
158
}
159
160
// compute parameters of the batch:
161
//   credit_canonical: credit granted to canonical instances
162
//   fraction_done: frac of jobs that are done (success or failed)
163
//   state: whether complete (all jobs done)
164
//   completion_time: if newly complete
165
//   nerror_jobs: # of failed jobs
166
// Update the above in DB.
167
// Also compute (not in DB):
168
//   njobs_success: # of jobs with canonical instance
169
//   njobs_in_prog: # of jobs not success or fail,
170
//      and at least one result in progress
171
// return the batch object, with these values
172
//
173
// You need to pass in a list of the batch's WUs.
174
// These need to have the following fields:
175
//
176
// id
177
// rsc_fpops_est
178
// canonical_resultid
179
// canonical_credit
180
// error_mask
181
//
182
// add 'status' field (UNSENT, IN_PROGRESS, SUCCESS) to WUs
183
//
184
// 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...
185
//
186
function get_batch_params($batch, $wus) {
187
    if ($batch->state == BATCH_STATE_INIT) {
188
        // a batch in INIT state has no jobs
189
        //
190
        return $batch;
191
    }
192
    if (!$wus) {
193
        if ($batch->njobs) {
194
            $batch->update('njobs=0');
195
            $batch->njobs = 0;
196
        }
197
        return $batch;
198
    }
199
200
    // make list of WU IDs with an in-progress result
201
    $res_in_prog = BoincResult::enum_fields(
202
        'workunitid',
203
        sprintf('batch=%d and server_state in (%d, %d)',
204
            $batch->id,
205
            RESULT_SERVER_STATE_IN_PROGRESS, RESULT_SERVER_STATE_OVER
206
        )
207
    );
208
    $wus_in_prog = [];
209
    foreach ($res_in_prog as $res) {
210
        $wus_in_prog[$res->workunitid] = true;
211
    }
212
    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...
213
214
    $fp_total = 0;
215
    $fp_done = 0;
216
    $completed = true;
217
    $batch->nerror_jobs = 0;
218
    $batch->credit_canonical = 0;
219
    $njobs_success = 0;
220
    $njobs_in_prog = 0;
221
    foreach ($wus as $wu) {
222
        $fp_total += $wu->rsc_fpops_est;
223
        if ($wu->canonical_resultid) {
224
            $fp_done += $wu->rsc_fpops_est;
225
            $njobs_success++;
226
            $batch->credit_canonical += $wu->canonical_credit;
227
            $wu->status = WU_SUCCESS;
228
        } else if ($wu->error_mask) {
229
            $batch->nerror_jobs++;
230
            $wu->status = WU_ERROR;
231
        } else {
232
            $completed = false;
233
            if (array_key_exists($wu->id, $wus_in_prog)) {
234
                $njobs_in_prog++;
235
                $wu->status = WU_IN_PROGRESS;
236
            } else {
237
                $wu->status = WU_UNSENT;
238
            }
239
        }
240
    }
241
    $njobs = count($wus);
242
    $batch->njobs = $njobs;
243
    $batch->fraction_done = ($njobs_success + $batch->nerror_jobs)/$batch->njobs;
244
    if ($completed && $batch->state == BATCH_STATE_IN_PROGRESS) {
245
        $batch->state = BATCH_STATE_COMPLETE;
246
        $batch->completion_time = time();
247
    }
248
    $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");
249
250
    $batch->njobs_success = $njobs_success;
251
    $batch->njobs_in_prog = $njobs_in_prog;
252
    return $batch;
253
}
254
255
// get params of in-progress batches; they might not be in progress anymore.
256
//
257
function get_batches_params($batches) {
258
    $b = [];
259
    foreach ($batches as $batch) {
260
        if ($batch->state == BATCH_STATE_IN_PROGRESS) {
261
            $wus = BoincWorkunit::enum_fields(
262
                'id, name, rsc_fpops_est, canonical_credit, canonical_resultid, error_mask',
263
                "batch = $batch->id"
264
            );
265
            $b[] = get_batch_params($batch, $wus);
266
        } else {
267
            $b[] = $batch;
268
        }
269
    }
270
    return $b;
271
}
272
273
// get the physical names of a result's output files.
274
//
275
function get_outfile_phys_names($result) {
276
    $names = [];
277
    $xml = "<a>".$result->xml_doc_out."</a>";
278
    $r = simplexml_load_string($xml);
279
    if (!$r) return $names;
0 ignored issues
show
introduced by
$r is of type SimpleXMLElement, thus it always evaluated to true.
Loading history...
280
    foreach ($r->file_info as $fi) {
281
        $names[] = (string)($fi->name);
282
    }
283
    return $names;
284
}
285
286
function get_outfile_log_names($result) {
287
    $names = [];
288
    $xml = "<a>".$result->xml_doc_in."</a>";
289
    $r = simplexml_load_string($xml);
290
    if (!$r) return $names;
0 ignored issues
show
introduced by
$r is of type SimpleXMLElement, thus it always evaluated to true.
Loading history...
291
    foreach ($r->result->file_ref as $fr) {
292
        $names[] = (string)($fr->open_name);
293
    }
294
    return $names;
295
}
296
297
function get_outfile_paths($result) {
298
    $fanout = parse_config(get_config(), "<uldl_dir_fanout>");
299
    $upload_dir = parse_config(get_config(), "<upload_dir>");
300
301
    $paths = array();
302
    $xml = "<a>".$result->xml_doc_out."</a>";
303
    $r = simplexml_load_string($xml);
304
    if (!$r) return $paths;
0 ignored issues
show
introduced by
$r is of type SimpleXMLElement, thus it always evaluated to true.
Loading history...
305
    foreach ($r->file_info as $fi) {
306
        $path = dir_hier_path((string)($fi->name), $upload_dir, $fanout);
307
        $paths[] = $path;
308
    }
309
    return $paths;
310
}
311
312
function abort_workunit($wu) {
313
    BoincResult::update_aux(
314
        sprintf(
315
            'server_state=%d, outcome=%d where server_state=%d and workunitid=%d',
316
            RESULT_SERVER_STATE_OVER, RESULT_OUTCOME_DIDNT_NEED,
317
            RESULT_SERVER_STATE_UNSENT,
318
            $wu->id
319
        )
320
    );
321
    $wu->update(
322
        sprintf('error_mask=error_mask|%d, file_delete_state=%d',
323
            WU_ERROR_CANCELLED, FILE_DELETE_READY
324
        )
325
    );
326
}
327
328
function abort_batch($batch) {
329
    $wus = BoincWorkunit::enum_fields(
330
        'id',
331
        "batch=$batch->id"
332
    );
333
    $ids = [];
334
    foreach ($wus as $wu) {
335
        $ids[] = $wu->id;
336
    }
337
    if ($ids) {
338
        $ids = implode(',', $ids);
339
        // cancel unsent instances
340
        //
341
        BoincResult::update_aux(
342
            sprintf(
343
                'server_state=%d, outcome=%d where server_state=%d and workunitid in (%s)',
344
                RESULT_SERVER_STATE_OVER, RESULT_OUTCOME_DIDNT_NEED,
345
                RESULT_SERVER_STATE_UNSENT,
346
                $ids
347
            )
348
        );
349
        BoincWorkunit::update_aux(
350
            sprintf('error_mask=error_mask|%d, file_delete_state=%d where id in(%s)',
351
                WU_ERROR_CANCELLED, FILE_DELETE_READY, $ids
352
            )
353
        );
354
    }
355
    $batch->update(
356
        sprintf('state=%d, completion_time=%d', BATCH_STATE_ABORTED, time())
357
    );
358
    return 0;
359
}
360
361
// retire a batch:
362
// - mark the batch as retired (don't delete it; might be useful later)
363
// - delete output files (results/batchid/)
364
// - mark unsent WUs as cancelled
365
//
366
// Don't delete the batch; it may have in-progress jobs that
367
// we still need to file-delete and purge,
368
// and the batch needs to be present for this.
369
// Use ops/delete_batches.php to delete retired batches with no WUs
370
//
371
function retire_batch($batch) {
372
    system("rm -rf ../../results/$batch->id");
373
374
    // get list of unsent WUs in this batch
375
    //
376
    $wus = BoincWorkunit::enum_fields(
377
        'id, rsc_fpops_est, canonical_credit, canonical_resultid, error_mask',
378
        "batch = $batch->id"
379
    );
380
    get_batch_params($batch, $wus);
381
    $batch->update("state=".BATCH_STATE_RETIRED);
382
        // do this AFTER get_batch_params()
383
    $wu_ids = [];
384
    foreach ($wus as $wu) {
385
        if ($wu->status == WU_UNSENT) {
386
            $wu_ids[] = $wu->id;
387
        }
388
    }
389
390
    // cancel them
391
    //
392
    if ($wu_ids) {
393
        $wu_ids = implode(',', $wu_ids);
394
        BoincWorkunit::update_aux(
395
            sprintf('error_mask=error_mask|%d, file_delete_state=%d where id in (%s)',
396
                WU_ERROR_CANCELLED, FILE_DELETE_READY, $wu_ids
397
            )
398
        );
399
    }
400
}
401
402
function expire_batch($batch) {
403
    abort_batch($batch);
404
    retire_batch($batch);
405
    $batch->update("state=".BATCH_STATE_EXPIRED);
406
}
407
408
function batch_state_string($state) {
409
    switch ($state) {
410
    case BATCH_STATE_INIT: return "new";
411
    case BATCH_STATE_IN_PROGRESS: return "in progress";
412
    case BATCH_STATE_COMPLETE: return "completed";
413
    case BATCH_STATE_ABORTED: return "aborted";
414
    case BATCH_STATE_RETIRED: return "retired";
415
    }
416
    return "unknown state $state";
417
}
418
// get the total size of output files of a batch
419
//
420
function batch_output_file_size($batchid) {
421
    $batch_td_size=0;
422
    $wus = BoincWorkunit::enum_fields(
423
        'canonical_resultid',
424
        "batch=$batchid"
425
    );
426
    $fanout = parse_config(get_config(), "<uldl_dir_fanout>");
427
    $upload_dir = parse_config(get_config(), "<upload_dir>");
428
    foreach ($wus as $wu) {
429
        if (!$wu->canonical_resultid) continue;
430
        $result = BoincResult::lookup_id($wu->canonical_resultid);
431
        $names = get_outfile_phys_names($result);
432
        foreach ($names as $name) {
433
            $path = dir_hier_path($name, $upload_dir, $fanout);
434
            if (is_file($path)) {
435
                $batch_td_size += filesize($path);
436
            }
437
        }
438
    }
439
    return $batch_td_size;
440
}
441
442
function boinc_get_output_file_url($user, $result, $i) {
443
    $name = $result->name;
444
    $auth_str = md5($user->authenticator.$name);
445
    return "get_output.php?cmd=result_file&result_name=$name&file_num=$i&auth_str=$auth_str";
446
}
447
448
function boinc_get_output_files_url($user, $batch_id) {
449
    $auth_str = md5($user->authenticator.$batch_id);
450
    return "get_output.php?cmd=batch_files&batch_id=$batch_id&auth_str=$auth_str";
451
}
452
453
function boinc_get_wu_output_files_url($user, $wu_id) {
454
    $auth_str =  md5($user->authenticator.$wu_id);
0 ignored issues
show
Coding Style introduced by
Expected 1 space after "="; 2 found
Loading history...
455
    return "get_output.php?cmd=workunit_files&wu_id=$wu_id&auth_str=$auth_str";
456
}
457
458
////////////////// FILE INFO FILES //////////////
459
460
// these are used:
461
// 1) in user file sandbox
462
// 2) in BUDA app variant dirs
463
// in each case a file dir/foo has an info file dir/.md5/foo
464
// containing its md5 and size
465
// (same format as .md5 files in download hierarchy)
466
467
// get the MD5 and size of a file
468
//
469
function get_file_info($path) {
470
    $md5 = md5_file($path);
471
    $s = stat($path);
472
    $size = $s['size'];
473
    return [$md5, $size];
474
}
475
476
// write a "info file" containing MD5 and size
477
//
478
function write_info_file($path, $md5, $size) {
479
    file_put_contents($path, "$md5 $size");
480
}
481
482
// parse info file and return [md5, size]
483
//
484
function parse_info_file($path) {
485
    if (!file_exists($path)) return null;
486
    $x = file_get_contents($path);
487
    $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...
488
    if ($n != 2 || strlen($md5)!=32) {
489
        return null;
490
    }
491
    return [$md5, $size];
492
}
493
494
///////////////// TEMPLATE CREATION //////////////
495
496
function file_ref_in($fname) {
497
    return(sprintf(
498
'      <file_ref>
499
         <open_name>%s</open_name>
500
         <copy_file/>
501
      </file_ref>
502
',
503
        $fname
504
    ));
505
}
506
function file_info_out($i) {
507
    return sprintf(
508
'    <file_info>
509
        <name><OUTFILE_%d/></name>
510
        <generated_locally/>
511
        <upload_when_present/>
512
        <max_nbytes>5000000</max_nbytes>
513
        <url><UPLOAD_URL/></url>
514
    </file_info>
515
',
516
        $i
517
    );
518
}
519
520
function file_ref_out($i, $fname) {
521
    return sprintf(
522
'        <file_ref>
523
            <file_name><OUTFILE_%d/></file_name>
524
            <open_name>%s</open_name>
525
            <copy_file/>
526
        </file_ref>
527
',      $i, $fname
528
    );
529
}
530
531
?>
532