Passed
Push — dpa_submit24 ( 53eee7 )
by David
10:09
created

has_manage_access()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 6
c 0
b 0
f 0
nc 4
nop 2
dl 0
loc 7
rs 10
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
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
// 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=%d',
174
            $batch->id, RESULT_SERVER_STATE_IN_PROGRESS
175
        )
176
    );
177
    $wus_in_prog = [];
178
    foreach ($res_in_prog as $res) {
179
        $wus_in_prog[$res->workunitid] = true;
180
    }
181
    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...
182
183
    $fp_total = 0;
184
    $fp_done = 0;
185
    $completed = true;
186
    $batch->nerror_jobs = 0;
187
    $batch->credit_canonical = 0;
188
    $njobs_success = 0;
189
    $njobs_in_prog = 0;
190
    foreach ($wus as $wu) {
191
        $fp_total += $wu->rsc_fpops_est;
192
        if ($wu->canonical_resultid) {
193
            $fp_done += $wu->rsc_fpops_est;
194
            $njobs_success++;
195
            $batch->credit_canonical += $wu->canonical_credit;
196
            $wu->status = WU_SUCCESS;
197
        } else if ($wu->error_mask) {
198
            $batch->nerror_jobs++;
199
            $wu->status = WU_ERROR;
200
        } else {
201
            $completed = false;
202
            if (array_key_exists($wu->id, $wus_in_prog)) {
203
                $njobs_in_prog++;
204
                $wu->status = WU_IN_PROGRESS;
205
            } else {
206
                $wu->status = WU_UNSENT;
207
            }
208
        }
209
    }
210
    $njobs = count($wus);
211
    $batch->njobs = $njobs;
212
    $batch->fraction_done = ($njobs_success + $batch->nerror_jobs)/$batch->njobs;
213
    if ($completed && $batch->state == BATCH_STATE_IN_PROGRESS) {
214
        $batch->state = BATCH_STATE_COMPLETE;
215
        $batch->completion_time = time();
216
    }
217
    $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");
218
219
    $batch->njobs_success = $njobs_success;
220
    $batch->njobs_in_prog = $njobs_in_prog;
221
    return $batch;
