Passed
Push — master ( 31517f...dc3597 )
by Vitalii
01:28 queued 22s
created

wus_nsent()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 11
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 submissions and control
21
22
require_once("../inc/submit_db.inc");
23
24
// write status and error messages to log
25
//
26
function log_write($x) {
27
    static $enabled, $log_file;
28
29
    if (!isset($enabled)) {
30
        $enabled = false;
31
        $filename = parse_config(get_config(), "<remote_submit_log>");
32
        if (!$filename) {
33
            return;
34
        }
35
        $log_dir = parse_config(get_config(), "<log_dir>");
36
        if (!$log_dir) {
37
            return;
38
        }
39
        $log_file = fopen("$log_dir/$filename", "a");
40
        if (!$log_file) return;
0 ignored issues
show
introduced by
$log_file is of type resource, thus it always evaluated to false.
Loading history...
41
        $enabled = true;
42
    }
43
    if (!$enabled) return;
44
    fwrite($log_file, sprintf("%s: %s\n", strftime("%c"), $x));
45
    fflush($log_file);
46
}
47
48
// in remote job submission,
49
// for input files of type local, semilocal, and inline,
50
// we need to give a unique physical name based on its content.
51
// Prepend the jf_ to make the origin of the file clear
52
//
53
function job_file_name($md5) {
54
    return "jf_$md5";
55
}
56
57
// can user upload files?
58
//
59
function has_file_access($user) {
60
    $us = BoincUserSubmit::lookup_userid($user->id);
61
    if (!$us) return false;
62
    return true;
63
}
64
65
// can user submit to given app?
66
//
67
function has_submit_access($user, $app_id) {
68
    $us = BoincUserSubmit::lookup_userid($user->id);
69
    if (!$us) return false;
70
    if ($us->submit_all) return true;
71
    $usa = BoincUserSubmitApp::lookup("user_id=$user->id and app_id=$app_id");
72
    if (!$usa) return false;
73
    return true;
74
}
75
76
// can user administer given app (or all apps if zero)?
77
//
78
function has_admin_access($user, $app_id) {
79
    $us = BoincUserSubmit::lookup_userid($user->id);
80
    if (!$us) return false;
81
    if ($us->manage_all) return true;
82
    $usa = BoincUserSubmitApp::lookup("user_id=$user->id and app_id=$app_id");
83
    if (!$usa) return false;
84
    return $usa->manage;
85
}
86
87
// check whether user has permissions for a remote job submission
88
// or job file request.
89
// $r is a request message that includes an 'authenticator' field
90
// $app is the app being submitted to (or null if file op)
91
// returns user, or give XML error and quit
92
//
93
function check_remote_submit_permissions($r, $app) {
94
    $auth = (string)$r->authenticator;
95
    if (!$auth) {
96
        log_write("no authenticator");
97
        xml_error(-1, "no authenticator");
98
    }
99
    $auth = BoincDb::escape_string($auth);
100
    $user = BoincUser::lookup("authenticator='$auth'");
101
    if (!$user) {
102
        log_write("bad authenticator");
103
        xml_error(-1, "bad authenticator");
104
    }
105
106
    // check access
107
    //
108
    if ($app) {
109
        if (!has_submit_access($user, $app->id)) {
110
            log_write("no submit access");
111
            xml_error(-1, "no submit access");
112
        }
113
    } else {
114
        if (!has_file_access($user)) {
115
            log_write("no file access");
116
            xml_error(-1, "no file access");
117
        }
118
    }
119
    return $user;
120
}
121
122
// remove all of user's permissions
123
//
124
function delete_remote_submit_user($user) {
125
    BoincUserSubmit::delete_user($user->id);
126
    BoincUserSubmitApp::delete_user($user->id);
127
}
128
129
// given its WUs, compute parameters of a batch:
130
//   credit_canonical: credit granted to canonical instances
131
//   fraction_done: frac of jobs that are done (success or failed)
132
//   state: whether complete (all jobs done)
133
//   completion_time: if newly complete
134
//   nerror_jobs: # of failed jobs
135
// Update the above in DB.
136
// Also compute (not in DB):
137
//   njobs_success: # of jobs with canonical instance
138
//   njobs_in_prog: # of jobs not success or fail,
139
//      and at least one result in progress
140
//
141
// return the batch object, with these values
142
//
143
// NOTE: this involves reading the batch's WUs and results,
144
// which could be inefficient for huge batches.
145
// It could instead be done by server components
146
// (transitioner, validator etc.) as jobs complete or time out
147
//
148
// 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...
149
//
150
function get_batch_params($batch, $wus) {
151
    if ($batch->state == BATCH_STATE_INIT) {
152
        // a batch in INIT state has no jobs
153
        //
154
        return $batch;
155
    }
156
    if (!$wus) {
157
        if ($batch->njobs) {
158
            $batch->update('njobs=0');
159
            $batch->njobs = 0;
160
        }
161
        return $batch;
162
    }
163
164
    // make list of WU IDs with an in-progress result
165
    $res_in_prog = BoincResult::enum(
166
        sprintf('batch=%d and server_state<>%d',
167
            $batch->id, RESULT_SERVER_STATE_IN_PROGRESS
168
        )
169
    );
170
    $wus_in_prog = [];
171
    foreach ($res_in_prog as $res) {
172
        $wus_in_prog[$res->workunitid] = true;
173
    }
174
175
    $fp_total = 0;
176
    $fp_done = 0;
177
    $completed = true;
178
    $batch->nerror_jobs = 0;
179
    $batch->credit_canonical = 0;
180
    $njobs_success = 0;
181
    $njobs_in_prog = 0;
182
    foreach ($wus as $wu) {
183
        $fp_total += $wu->rsc_fpops_est;
184
        if ($wu->canonical_resultid) {
185
            $fp_done += $wu->rsc_fpops_est;
186
            $njobs_success++;
187
            $batch->credit_canonical += $wu->canonical_credit;
188
        } else if ($wu->error_mask) {
189
            $batch->nerror_jobs++;
190
        } else {
191
            $completed = false;
192
            if (array_key_exists($wu->id, $wus_in_prog)) {
193
                $njobs_in_prog++;
194
            }
195
        }
196
    }
197
    $njobs = count($wus);
198
    $batch->njobs = $njobs;
199
    $batch->fraction_done = ($njobs_success + $batch->nerror_jobs)/$batch->njobs;
200
    if ($completed && $batch->state == BATCH_STATE_IN_PROGRESS) {
201
        $batch->state = BATCH_STATE_COMPLETE;
202
        $batch->completion_time = time();
203
    }
204
    $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");
205
206
    $batch->njobs_success = $njobs_success;
207
    $batch->njobs_in_prog = $njobs_in_prog;
208
    return $batch;
209
}
210
211
// get the physical names of a result's output files.
212
//
213
function get_outfile_phys_names($result) {
214
    $names = [];
215
    $xml = "<a>".$result->xml_doc_out."</a>";
216
    $r = simplexml_load_string($xml);
217
    if (!$r) return $names;
0 ignored issues
show
introduced by
$r is of type SimpleXMLElement, thus it always evaluated to true.
Loading history...
218
    foreach ($r->file_info as $fi) {
219
        $names[] = (string)($fi->name);
220
    }
221
    return $names;
222
}
223
224
function get_outfile_log_names($result) {
225
    $names = [];
226
    $xml = "<a>".$result->xml_doc_in."</a>";
227
    $r = simplexml_load_string($xml);
228
    if (!$r) return $names;
0 ignored issues
show
introduced by
$r is of type SimpleXMLElement, thus it always evaluated to true.
Loading history...
229
    foreach ($r->result->file_ref as $fr) {
230
        $names[] = (string)($fr->open_name);
231
    }
232
    return $names;
233
}
234
235
function get_outfile_paths($result) {
236
    $fanout = parse_config(get_config(), "<uldl_dir_fanout>");
237
    $upload_dir = parse_config(get_config(), "<upload_dir>");
238
239
    $paths = array();
240
    $xml = "<a>".$result->xml_doc_out."</a>";
241
    $r = simplexml_load_string($xml);
242
    if (!$r) return $paths;
0 ignored issues
show
introduced by
$r is of type SimpleXMLElement, thus it always evaluated to true.
Loading history...
243
    foreach ($r->file_info as $fi) {
244
        $path = dir_hier_path((string)($fi->name), $upload_dir, $fanout);
245
        $paths[] = $path;
246
    }
247
    return $paths;
248
}
249
250
function abort_workunit($wu) {
251
    BoincResult::update_aux(
252
        "server_state=5, outcome=5 where server_state=2 and workunitid=$wu->id"
253
    );
254
    $wu->update("error_mask=error_mask|16");
255
}
256
257
function abort_batch($batch) {
258
    $wus = BoincWorkunit::enum("batch=$batch->id");
259
    foreach ($wus as $wu) {
260
        abort_workunit($wu);
261
    }
262
    $batch->update("state=".BATCH_STATE_ABORTED);
263
    return 0;
264
}
265
266
// mark WUs as assimilated; this lets them be purged
267
//
268
function retire_batch($batch) {
269
    $wus = BoincWorkunit::enum("batch=$batch->id");
270
    $now = time();
271
    foreach ($wus as $wu) {
272
        $wu->update(
273
            "assimilate_state=".ASSIMILATE_DONE.", transition_time=$now"
274
        );
275
        // remove output template if it's a temporary
276
        //
277
        if (strstr($wu->result_template_file, "templates/tmp/")) {
278
            @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

278
            /** @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...
279
        }
280
    }
281
    $batch->update("state=".BATCH_STATE_RETIRED);
282
}
283
284
function expire_batch($batch) {
285
    abort_batch($batch);
286
    retire_batch($batch);
287
    $batch->update("state=".BATCH_STATE_EXPIRED);
288
}
289
290
function batch_state_string($state) {
291
    switch ($state) {
292
    case BATCH_STATE_INIT: return "new";
293
    case BATCH_STATE_IN_PROGRESS: return "in progress";
294
    case BATCH_STATE_COMPLETE: return "completed";
295
    case BATCH_STATE_ABORTED: return "aborted";
296
    case BATCH_STATE_RETIRED: return "retired";
297
    }
298
    return "unknown state $state";
299
}
300
// get the total size of output files of a batch
301
//
302
function batch_output_file_size($batchid) {
303
    $batch_td_size=0;
304
    $wus = BoincWorkunit::enum("batch=$batchid");
305
    $fanout = parse_config(get_config(), "<uldl_dir_fanout>");
306
    $upload_dir = parse_config(get_config(), "<upload_dir>");
307
    foreach ($wus as $wu) {
308
        if (!$wu->canonical_resultid) continue;
309
        $result = BoincResult::lookup_id($wu->canonical_resultid);
310
        $names = get_outfile_phys_names($result);
311
        foreach ($names as $name) {
312
            $path = dir_hier_path($name, $upload_dir, $fanout);
313
            if (is_file($path)) {
314
                $batch_td_size += filesize($path);
315
            }
316
        }
317
    }
318
    return $batch_td_size;
319
}
320
321
function boinc_get_output_file_url($user, $result, $i) {
322
    $name = $result->name;
323
    $auth_str = md5($user->authenticator.$name);
324
    return "get_output.php?cmd=result_file&result_name=$name&file_num=$i&auth_str=$auth_str";
325
}
326
327
function boinc_get_output_files_url($user, $batch_id) {
328
    $auth_str = md5($user->authenticator.$batch_id);
329
    return "get_output.php?cmd=batch_files&batch_id=$batch_id&auth_str=$auth_str";
330
}
331
332
function boinc_get_wu_output_files_url($user, $wu_id) {
333
    $auth_str =  md5($user->authenticator.$wu_id);
0 ignored issues
show
Coding Style introduced by
Expected 1 space after "="; 2 found
Loading history...
334
    return "get_output.php?cmd=workunit_files&wu_id=$wu_id&auth_str=$auth_str";
335
}
336
337
////////////////// FILE INFO FILES //////////////
338
339
// these are used:
340
// 1) in user file sandbox
341
// 2) in BUDA app variant dirs
342
// in each case a file dir/foo has an info file dir/.md5/foo
343
// containing its md5 and size
344
// (same format as .md5 files in download hierarchy)
345
346
// get the MD5 and size of a file
347
//
348
function get_file_info($path) {
349
    $md5 = md5_file($path);
350
    $s = stat($path);
351
    $size = $s['size'];
352
    return [$md5, $size];
353
}
354
355
// write a "info file" containing MD5 and size
356
//
357
function write_info_file($path, $md5, $size) {
358
    file_put_contents($path, "$md5 $size");
359
}
360
361
// parse info file and return [md5, size]
362
//
363
function parse_info_file($path) {
364
    if (!file_exists($path)) return null;
365
    $x = file_get_contents($path);
366
    $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...
367
    if ($n != 2 || strlen($md5)!=32) {
368
        return null;
369
    }
370
    return [$md5, $size];
371
}
372
373
?>
374