Perf dashboard should support authentication via a slave password
[WebKit-https.git] / Websites / perf.webkit.org / public / include / report-processor.php
1 <?php
2
3 require_once('../include/json-header.php');
4
5 class ReportProcessor {
6     private $db;
7     private $name_to_aggregator;
8     private $report_id;
9     private $runs;
10
11     function __construct($db) {
12         $this->db = $db;
13         $this->name_to_aggregator = array();
14         $aggregator_table = $db->fetch_table('aggregators');
15         if ($aggregator_table) {
16             foreach ($aggregator_table as $aggregator_row) {
17                 $this->name_to_aggregator[$aggregator_row['aggregator_name']] = $aggregator_row;
18             }
19         }
20     }
21
22     private function exit_with_error($message, $details = NULL) {
23         if (!$this->report_id) {
24             $details['failureStored'] = FALSE;
25             exit_with_error($message, $details);
26         }
27
28         $details['failureStored'] = $this->db->query_and_get_affected_rows(
29             'UPDATE reports SET report_failure = $1, report_failure_details = $2 WHERE report_id = $3',
30             array($message, $details ? json_encode($details) : NULL, $this->report_id)) == 1;
31         exit_with_error($message, $details);
32     }
33
34     function process($report, $existing_report_id = NULL) {
35         $this->report_id = $existing_report_id;
36         $this->runs = NULL;
37
38         array_key_exists('builderName', $report) or $this->exit_with_error('MissingBuilderName');
39         array_key_exists('buildTime', $report) or $this->exit_with_error('MissingBuildTime');
40
41         $builder_info = array('name' => $report['builderName']);
42         $slave_name = array_get($report, 'slaveName', NULL);
43         $slave_id = NULL;
44         if (!$existing_report_id) {
45             $hash = NULL;
46             if ($slave_name && array_key_exists('slavePassword', $report)) {
47                 $hash = hash('sha256', $report['slavePassword']);
48                 $slave = $this->db->select_first_row('build_slaves', 'slave', array('name' => $slave_name, 'password_hash' => $hash));
49                 if ($slave)
50                     $slave_id = $slave['slave_id'];
51             } else if (array_key_exists('builderPassword', $report))
52                 $hash = hash('sha256', $report['builderPassword']);
53
54             if (!$hash)
55                 $this->exit_with_error('BuilderNotFound');
56             if (!$slave_id)
57                 $builder_info['password_hash'] = $hash;
58         }
59
60         if (array_key_exists('builderPassword', $report))
61             unset($report['builderPassword']);
62         if (array_key_exists('slavePassword', $report))
63             unset($report['slavePassword']);
64
65         $builder_id = NULL;
66         if ($slave_id)
67             $builder_id = $this->db->select_or_insert_row('builders', 'builder', $builder_info);
68         else {
69             $builder = $this->db->select_first_row('builders', 'builder', $builder_info);
70             if (!$builder)
71                 $this->exit_with_error('BuilderNotFound', array('name' => $builder_info['name']));
72             $builder_id = $builder['builder_id'];
73             if ($slave_name)
74                 $slave_id = $this->db->select_or_insert_row('build_slaves', 'slave', array('name' => $slave_name));
75         }
76
77         $build_data = $this->construct_build_data($report, $builder_id, $slave_id);
78         if (!$existing_report_id)
79             $this->store_report($report, $build_data);
80
81         $this->runs = new TestRunsGenerator($this->db, $this->name_to_aggregator, $this->report_id);
82         $this->recursively_ensure_tests($report['tests']);
83
84         $this->runs->aggregate();
85         $this->runs->compute_caches();
86
87         $platform_id = $this->db->select_or_insert_row('platforms', 'platform', array('name' => $report['platform']));
88         if (!$platform_id)
89             $this->exit_with_error('FailedToInsertPlatform', array('name' => $report['platform']));
90
91         $build_id = $this->resolve_build_id($build_data, array_get($report, 'revisions', array()));
92
93         $this->runs->commit($platform_id, $build_id);
94     }
95
96     private function construct_build_data($report, $builder_id, $slave_id) {
97         array_key_exists('buildNumber', $report) or $this->exit_with_error('MissingBuildNumber');
98         array_key_exists('buildTime', $report) or $this->exit_with_error('MissingBuildTime');
99
100         return array('builder' => $builder_id, 'slave' => $slave_id, 'number' => $report['buildNumber'], 'time' => $report['buildTime']);
101     }
102
103     private function store_report($report, $build_data) {
104         assert(!$this->report_id);
105         $this->report_id = $this->db->insert_row('reports', 'report', array(
106             'builder' => $build_data['builder'],
107             'slave' => $build_data['slave'],
108             'build_number' => $build_data['number'],
109             'content' => json_encode($report)));
110         if (!$this->report_id)
111             $this->exit_with_error('FailedToStoreRunReport');
112     }
113
114     private function resolve_build_id($build_data, $revisions) {
115         // FIXME: This code has a race condition. See <rdar://problem/15876303>.
116         $results = $this->db->query_and_fetch_all("SELECT build_id, build_slave FROM builds
117             WHERE build_builder = $1 AND build_number = $2 AND build_time <= $3 AND build_time + interval '1 day' > $3",
118             array($build_data['builder'], $build_data['number'], $build_data['time']));
119         if ($results) {
120             $first_result = $results[0];
121             if ($first_result['build_slave'] != $build_data['slave'])
122                 $this->exit_with_error('MismatchingBuildSlave', array('storedBuild' => $results, 'reportedBuildData' => $build_data));
123             $build_id = $first_result['build_id'];
124         } else
125             $build_id = $this->db->insert_row('builds', 'build', $build_data);
126         if (!$build_id)
127             $this->exit_with_error('FailedToInsertBuild', $build_data);
128
129         foreach ($revisions as $repository_name => $revision_data) {
130             $repository_id = $this->db->select_or_insert_row('repositories', 'repository', array('name' => $repository_name));
131             if (!$repository_id)
132                 $this->exit_with_error('FailedToInsertRepository', array('name' => $repository_name));
133
134             $commit_data = array('repository' => $repository_id, 'revision' => $revision_data['revision'], 'time' => array_get($revision_data, 'timestamp'));
135
136             $mismatching_commit = $this->db->query_and_fetch_all('SELECT * FROM build_commits, commits
137                 WHERE build_commit = commit_id AND commit_build = $1 AND commit_repository = $2 AND commit_revision != $3 LIMIT 1',
138                 array($build_id, $repository_id, $revision_data['revision']));
139             if ($mismatching_commit)
140                 $this->exit_with_error('MismatchingCommitRevision', array('build' => $build_id, 'existing' => $mismatching_commit, 'new' => $commit_data));
141
142             $commit_row = $this->db->select_or_insert_row('commits', 'commit',
143                 array('repository' => $repository_id, 'revision' => $revision_data['revision']), $commit_data, '*');
144             if (!$commit_row)
145                 $this->exit_with_error('FailedToRecordCommit', $commit_data);
146             if (abs($commit_row['commit_time'] - $commit_data['time']) > 1.0)
147                 $this->exit_with_error('MismatchingCommitTime', array('existing' => $commit_row, 'new' => $commit_data));
148
149             if (!$this->db->select_or_insert_row('build_commits', null,
150                 array('commit_build' => $build_id, 'build_commit' => $commit_row['commit_id']), null, '*'))
151                 $this->exit_with_error('FailedToRelateCommitToBuild', array('commit' => $commit_row, 'build' => $build_id));
152         }
153
154         return $build_id;
155     }
156
157     private function recursively_ensure_tests($tests, $parent_id = NULL, $level = 0) {
158         foreach ($tests as $test_name => $test) {
159             $test_id = $this->db->select_or_insert_row('tests', 'test', $parent_id ? array('name' => $test_name, 'parent' => $parent_id) : array('name' => $test_name),
160                 array('name' => $test_name, 'parent' => $parent_id, 'url' => array_get($test, 'url')));
161             if (!$test_id)
162                 $this->exit_with_error('FailedToAddTest', array('name' => $test_name, 'parent' => $parent_id));
163
164             if (array_key_exists('tests', $test))
165                 $this->recursively_ensure_tests($test['tests'], $test_id, $level + 1);
166
167             foreach (array_get($test, 'metrics', array()) as $metric_name => $aggregators_or_config_types) {
168                 $aggregators = $this->aggregator_list_if_exists($aggregators_or_config_types);
169                 if ($aggregators) {
170                     foreach ($aggregators as $aggregator_name)
171                         $this->runs->add_aggregated_metric($parent_id, $test_id, $test_name, $metric_name, $aggregator_name, $level);
172                 } else {
173                     $metric_id = $this->db->select_or_insert_row('test_metrics', 'metric', array('name' => $metric_name, 'test' => $test_id));
174                     if (!$metric_id)
175                         $this->exit_with_error('FailedToAddMetric', array('name' => $metric_name, 'test' => $test_id));
176
177                     foreach ($aggregators_or_config_types as $config_type => $values) {
178                         // Some tests submit groups of iterations; e.g. [[1, 2, 3, 4], [5, 6, 7, 8]]
179                         // Convert other tests to this format to simplify the computation later.
180                         if (gettype($values) !== 'array')
181                             $values = array($values);
182                         if (gettype($values[0]) !== 'array')
183                             $values = array($values);
184                         $this->runs->add_values_to_commit($metric_id, $config_type, $values);
185                         $this->runs->add_values_for_aggregation($parent_id, $test_name, $metric_name, $config_type, $values);
186                     }
187                 }
188             }
189         }
190     }
191
192     private function aggregator_list_if_exists($aggregators_or_config_types) {
193         if (array_key_exists(0, $aggregators_or_config_types))
194             return $aggregators_or_config_types;
195         else if (array_get($aggregators_or_config_types, 'aggregators'))
196             return $aggregators_or_config_types['aggregators'];
197         return NULL;
198     }
199 };
200
201 class TestRunsGenerator {
202     private $db;
203     private $name_to_aggregator;
204     private $report_id;
205     private $metrics_to_aggregate;
206     private $parent_to_values;
207     private $values_to_commit;
208
209     function __construct($db, $name_to_aggregator, $report_id) {
210         $this->db = $db;
211         $this->name_to_aggregator = $name_to_aggregator or array();
212         $this->report_id = $report_id;
213         $this->metrics_to_aggregate = array();
214         $this->parent_to_values = array();
215         $this->values_to_commit = array();
216     }
217
218     private function exit_with_error($message, $details = NULL) {
219         $details['failureStored'] = $this->db->query_and_get_affected_rows(
220             'UPDATE reports SET report_failure = $1, report_failure_details = $2 WHERE report_id = $3',
221             array($message, $details ? json_encode($details) : NULL, $this->report_id)) == 1;
222         exit_with_error($message, $details);
223     }
224
225     function add_aggregated_metric($parent_id, $test_id, $test_name, $metric_name, $aggregator_name, $level) {
226         array_key_exists($aggregator_name, $this->name_to_aggregator) or $this->exit_with_error('AggregatorNotFound', array('name' => $aggregator_name));
227
228         $metric_id = $this->db->select_or_insert_row('test_metrics', 'metric', array('name' => $metric_name,
229             'test' => $test_id, 'aggregator' => $this->name_to_aggregator[$aggregator_name]['aggregator_id']));
230         if (!$metric_id)
231             $this->exit_with_error('FailedToAddAggregatedMetric', array('name' => $metric_name, 'test' => $test_id, 'aggregator' => $aggregator_name));
232
233         array_push($this->metrics_to_aggregate, array(
234             'test_id' => $test_id,
235             'parent_id' => $parent_id,
236             'metric_id' => $metric_id,
237             'test_name' => $test_name,
238             'metric_name' => $metric_name,
239             'aggregator' => $aggregator_name,
240             'aggregator_definition' => $this->name_to_aggregator[$aggregator_name]['aggregator_definition'],
241             'level' => $level));
242     }
243
244     function add_values_for_aggregation($parent_id, $test_name, $metric_name, $config_type, $values, $aggregator = NULL) {
245         $value_list = &array_ensure_item_has_array(array_ensure_item_has_array(array_ensure_item_has_array(array_ensure_item_has_array(
246             $this->parent_to_values, strval($parent_id)), $metric_name), $config_type), $test_name);
247         array_push($value_list, array('aggregator' => $aggregator, 'values' => $values));
248     }
249
250     function aggregate() {
251         $expressions = array();
252         foreach ($this->metrics_to_aggregate as $test_metric) {
253             $configurations = array_get(array_get($this->parent_to_values, strval($test_metric['test_id']), array()), $test_metric['metric_name']);
254             foreach ($configurations as $config_type => $test_value_list) {
255                 // FIXME: We should preserve the test order. For that, we need a new column in our database.
256                 $values_by_iteration = $this->test_value_list_to_values_by_iterations($test_value_list, $test_metric, $test_metric['aggregator']);
257                 $flattened_aggregated_values = array();
258                 for ($i = 0; $i < count($values_by_iteration['values']); ++$i)
259                     array_push($flattened_aggregated_values, $this->aggregate_values($test_metric['aggregator'], $values_by_iteration['values'][$i]));
260
261                 $grouped_values = array();
262                 foreach ($values_by_iteration['group_sizes'] as $size) {
263                     $new_group = array();
264                     for ($i = 0; $i < $size; ++$i)
265                         array_push($new_group, array_shift($flattened_aggregated_values));
266                     array_push($grouped_values, $new_group);
267                 }
268
269                 $this->add_values_to_commit($test_metric['metric_id'], $config_type, $grouped_values);
270                 $this->add_values_for_aggregation($test_metric['parent_id'], $test_metric['test_name'], $test_metric['metric_name'],
271                     $config_type, $grouped_values, $test_metric['aggregator']);
272             }
273         }
274     }
275
276     private function test_value_list_to_values_by_iterations($test_value_list, $test_metric, $aggregator) {
277         $values_by_iterations = array();
278         $group_sizes = array();
279         $first_test = TRUE;
280         foreach ($test_value_list as $test_name => $aggregators_and_values) {
281             if (count($aggregators_and_values) == 1) // Either the subtest has exactly one aggregator or is raw value (not aggregated)
282                 $values = $aggregators_and_values[0]['values'];
283             else {
284                 $values = NULL;
285                 // Find the values of the subtest aggregated by the same aggregator.
286                 foreach ($aggregators_and_values as $aggregator_and_values) {
287                     if ($aggregator_and_values['aggregator'] == $aggregator) {
288                         $values = $aggregator_and_values['values'];
289                         break;                        
290                     }
291                 }
292                 if (!$values) {
293                     $this->exit_with_error('NoMatchingAggregatedValueInSubtest',
294                         array('parent' => $test_metric['test_id'],
295                         'metric' => $test_metric['metric_name'],
296                         'childTest' => $test_name,
297                         'aggregator' => $aggregator,
298                         'aggregatorAndValues' => $aggregators_and_values));
299                 }
300             }
301
302             for ($group = 0; $group < count($values); ++$group) {
303                 if ($first_test) {
304                     array_push($group_sizes, count($values[$group]));
305                     for ($i = 0; $i < count($values[$group]); ++$i)
306                         array_push($values_by_iterations, array());
307                 }
308
309                 if ($group_sizes[$group] != count($values[$group])) {
310                     $this->exit_with_error('IterationGroupSizeIsInconsistent',
311                         array('parent' => $test_metric['test_id'],
312                         'metric' => $test_metric['metric_name'],
313                         'childTest' => $test_name,
314                         'groupSizes' => $group_sizes,
315                         'group' => $group,
316                         'values' => $values));
317                 }
318             }
319             $first_test = FALSE;
320
321             if (count($values) != count($group_sizes)) {
322                 // FIXME: We should support bootstrapping or just computing the mean in this case.
323                 $this->exit_with_error('IterationGroupCountIsInconsistent', array('parent' => $test_metric['test_id'],
324                     'metric' => $test_metric['metric_name'], 'childTest' => $name_and_values['name'],
325                     'valuesByIterations' => $values_by_iterations, 'values' => $values));
326             }
327
328             $flattened_iteration_index = 0;
329             for ($group = 0; $group < count($values); ++$group) {
330                 for ($i = 0; $i < count($values[$group]); ++$i) {
331                     $run_iteration_value = $values[$group][$i];
332                     if (!is_numeric($run_iteration_value)) {
333                         $this->exit_with_error('NonNumeralIterationValueForAggregation', array('parent' => $test_metric['test_id'],
334                             'metric' => $test_metric['metric_name'], 'childTest' => $name_and_values['name'],
335                             'valuesByIterations' => $values_by_iterations, 'values' => $values, 'index' => $i));
336                     }
337                     array_push($values_by_iterations[$flattened_iteration_index], $run_iteration_value);
338                     $flattened_iteration_index++;
339                 }
340             }
341         }
342
343         if (!$values_by_iterations)
344             $this->exit_with_error('NoIterationToAggregation', array('parent' => $test_metric['test_id'], 'metric' => $test_metric['metric_name']));
345
346         return array('values' => $values_by_iterations, 'group_sizes' => $group_sizes);
347     }
348
349     private function aggregate_values($aggregator, $values) {
350         switch ($aggregator) {
351         case 'Arithmetic':
352             return array_sum($values) / count($values);
353         case 'Geometric':
354             return pow(array_product($values), 1 / count($values));
355         case 'Harmonic':
356             return count($values) / array_sum(array_map(function ($x) { return 1 / $x; }, $values));
357         case 'Total':
358             return array_sum($values);
359         case 'SquareSum':
360             return array_sum(array_map(function ($x) { return $x * $x; }, $values));
361         default:
362             $this->exit_with_error('UnknownAggregator', array('aggregator' => $aggregator));
363         }
364         return NULL;
365     }
366
367     function compute_caches() {
368         $expressions = array();
369         $size = count($this->values_to_commit);
370         for ($i = 0; $i < $size; ++$i) {
371             $flattened_value = array();
372             foreach ($this->values_to_commit[$i]['values'] as $group) {
373                 for ($j = 0; $j < count($group); ++$j) {
374                     $iteration_value = $group[$j];
375                     if (gettype($iteration_value) === 'array') { // [relative time, value]
376                         if (count($iteration_value) != 2) {
377                             // FIXME: Also report test and metric.
378                             $this->exit_with_error('InvalidIterationValueFormat', array('values' => $this->values_to_commit[$i]['values']));
379                         }
380                         $iteration_value = $iteration_value[1];
381                     }
382                     array_push($flattened_value, $iteration_value);                    
383                 }
384             }
385             $this->values_to_commit[$i]['mean'] = $this->aggregate_values('Arithmetic', $flattened_value);
386             $this->values_to_commit[$i]['sum'] = $this->aggregate_values('Total', $flattened_value);
387             $this->values_to_commit[$i]['square_sum'] = $this->aggregate_values('SquareSum', $flattened_value);
388         }
389     }
390
391     function add_values_to_commit($metric_id, $config_type, $values) {
392         array_push($this->values_to_commit, array('metric_id' => $metric_id, 'config_type' => $config_type, 'values' => $values));
393     }
394
395     function commit($platform_id, $build_id) {
396         $this->db->begin_transaction() or $this->exit_with_error('FailedToBeginTransaction');
397
398         foreach ($this->values_to_commit as $item) {
399             $config_data = array('metric' => $item['metric_id'], 'type' => $item['config_type'], 'platform' => $platform_id);
400             $config_id = $this->db->select_or_insert_row('test_configurations', 'config', $config_data);
401             if (!$config_id)
402                 $this->rollback_with_error('FailedToObtainConfiguration', $config_data);
403
404             $values = $item['values'];
405             $total_count = 0;
406             for ($group = 0; $group < count($values); ++$group)
407                 $total_count += count($values[$group]);
408             $run_data = array('config' => $config_id, 'build' => $build_id, 'iteration_count_cache' => $total_count,
409                 'mean_cache' => $item['mean'], 'sum_cache' => $item['sum'], 'square_sum_cache' => $item['square_sum']);
410             $run_id = $this->db->insert_row('test_runs', 'run', $run_data);
411             if (!$run_id)
412                 $this->rollback_with_error('FailedToInsertRun', array('metric' => $item['metric_id'], 'param' => $run_data));
413
414             $flattened_order = 0;
415             for ($group = 0; $group < count($values); ++$group) {
416                 for ($i = 0; $i < count($values[$group]); ++$i) {
417                     $iteration_value = $values[$group][$i];
418                     $relative_time = NULL;
419                     if (gettype($iteration_value) === 'array') {
420                         assert(count($iteration_value) == 2); // compute_caches checks this condition.
421                         $relative_time = $iteration_value[0];
422                         $iteration_value = $iteration_value[1];
423                     }
424                     $param = array('run' => $run_id, 'order' => $flattened_order, 'value' => $iteration_value,
425                         'group' => count($values) == 1 ? NULL : $group, 'relative_time' => $relative_time);
426                     $this->db->insert_row('run_iterations', 'iteration', $param, NULL)
427                         or $this->rollback_with_error('FailedToInsertIteration', array('config' => $config_id, 'build' => $build_id, 'param' => $param));
428                     $flattened_order++;
429                 }
430             }
431         }
432
433         $this->db->query_and_get_affected_rows("UPDATE reports SET report_committed_at = CURRENT_TIMESTAMP AT TIME ZONE 'UTC'
434             WHERE report_id = $1", array($this->report_id));
435
436         $this->db->commit_transaction() or $this->exit_with_error('FailedToCommitTransaction');
437     }
438
439     private function rollback_with_error($message, $details) {
440         $this->db->rollback_transaction();
441         $this->exit_with_error($message, $details);
442     }
443 };
444
445 ?>