222
}
223
224
// get the physical names of a result's output files.
225
//
226
function get_outfile_phys_names($result) {
227
    $names = [];
228
    $xml = "<a>".$result->xml_doc_out."</a>";
229
    $r = simplexml_load_string($xml);
230
    if (!$r) return $names;
0 ignored issues
show
introduced by
$r is of type SimpleXMLElement, thus it always evaluated to true.
Loading history...
231
    foreach ($r->file_info as $fi) {
232
        $names[] = (string)($fi->name);
233
    }
234
    return $names;
235
}
236
237
function get_outfile_log_names($result) {
238
    $names = [];
239
    $xml = "<a>".$result->xml_doc_in."</a>";
240
    $r = simplexml_load_string($xml);
241
    if (!$r) return $names;
0 ignored issues
show
introduced by
$r is of type SimpleXMLElement, thus it always evaluated to true.
Loading history...
242
    foreach ($r->result->file_ref as $fr) {
243
        $names[] = (string)($fr->open_name);
244
    }
245
    return $names;
246
}
247
248
function get_outfile_paths($result) {
249
    $fanout = parse_config(get_config(), "<uldl_dir_fanout>");
250
    $upload_dir = parse_config(get_config(), "<upload_dir>");
251
252
    $paths = array();
253
    $xml = "<a>".$result->xml_doc_out."</a>";
254
    $r = simplexml_load_string($xml);
255
    if (!$r) return $paths;
0 ignored issues
show
introduced by
$r is of type SimpleXMLElement, thus it always evaluated to true.
Loading history...
256
    foreach ($r->file_info as $fi) {
257
        $path = dir_hier_path((string)($fi->name), $upload_dir, $fanout);
258
        $paths[] = $path;
259
    }
260
    return $paths;
261
}
262
263
function abort_workunit($wu) {
264
    BoincResult::update_aux(
265
        sprintf(
266
            'server_state=%d, outcome=%d where server_state=%d and workunitid=%d',
267
            RESULT_SERVER_STATE_OVER, RESULT_OUTCOME_DIDNT_NEED,
268
            RESULT_SERVER_STATE_UNSENT,
269
            $wu->id
270
        )
271
    );
272
    $wu->update("error_mask=error_mask|16");
273
}
274
275
function abort_batch($batch) {
276
    $wus = BoincWorkunit::enum("batch=$batch->id");
277
    foreach ($wus as $wu) {
278
        abort_workunit($wu);
279
    }
280
    $batch->update(
281
        sprintf('state=%d', BATCH_STATE_ABORTED)
282
    );
283
    return 0;
284
}
285
286
// mark WUs as assimilated; this lets them be purged
287
//
288
function retire_batch($batch) {
289
    $wus = BoincWorkunit::enum("batch=$batch->id");
290
    $now = time();
291
    foreach ($wus as $wu) {
292
        $wu->update(
293
            "assimilate_state=".ASSIMILATE_DONE.", transition_time=$now"
294
        );
295
        // remove output template if it's a temporary
296
        //
297
        if (strstr($wu->result_template_file, "templates/tmp/")) {
298
            @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

298
            /** @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...
299
        }
300
    }
301
    $batch->update("state=".BATCH_STATE_RETIRED);
302
}
303
304
function expire_batch($batch) {
305
    abort_batch($batch);
306
    retire_batch($batch);
307
    $batch->update("state=".BATCH_STATE_EXPIRED);
308
}
309
310
function batch_state_string($state) {
311
    switch ($state) {
312
    case BATCH_STATE_INIT: return "new";
313
    case BATCH_STATE_IN_PROGRESS: return "in progress";
314
    case BATCH_STATE_COMPLETE: return "completed";
315
    case BATCH_STATE_ABORTED: return "aborted";
316
    case BATCH_STATE_RETIRED: return "retired";
317
    }
318
    return "unknown state $state";
319
}
320
// get the total size of output files of a batch
321
//
322
function batch_output_file_size($batchid) {
323
    $batch_td_size=0;
324
    $wus = BoincWorkunit::enum("batch=$batchid");
325
    $fanout = parse_config(get_config(), "<uldl_dir_fanout>");
326
    $upload_dir = parse_config(get_config(), "<upload_dir>");
327
    foreach ($wus as $wu) {
328
        if (!$wu->canonical_resultid) continue;
329
        $result = BoincResult::lookup_id($wu->canonical_resultid);
330
        $names = get_outfile_phys_names($result);
331
        foreach ($names as $name) {
332
            $path = dir_hier_path($name, $upload_dir, $fanout);
333
            if (is_file($path)) {
334
                $batch_td_size += filesize($path);
335
            }
336
        }
337
    }
338
    return $batch_td_size;
339
}
340
341
function boinc_get_output_file_url($user, $result, $i) {
342
    $name = $result->name;
343
    $auth_str = md5($user->authenticator.$name);
344
    return "get_output.php?cmd=result_file&result_name=$name&file_num=$i&auth_str=$auth_str";
345
}
346
347
function boinc_get_output_files_url($user, $batch_id) {
348
    $auth_str = md5($user->authenticator.$batch_id);
349
    return "get_output.php?cmd=batch_files&batch_id=$batch_id&auth_str=$auth_str";
350
}
351
352
function boinc_get_wu_output_files_url($user, $wu_id) {
353
    $auth_str =  md5($user->authenticator.$wu_id);
0 ignored issues
show
Coding Style introduced by
Expected 1 space after "="; 2 found
Loading history...
354
    return "get_output.php?cmd=workunit_files&wu_id=$wu_id&auth_str=$auth_str";
355
}
356
357
////////////////// FILE INFO FILES //////////////
358
359
// these are used:
360
// 1) in user file sandbox
361
// 2) in BUDA app variant dirs
362
// in each case a file dir/foo has an info file dir/.md5/foo
363
// containing its md5 and size
364
// (same format as .md5 files in download hierarchy)
365
366
// get the MD5 and size of a file
367
//
368
function get_file_info($path) {
369
    $md5 = md5_file($path);
370
    $s = stat($path);
371
    $size = $s['size'];
372
    return [$md5, $size];
373
}
374
375
// write a "info file" containing MD5 and size
376
//
377
function write_info_file($path, $md5, $size) {
378
    file_put_contents($path, "$md5 $size");
379
}
380
381
// parse info file and return [md5, size]
382
//
383
function parse_info_file($path) {
384
    if (!file_exists($path)) return null;
385
    $x = file_get_contents($path);
386
    $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...
387
    if ($n != 2 || strlen($md5)!=32) {
388
        return null;
389
    }
390
    return [$md5, $size];
391
}
392
393
///////////////// TEMPLATE CREATION //////////////
394
395
function file_ref_in($fname) {
396
    return(sprintf(
397
'      <file_ref>
398
         <open_name>%s</open_name>
399
         <copy_file/>
400
      </file_ref>
401
',
402
        $fname
403
    ));
404
}
405
function file_info_out($i) {
406
    return sprintf(
407
'    <file_info>
408
        <name><OUTFILE_%d/></name>
409
        <generated_locally/>
410
        <upload_when_present/>
411
        <max_nbytes>5000000</max_nbytes>
412
        <url><UPLOAD_URL/></url>
413
    </file_info>
414
',
415
        $i
416
    );
417
}
418
419
function file_ref_out($i, $fname) {
420
    return sprintf(
421
'        <file_ref>
422
            <file_name><OUTFILE_%d/></file_name>
423
            <open_name>%s</open_name>
424
            <copy_file/>
425
        </file_ref>
426
',      $i, $fname
427
    );
428
}
429
430
?>
431