public function actionIndex Запускаем бесконечный цикл обработки while

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
public function actionIndex()
{
// Запускаем бесконечный цикл обработки
while(true)
{
try
{
// Выбираем задачу на бэктестинг
$ts = new TasksStorage();
$task = $ts->getBackTask('history');
if (empty($task))
{
sleep(self::WAIT_TIMEOUT);
continue;
}
$optionSymbol = explode('.', $task->symbol)[0];
$unixStart = strtotime($task->start);
$unixEnd = strtotime($task->end);
// Выбираем данные по стратегии
$strategyModel = Strategies::model()->findByPk($task->id_strategy);
if (empty($strategyModel))
throw new Exception("No strategy data. ID strategy: " . $task->id_strategy);
$builderData = CJSON::decode($strategyModel->builder_data);
if (empty($builderData))
throw new Exception("No strategy data. ID strategy: " . $task->id_strategy);
$enterPoints = [];
$classNames = [];
$entitiesCount = 0;
// Подготовка модулей стратегии
foreach ($builderData as $item)
{
$moduleObj = function($model) use ($item, $task){
if ($item['type'] == 'entities')
$fileName = Yii::app()->basePath."/commands/strategy/{$item['type']}/{$model->function_name}.php";
else
$fileName = Yii::app()->basePath."/commands/strategy/".ucfirst($item['type'])."Handler.php";
if (!file_exists($fileName))
throw new Exception("Entity's file is not found $fileName");
else
require_once $fileName;
$task->itemId = $item['id'];
if (class_exists($model->function_name))
{
$obj = new $model->function_name();
$obj->set(clone $task);
}
else
throw new Exception("Entity class '{$model->function_name}' is not exists");
if (!method_exists($obj, 'run'))
throw new Exception("Entity class does not have method 'run'");
return $obj;
};
switch($item['type'])
{
// Подготовка сущностей для стратегии
case 'entities':
$model = Entities::model()->findByPk($item['id']);
${$model->function_name} = $moduleObj($model);
if (empty($item['connections']))
$enterPoints[0][] = $item['hash'];
$entitiesCount++;
break;
// Подготовка алгоритмов
case 'algorithms':
$model = Algorithms::model()->findByPk($item['id']);
${$model->function_name} = $moduleObj($model);
break;
// Подготовка действий
case 'actions':
$model = Actions::model()->findByPk($item['id']);
${$model->function_name} = $moduleObj($model);
break;
}
$classNames[$item['hash']]['class'] = $model->function_name;
$classNames[$item['hash']]['type'] = $item['type'];
$classNames[$item['hash']]['id'] = $item['id'];
}
// Строим последовательную структуру для обработки
$counter = 1;
$hashes = $enterPoints[0];
while($counter < count($builderData))
{
foreach($builderData as $item)
{
if (isset($item['connections']) && !in_array($item['hash'], $hashes))
foreach($item['connections'] as $connection)
if (in_array($connection['sourceId'], $enterPoints[$counter-1]))
{
$enterPoints[$counter][] = $item['hash'];
$hashes[] = $item['hash'];
break;
}
}
$counter++;
}
unset($hashes);
$result = $task->symbol;
$filename = Yii::app()->basePath.'/'.$this->resultsPath.$task->symbol.'_'.date('YmdHis', $unixStart).'_'.date('YmdHis', $unixEnd).'_'.$task->id_strategy.'.txt';
foreach($enterPoints as $point)
{
if ($classNames[$point[0]]['type'] == 'algorithms')
{
Logger::write("TaskWorker(".__LINE__.")", "Run algorithm: {$classNames[$point[0]]['class']}");
$resultPart = [
'graph' => [],
'strategy' => []
];
$dataExists = 0;
$rs = new ResultsStorage($filename);
for($i = strtotime(date('Y-m-d', $unixStart) . self::DEFAULT_START_TIME); $i <= $unixEnd; $i++)
{
$tempResult = ${$classNames[$point[0]]['class']}->run($result, $i);
$resultPart['graph'] = array_unique(CMap::mergeArray($resultPart['graph'], $tempResult['graph']), SORT_REGULAR);
$resultPart['strategy'] = CMap::mergeArray($resultPart['strategy'], $tempResult['strategy']);
if (strlen(CJSON::encode($resultPart)) > self::PART_SIZE_LIMIT)
{
if (!empty($resultPart['graph']) || !empty($resultPart['strategy']))
{
$dataExists = 1;
$rs->save($filename, CJSON::encode($resultPart)."\r\n");
}
$resultPart = [
'graph' => [],
'strategy' => []
];
}
}
unset($rs);
}
else if ($classNames[$point[0]]['type'] == 'actions')
{
$rs = new ResultsStorage($filename, 'r');
$resultRead = $rs->read($filename);
Logger::write("TaskWorker(".__LINE__.")", "Run action: {$classNames[$point[0]]['class']}");
foreach($resultRead as $res)
{
$decRes = CJSON::decode($res);
if (!empty($decRes['strategy']))
${$classNames[$point[0]]['class']}->run($decRes['strategy']);
}
}
else
{
Logger::write("TaskWorker(".__LINE__.")", "Run entity: {$classNames[$point[0]]['class']}");
$result = ${$classNames[$point[0]]['class']}->run($result);
}
}
}
catch (Exception $e)
{
Logger::write("TaskWorker(".__LINE__.")", $e->getMessage());
$task->status = 'error';
$task->save();
continue;
}
// Обновляем статус задачи
$task->status = 'finished';
$task->save();
}
}