Skip to content
Snippets Groups Projects
Backend.php 109 KiB
Newer Older
root's avatar
root committed
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
                              (int)($series->r === null);

            if ($invalid_sphere != 0 && $invalid_sphere != 4) {
                throw new BadRequestException("Invalid sphere parameters");
            } else if($invalid_sphere == 0) {
                $parameters = array_merge($parameters, array(':x'    => $series->x,
                                                             ':y'    => $series->y,
                                                             ':z'    => $series->z,
                                                             ':r'    => $series->r));
                $query .= ' AND SQRT(POW(x - :x, 2) + POW(y - :y, 2) + POW(z - :z, 2)) <= :r + r';
                $filter_sphere = true;
            } else {
                $filter_sphere = false;
            }

            $query .= ' AND domain = :domain AND count > 0;';

            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME,
                                        Config::config()::MYSQL_PORT,
                                        Config::config()::MYSQL_DBNAME,
                                        Config::config()::MYSQL_USERNAME,
                                        Config::config()::MYSQL_PASSWORD);

            $select_stmt = $conn->prepare($query);
            $select_stmt->execute($parameters);

            $id_set = \Cassandra\Type::collection(\Cassandra\Type::bigint())->create();

            $selected_slices = array_column($select_stmt->fetchAll(), 'unit', 'slice');

            foreach ($selected_slices as $slice => $unit)
                $id_set->add(new \Cassandra\Bigint($slice));

            $session = self::_cassandraConnect(Config::config()::CASSANDRA_SERVERNAME, Config::config()::CASSANDRA_PORT, $this->_username, $this->_password, Config::config()::CASSANDRA_KEYSPACE);

            $is_digital  = $series->unit()->is_digital();

            $cassandra_table = "{$this->_domain}" . (($is_digital) ? '_dig' : '');

            $cass_select_stmt = $session->prepare("SELECT * FROM {$cassandra_table} WHERE (id IN ?) AND (timestamp >= ?) AND (timestamp <= ?);");

            $result_page = $session->execute($cass_select_stmt,
                            array('arguments' => array($id_set, new \Cassandra\Varint($series->t0), new \Cassandra\Varint($series->t1))));

            //ini_set('memory_limit', '-1'); // check this
            //ini_set('max_execution_time', 300); // check this

            $index = 0;
            $response_json = array('series' => array());

            $aggregator = ($this->internal()) ? null : Aggregator::new($aggr);

            while($result_page) {
                foreach ($result_page as $column) {
                    $slice = (int)$column['id'];
                    $entry = $column['entry'];
                    $time  = (string)$column['timestamp']->value(); //bigint
                    if($is_digital){
                        $value_blob = $entry->get('value')->toBinaryString();
                        if(isset($_GET['type'])){
                            $value = Unpack::uInt64($value_blob);// blob
                        }else{
                            $value = Unpack::d64($value_blob);// blob
                        }
                        if($value === null)
                            $value = $value_blob; // TODO: remove this in the new API
                    } else {
                        $value = (double)$entry->get('value'); // double
                    }

                    $error = (int)$entry->get('error');             //tinyint
                    $conf  = (int)$entry->get('confidence');        //tinyint
                    $x     = (int)$entry->get('x');                 //int
                    $y     = (int)$entry->get('y');                 //int
                    $z     = (int)$entry->get('z');                 //int
                    $d     = (int)$entry->get('d');                 //int
                    $gw    = (int)$entry->get('gw');                //int (TO DO GET GATEWAY)

                    if ( $filter_sphere && !$series->contains_point($x, $y, $z) )
                        continue;

                    $smartdata = null;

                    switch ($series->version) {
                        case SmartData::STATIC_VERSION:
                            $smartdata = new StaticSmartData($series->unit,$value,$error,$conf,$x,$y,$z,$time,$d,$gw);
                            break;
                        case SmartData::MOBILE_VERSION:
                            $smartdata = new MobileSmartData($series->unit,$value,$error,$conf,$x,$y,$z,$time,$d,$gw, null);
                            break;
                        default:
                            continue 2;
                            break;
                    }

                    if($aggregator != null) {
                        $smartdata = $aggregator->aggregate($smartdata);
                    }

                    if($smartdata != null) {
                        if(is_array($smartdata)){
                            foreach ($smartdata as $key => $data) {
                                $response_json['series'][$index++] = $data->toArray();
                                if ($index >= Config::config()::POINTS_LIMIT) break;
                            }
                        } else {
                            $response_json['series'][$index++] = $smartdata->toArray();
                            if($this->internal()){
                                $response_json['series'][$index-1]['slice'] = $slice;
                                $response_json['series'][$index-1]['gw'] = $gw;
                            }
                        }
                    } else {
                        continue;
                    }

                    if ($index >= Config::config()::POINTS_LIMIT) break 2;
                }

                $result_page = $result_page->nextPage();

                if(!$result_page && isset($aggregator) && $index < Config::config()::POINTS_LIMIT){
                    $smartdata = $aggregator->finish();
                    if($smartdata != null) {
                        $response_json['series'][$index++] = $smartdata->toArray();
                    }
                }
            }

            $session->close();

            usort($response_json['series'], function ($a, $b) {
                $a_timestamp  = gmp_init($a['timestamp']);
                $b_timestamp  = gmp_init($b['timestamp']);
                return gmp_cmp($a_timestamp, $b_timestamp);
            });

        } catch (\Exception $e) {
            Logger::exception($e);
            $response_json = NULL;
        } finally {
            if (isset($session))
                $session->close();
            $conn = null;
        }

        return $response_json;
    }

    public function insertBatch(Series $series, SmartData ...$smart_data) {
        if ($smart_data[0] instanceof StaticSmartData)
            return $this->_insertStaticSmartDataBatch($series, ...$smart_data);
        else
            throw new BadRequestException("Error processing JSON request: unsupported SmartData version");
    }

    // Insert a static version of smartdata
    private function _insertStaticSmartDataBatch(Series $series, StaticSmartData ...$smart_data) : bool {
        $sucess = true;

        $smart_data_count = count($smart_data);

        $parameters = array(':version'  => $series->version,
                            ':unit'     => $series->unit,
                            ':x'        => $series->x,
                            ':y'        => $series->y,
                            ':z'        => $series->z,
                            ':r'        => $series->r,
                            ':t0'       => $series->t0,
                            ':t1'       => $series->t1,
                            ':domain'   => $this->_domain);

        try {

            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME,
                                        Config::config()::MYSQL_PORT,
                                        Config::config()::MYSQL_DBNAME,
                                        Config::config()::MYSQL_USERNAME,
                                        Config::config()::MYSQL_PASSWORD);

            $table = Config::config()::MySQL_Table($series->version);

            $series_db = NULL;

            $stmt_select = $conn->prepare("SELECT * FROM {$table} WHERE version = :version
                                                    AND unit = :unit AND x = :x AND y = :y AND z = :z AND r = :r
                                                    AND t0 = :t0 AND t1 = :t1 AND domain = :domain
                                                    ORDER BY id DESC LIMIT 1;");

            $stmt_select->execute($parameters);
            $series_db = $stmt_select->fetch(\PDO::FETCH_OBJ);

            if ($series_db == NULL){// || (($series_db->count + $smart_data_count) >= Config\CASSANDRA_MAX_ROW_SIZE) ) {
                throw new Exception\NoMatchingSeriesException('No matching series');
            }else{
                //Logger::debug("Inserting a Batch of StaticSmartData");

                $is_digital = $series->unit()->is_digital();

                $entry_type = \Cassandra\Type::userType(
                    'value',      ($is_digital) ? \Cassandra\Type::blob() : \Cassandra\Type::double(),
                    'error',      \Cassandra\Type::tinyint(),
                    'confidence', \Cassandra\Type::tinyint(),
                    'x',          \Cassandra\Type::int(),
                    'y',          \Cassandra\Type::int(),
                    'z',          \Cassandra\Type::int(),
                    'd',          \Cassandra\Type::bigint(),
                    'gw',         \Cassandra\Type::bigint()
                );

                $cassandra_table = "{$this->_domain}" . (($is_digital) ? '_dig' : '');

                /* change this */
                // TODO: get this values from the smartdata object
                $slice      = new \Cassandra\Bigint($series_db->slice);
                $error      = new \Cassandra\Tinyint(0);
                $confidence = new \Cassandra\Tinyint(0);
                $gw         = new \Cassandra\Bigint(-1);
                /* change this */


                $session = self::_cassandraConnect(Config::config()::CASSANDRA_SERVERNAME, Config::config()::CASSANDRA_PORT, $this->_username, $this->_password, Config::config()::CASSANDRA_KEYSPACE);
                $insert_stmt = $session->prepare("INSERT INTO {$cassandra_table} (id, timestamp, entry) VALUES (?, ?, ?);");

                $batch = new \Cassandra\BatchStatement(\Cassandra::BATCH_LOGGED);

                $count = 0;
                foreach ($smart_data as $key => $data) {
                    $batch->add($insert_stmt, array($slice,
                                                    new \Cassandra\Varint($data->time),
                                                    $entry_type->create(
                                                        'value',      ($is_digital) ? new \Cassandra\Blob($data->value) : (double) $data->value,
                                                        'error',      $error,
                                                        'confidence', $confidence,
                                                        'x',          (int)$data->x,
                                                        'y',          (int)$data->y,
                                                        'z',          (int)$data->z,
                                                        'd',          new \Cassandra\Bigint($data->dev),
                                                        'gw',         $gw
                                                    )));
                    $count++;

                    if($count == 400){
                        //echo "       Inserted\n";
                        $session->execute($batch);
                        $count = 0;
                        $batch = new \Cassandra\BatchStatement(\Cassandra::BATCH_LOGGED);
                    }
                }

                if($count > 0){
                    $session->execute($batch);
                    $count = 0;
                }

                $update_stmt = $conn->prepare("UPDATE {$table} SET count = count + :smart_data_count WHERE id = :id LIMIT 1;");
                $update_stmt->execute(array('id' => $series_db->id, 'smart_data_count' => $smart_data_count));
            }

        } catch (\Exception $e) {
            Logger::exception($e);
            $sucess = false;
        } finally {
            if (isset($session))
                $session->close();
            $conn = null;
        }

        return $sucess;
    }

    private function _insertMobileSmartDataBatch(Series $series, MobileSmartData ...$smart_data) : bool {
        throw new Exception\NotImplementedException("Batch insertion has not been implemented yet");
    }

    public function assignConfidence($t0, $t1, $max_time_diff, $query_filename="nn_input.csv", $confidence_filename="nn_output.csv", $train=false, $get=false) : bool {
        return true;
    }

    public function assign_confidence($smart_data) {
        $pushd = 'pushd '.Config::config()::CONFIDENCE_ASSIGNER;
        $popd  = 'popd';
        $json = $smart_data->toJson();
        //$return = shell_exec("{$pushd}; ./assign '{$json}'; {$popd};");
        preg_match('#\{(.*?)\}#', $return??'', $match);
        $confidence = $match[1] ?? $smart_data->confidence;

        //Logger::debug('assigned confidence: '.$confidence);
        return $smart_data->confidence = $confidence;
    }
}

## Backend of API version 1.1 ##############################################################################
class Backend_V1_1 extends Backend_Common
{
    public function create($to_be_created) {
        switch($to_be_created->version) {
        case SmartData::STATIC_VERSION:
            self::debug_X("Creating Series : {$to_be_created}");
            return $this->_createSeries($to_be_created);
        case SmartData::MOBILE_VERSION:
            self::debug_X("Creating Tracker : {$to_be_created}");
            return $this->_createTracker($to_be_created);
        default:
            throw new BadRequestException("Error processing request: unsupported Series/Tracker version [{$to_be_attached->version}]");
        }
    }

    public function attach($to_be_attached) {
        switch($to_be_attached->version) {
        case SmartData::STATIC_VERSION:
            self::debug_X("Attaching Series : {$to_be_attached}");
            return $this->_attachSeries($to_be_attached);
        case SmartData::MOBILE_VERSION:
            self::debug_X("Attaching Tracker : {$to_be_attached}");
            return $this->_attachTracker($to_be_attached);
        default:
            throw new BadRequestException("Error processing request: unsupported Series/Tracker version [{$to_be_attached->version}]");
            return null;
        }
    }

    // Insert SmartData into series/tracker matched
    public function insert(SmartData $smart_data) {
        if ($smart_data instanceof StaticSmartData) {
            self::debug_X("Inserting a Static SmartData : {$smart_data}");
            return $this->_insertStaticSmartData($smart_data);
        } else if ($smart_data instanceof MobileSmartData){
            self::debug_X("Inserting a Mobile SmartData : {$smart_data}");
            return $this->_insertMobileSmartData($smart_data);
        } else
            throw new BadRequestException("Error processing request: unsupported SmartData version");
    }

    public function insertBatch(...$batch) {
        if ($batch[0] instanceof Series){
            self::debug_X('Batching Series : ['.count($batch).']');
            return $this->_insertStaticSmartDataBatch(...$batch);
        } else if ($batch[0] instanceof Tracker){
            self::debug_X('Batching Tracker : ['.count($batch).']');
            throw new Exception\NotImplementedException("Batching Tracker has not been implemented yet");
            //return $this->_insertMobileSmartDataBatch(...$batch);
        } else
            throw new BadRequestException("Error processing request: unsupported data version");
    }

    // Create a new series if not exist
    private function _createSeries(Series $series) : bool {
        $sucess = true;
        $parameters = array(':version'  => $series->version,
                            ':unit'     => $series->unit,
                            ':x'        => $series->x,
                            ':y'        => $series->y,
                            ':z'        => $series->z,
                            ':r'        => $series->r,
                            //':dev'      => $series->dev, // TODO: The series doesn't has a dev
                            ':t0'       => $series->t0,
                            ':t1'       => $series->t1,
                            ':workflow' => $series->workflow ?? 0,
                            ':domain'   => $this->_domain);
        try {
            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME, Config::config()::MYSQL_PORT, Config::config()::MYSQL_DBNAME, Config::config()::MYSQL_USERNAME, Config::config()::MYSQL_PASSWORD);
            $table = Config::config()::MySQL_Table($series->version);
            $stmt_select = $conn->prepare("SELECT * FROM {$table} WHERE 
                version = :version
            AND unit = :unit 
            AND (SQRT(POW(x - :x, 2) + POW(y - :y, 2) + POW(z - :z, 2))) <= (r + :r) 
            AND ((:t0 >= t0 AND :t0 <= t1) OR (:t0 <= t0 AND :t1 >= t1) OR (:t1 >= t0 AND :t1 <= t1 ))
            AND workflow = :workflow 
            AND domain = :domain;");
root's avatar
root committed

            $stmt_select->execute($parameters);
            $series_set = $stmt_select->fetch(\PDO::FETCH_OBJ);
root's avatar
root committed

            if ($series_set == NULL) {
root's avatar
root committed
                self::debug_X('The Series did not exist before');
                $stmt_insert = $conn->prepare("INSERT INTO {$table} VALUES (DEFAULT, :version, :unit, :x, :y, :z, :r, DEFAULT, :t0, :t1, :workflow, :domain, DEFAULT);");
                $stmt_insert->execute($parameters);
            } else {
                $rows_table = '`rows`';
                foreach ($series_set as $series_aux) {
                    $dist = SQRT(POW($series_aux->x - $series->x, 2) + POW($series_aux->y - $series->y, 2) + POW($series_aux->z - $series->z, 2));
                    $t0 = ($series_aux->t0 <= $series->t0) ? $series_aux->t0 : $series->t0;
                    $t1 = ($series_aux->t1 >= $series->t1) ? $series_aux->t0 : $series->t1;
                    if ($series_aux->r >= ($dist + $series->r)) {
                        //new series is spatially contained by the already inserted one
                        $x = $series_aux->x;
                        $y = $series_aux->y;
                        $z = $series_aux->z;
                        $r = $series_aux->r;
                    } else if ($series->r >= ($dist + $series_aux->r)) {
                        //already inserted series is spatially contained by the new one
                        $x = $series->x;
                        $y = $series->y;
                        $z = $series->z;
                        $r = $series->r;
                    } else {
                        $r = ($series->r + $dist + $series_aux->r)
                        $x = ($series_aux->x + ($series_aux->x - $series->x) * ($r - $series_aux->r)) / $dist;
                        $y = ($series_aux->y + ($series_aux->y - $series->y) * ($r - $series_aux->r)) / $dist;
                        $z = ($series_aux->z + ($series_aux->z - $series->z) * ($r - $series_aux->r)) / $dist;
                        //http://answers.google.com/answers/threadview/id/342125.html
                    }
                    $parameters = array(':x'        => $x,
                        ':y'        => $y,
                        ':z'        => $z,
                        ':r'        => $r,
                        ':t0'       => $t0,
                        ':t1'       => $t1);
                    if (isset($series->id)) {
                        $update_stmt = $conn->prepare("UPDATE {$table} SET x = :x, z = :z, r = :r, t0 = :t0, t1 = :t1 WHERE id = {$series->id};");
                        $update_stmt->execute($parameters);
                        $update_stmt = $conn->prepare("UPDATE {$rows_table} SET series_id = {$series->id} WHERE series_id = {$series_aux->id};");
                        $update_stmt->execute();
                        $update_stmt = $conn->prepare("DELETE FROM {$table} WHERE id = {$series_aux->id};");
                        $update_stmt->execute();
                    } else {
                        $update_stmt = $conn->prepare("UPDATE {$table} SET x = :x, z = :z, r = :r, t0 = :t0, t1 = :t1 WHERE id = {$series_aux->id};");
                        $update_stmt->execute($parameters);
                        $series->id = $series_aux->id;
                    }
                    $series->x = $x;
                    $series->y = $y;
                    $series->z = $z;
                    $series->r = $r;
                    $series->t0 = $t0;
                    $series->t1 = $t1;
                }
root's avatar
root committed
                //self::debug_X($series);
            }

        } catch (\Exception $e) {
            Logger::exception($e);
            $sucess = false;
        } finally {
            $conn = null;
        }

        return $sucess;
    }

    // Create a new tracker if not exist
    private function _createTracker(Series $tracker) : bool {
        $sucess = true;

        $parameters = array(':version'   => $tracker->version,
                            ':unit'      => $tracker->unit,
                            ':signature' => 0, // TODO: include signature
                            ':t0'        => $tracker->t0,
                            ':t1'        => $tracker->t1,
                            ':dev'       => $tracker->dev,
                            ':workflow'  => $tracker->workflow ?? 0,
                            ':domain'    => $this->_domain);

        try {
            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME, Config::config()::MYSQL_PORT, Config::config()::MYSQL_DBNAME, Config::config()::MYSQL_USERNAME, Config::config()::MYSQL_PASSWORD);
            $table = Config::config()::MySQL_Table($tracker->version);
            $stmt_select = $conn->prepare("SELECT * FROM {$table} WHERE
                      version = :version
                  AND unit = :unit
                  AND dev = :dev
                  AND t0 = :t0
                  AND t1 = :t1
                  AND signature = :signature
                  AND workflow = :workflow
                  AND domain = :domain
                ORDER BY count ASC LIMIT 1;");

            $stmt_select->execute($parameters);
            $selected_tracker = $stmt_select->fetch(\PDO::FETCH_OBJ);

            if ($selected_tracker == NULL) {
                self::debug_X('The Tracker did not exist before');
                $stmt_insert = $conn->prepare("INSERT INTO {$table} VALUES (DEFAULT, :version, :unit, :dev, :t0, :t1, :signature, DEFAULT, :workflow, :domain, (SELECT counter(:domain)), DEFAULT);");
                $stmt_insert->execute($parameters);
            } else {
                //self::debug_X($selected_tracker);
            }

        } catch (\Exception $e) {
            Logger::exception($e);
            $sucess = false;
        } finally {
            $conn = null;
        }

        return $sucess;
    }

    // Create a new series if there is not one that contains it
    private function _attachSeries(Series $series) : bool {
        $sucess = true;

        $parameters = array(':version'  => $series->version,
                            ':unit'     => $series->unit,
                            ':x'        => $series->x,
                            ':y'        => $series->y,
                            ':z'        => $series->z,
                            ':r'        => $series->r,
                            //':dev'      => $series->dev, // TODO: The series doesn't has a dev
                            ':t0'       => $series->t0,
                            ':t1'       => $series->t1,
                            ':workflow' => $series->workflow ?? 0,
                            ':domain'   => $this->_domain);

        try {

            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME, Config::config()::MYSQL_PORT, Config::config()::MYSQL_DBNAME, Config::config()::MYSQL_USERNAME, Config::config()::MYSQL_PASSWORD);
            $table = Config::config()::MySQL_Table($series->version);
            $stmt_select = $conn->prepare("SELECT * FROM {$table} WHERE version = :version
                  AND unit = :unit
                  AND r >= (SQRT(POW(x - :x, 2) + POW(y - :y, 2) + POW(z - :z, 2)) + :r)
                  AND t0 <= :t0 AND t1 >= :t1
                  AND workflow = :workflow
                  AND domain = :domain
                ORDER BY r ASC LIMIT 1;");

            $stmt_select->execute($parameters);
            $series = $stmt_select->fetch(\PDO::FETCH_OBJ);

            if ($series == NULL) {
                self::debug_X('The Series did not exist before');
                $stmt_insert = $conn->prepare("INSERT INTO {$table} VALUES (DEFAULT, :version, :unit, :x, :y, :z, :r, DEFAULT, :t0, :t1, :workflow, :domain, DEFAULT);");
                $stmt_insert->execute($parameters);
            } else {
                //self::debug_X($series);
            }
        } catch (\Exception $e) {
            Logger::exception($e);
            $sucess = false;
        } finally {
            $conn = null;
        }

        return $sucess;
    }

    // Create a new series if there is not one that contains it
    private function _attachTracker(Series $tracker) : bool {
        $sucess = true;

        $parameters = array(':version'   => $tracker->version,
                            ':unit'      => $tracker->unit,
                            ':signature' => 0, // TODO: include signature
                            ':t0'        => $tracker->t0,
                            ':t1'        => $tracker->t1,
                            ':dev'       => $tracker->dev,
                            ':workflow'  => $tracker->workflow ?? 0,
                            ':domain'    => $this->_domain);

        try {

            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME, Config::config()::MYSQL_PORT, Config::config()::MYSQL_DBNAME, Config::config()::MYSQL_USERNAME, Config::config()::MYSQL_PASSWORD);
            $table = Config::config()::MySQL_Table($tracker->version);
            $stmt_select = $conn->prepare("SELECT * FROM {$table} WHERE
                      version = :version
                  AND unit = :unit
                  AND dev = :dev
                  AND t0 <= :t0 AND t1 >= :t1
                  AND signature = :signature
                  AND workflow = :workflow
                  AND domain = :domain
                ORDER BY count ASC LIMIT 1;");

            $stmt_select->execute($parameters);
            $selected_tracker = $stmt_select->fetch(\PDO::FETCH_OBJ);

            if ($selected_tracker == NULL) {
                self::debug_X('The Tracker did not exist before');
                $stmt_insert = $conn->prepare("INSERT INTO {$table} VALUES (DEFAULT, :version, :unit, :dev, :t0, :t1, :signature, DEFAULT, :workflow, :domain, (SELECT counter(:domain)), DEFAULT);");
                $stmt_insert->execute($parameters);
            } else {
                //self::debug_X($selected_tracker);
            }

        } catch (\Exception $e) {
            Logger::exception($e);
            $sucess = false;
        } finally {
            $conn = null;
        }

        return $sucess;
    }

    // Insert a static version of smartdata
    private function _insertStaticSmartData(StaticSmartData $smart_data) : bool {
        $sucess = true;

        $parameters = array(':unit'       => $smart_data->unit,
                            ':x'          => $smart_data->x,
                            ':y'          => $smart_data->y,
                            ':z'          => $smart_data->z,
                            //':dev'        => $smart_data->dev, // TODO: The series doesn't has a dev
                            ':time'       => $smart_data->time,
                            ':domain'     => $this->_domain);

        $is_digital = $smart_data->unit()->is_digital();

        try {
	    Logger::time_elapsed(true);
            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME, Config::config()::MYSQL_PORT, Config::config()::MYSQL_DBNAME, Config::config()::MYSQL_USERNAME, Config::config()::MYSQL_PASSWORD);
            $table = Config::config()::MySQL_Table($smart_data->version);
            $stmt_select = $conn->prepare("SELECT * FROM {$table} WHERE unit = :unit AND (SQRT(POW(x - :x, 2) + POW(y - :y, 2) + POW(z - :z, 2))) <= r AND :time >= t0 AND :time <= t1 AND domain = :domain;");

            $stmt_select->execute($parameters);
            $series_set = $stmt_select->fetchAll(\PDO::FETCH_OBJ);
	    Logger::time_elapsed();
            if ($series_set == NULL) {
                throw new Exception\NoMatchingSeriesException('No matching series');
            } else {
                // the series exists
                $rows_table = '`rows`'; // TODO: move to Config file (row table name)

                $count_limit = Config::config()::CASSANDRA_MAX_ROW_SIZE;
                foreach ($series_set as $series) {
                    $series->row = NULL;
                    $first = true;

                    do {
                        $stmt_select_row = $conn->prepare("SELECT * FROM {$rows_table} WHERE series_id in (:series_id) AND x = :x AND y = :y AND z = :z AND dev = :dev AND count < {$count_limit} LIMIT 1;");

                        $parameters_row = array(':series_id'  => $series->id,
                                                ':x'          => $smart_data->x,
                                                ':y'          => $smart_data->y,
                                                ':z'          => $smart_data->z,
                                                ':dev'        => $smart_data->dev);

                        $stmt_select_row->execute($parameters_row);
                        $series->row = $stmt_select_row->fetch(\PDO::FETCH_OBJ);
                        if ($first && $series->row==NULL) {
                            self::debug_X('There were no rows before');
                            $stmt_insert_row = $conn->prepare("INSERT INTO {$rows_table} VALUES (DEFAULT, :x, :y, :z, :dev, DEFAULT, (SELECT counter(:domain)), :series_id, DEFAULT);");
                            $stmt_insert_row->execute(array_merge($parameters_row, array(':domain' => $this->_domain)));
                            $first = false;
                        } else {
                            break;
                        }
                    } while (true);
                }
            }
	    Logger::time_elapsed();
            $entry_type = \Cassandra\Type::userType(
                'value',      ($is_digital) ? \Cassandra\Type::blob() : \Cassandra\Type::double(),
                'error',      \Cassandra\Type::tinyint(),
                'confidence', \Cassandra\Type::tinyint(),
                'gw',         \Cassandra\Type::bigint()
            );

            foreach ($series_set as $series) {
                self::debug_X('Inserting StaticSmartData on series ['.$series->id.'] row ['.$series->row->row_id.']');
                $_smart_data = null;
                if($series->workflow ?? false){
                    self::debug_X('Enter workflow');
		    $_smart_data = clone $smart_data;
                    $_smart_data = $this->_workflow_input($_smart_data, $series->workflow);
root's avatar
root committed
                }else{
                    $_smart_data = $smart_data;
                }
                if($_smart_data === null)
                    continue;

                $arguments = array(
                    new \Cassandra\Bigint($series->row->row_id),
                    new \Cassandra\Varint($_smart_data->time),
                    $entry_type->create(
                        'value',      ($is_digital) ? new \Cassandra\Blob($_smart_data->value) : (double) $_smart_data->value,
                        'error',      new \Cassandra\Tinyint($_smart_data->error),
                        'confidence', new \Cassandra\Tinyint($_smart_data->confidence),
                        'gw',         new \Cassandra\Bigint($this->_gw_id)
                    )
                );

                // TODO: alter the cassandra table's name to Config file
                $cassandra_table  = $this->_domain.'_v1_1_';
                $cassandra_table .= $is_digital ? 'digital' : 'si';
                // -----

                $session = self::_cassandraConnect(Config::config()::CASSANDRA_SERVERNAME, Config::config()::CASSANDRA_PORT, $this->_username, $this->_password, Config::config()::CASSANDRA_KEYSPACE);

                $insert_stmt = $session->prepare("INSERT INTO {$cassandra_table} (id, timestamp, entry) VALUES (?, ?, ?);");
		$session->execute($insert_stmt, array('arguments' => $arguments));
root's avatar
root committed

                $update_stmt = $conn->prepare("UPDATE {$rows_table} SET count = count + 1 WHERE id = :id LIMIT 1;");
                $update_stmt->execute(array('id' => $series->row->id));
            }
	    Logger::time_elapsed();
        } catch (\Exception $e) {
            Logger::exception($e);
            $sucess = false;
        } finally {
            if (isset($session))
                $session->close();
            $conn = null;
        }
        return $sucess;
    }

    private function _process_exists($proc_id) {
        $exists= false;
        exec("ps -A | grep -i $proc_id | grep -v grep", $pids);
        if (!empty($pids)) {
            $exists = true;
        }
        return ($exists || file_exists("/proc/{$proc_id}"));
    }

    private function _initialize_daemon($workflow) {
        $_root  = __DIR__;
	//self::debug_X("root at: {$_root}");
        if (file_exists("{$_root}/../workflow/{$this->_domain}/{$workflow}_daemon")) {
            $alive = false;
            try {
                if(file_exists("{$_root}/../workflow/{$this->_domain}/{$workflow}_pid")) {
                    $pid_file = fopen("{$_root}/../workflow/{$this->_domain}/{$workflow}_pid", "r");
                    if($pid_file) {
                        $pid = fgets($pid_file);
                        fclose($pid_file);
                        $alive = $this->_process_exists($pid) ||  $this->_process_exists("{$workflow}_daemon"); //maybe this string check is not valid
                    }
                }
            } catch (Exception $e) {
                $alive = false;
            }

            if (!($alive)) {
                if (file_exists("{$_root}/../workflow/{$this->_domain}/{$workflow}_error.txt"))
                    unlink("{$_root}/../workflow/{$this->_domain}/{$workflow}_error.txt");
                if (file_exists("{$_root}/../workflow/{$this->_domain}/{$workflow}_pid"))
                    unlink("{$_root}/../workflow/{$this->_domain}/{$workflow}_pid");
                if (file_exists("{$_root}/../workflow/{$this->_domain}/{$workflow}_input"))
                    unlink("{$_root}/../workflow/{$this->_domain}/{$workflow}_input");
                if (file_exists("{$_root}/../workflow/{$this->_domain}/{$workflow}_output"))
                    unlink("{$_root}/../workflow/{$this->_domain}/{$workflow}_output");

                $descriptorspec = array(
                   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
                   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
                   2 => array("file", "{$_root}/../workflow/{$this->_domain}/{$workflow}_error.txt", "a") // stderr is a file to write to
                );
                $path = "{$_root}/../workflow/{$this->_domain}";
                $pid = proc_open("./{$workflow}_daemon $> {$workflow}_results.log", $descriptorspec, $pipes, $path);

                $timeout = 100000; //what is the best value? we can use a timeout in seconds also
                while (!(file_exists("{$_root}/../workflow/{$this->_domain}/{$workflow}_pid")) && $timeout >= 0)
                    $timeout--;
                if($timeout < 0) {
                    self::debug_X("Fail to initialize daemon for workflow {$this->_domain}/{$workflow}");
                }
            }
        } else {
            self::debug_X("No daemon found for {$this->_domain}/{$workflow}");
        }
    }

    private function _notify(\stdClass $json) {
        if(isset($json->notify)) {
            $notification = "Domain: {$this->_domain}. Data irregularity.";
            if(isset($json->notify->description)) {
                $notification .= " Description: {$json->notify->description}.";
            }
            if(isset($json->notify->severity)) {
                //threshold can be either defined by the workflow or by a standard value (100% in this case)
                // isset($json->notify->severity_threshold)
                $notification .= " Severity level: {$json->notify->severity}.";
                if ($json->notify->severity > 100) {
                    //send mail or message bus
                }
            }
            //log notification
            self::debug_X($notification);
        }
    }

    private function _workflow_input($smart_data, $wf) {
root's avatar
root committed
        $_root  = __DIR__;
        $_wf = "in{$wf}";
        $pushd = "pushd {$_root}/../workflow/{$this->_domain} > /dev/null";
root's avatar
root committed
        $popd  = 'popd > /dev/null';
        $this->_initialize_daemon($_wf);
        $json = "{\"smartdata\":" . $smart_data->toJson() . "}";
root's avatar
root committed
        $return = shell_exec("{$pushd}; ./{$_wf} '{$json}'; {$popd};");
        $json = json_decode($return, false, 512, JSON_BIGINT_AS_STRING);
        if (json_last_error() === JSON_ERROR_NONE){
            $smart_data = SmartData::fromJson($json->smartdata);
root's avatar
root committed
        }else{
            throw new Exception\InternalException('Error while processing workflow!');
        }
        $this->_notify($json);
root's avatar
root committed
        return $smart_data;
    }

    private function _workflow_output($json, $wf) {
        $_root  = __DIR__;
        $_wf = "out{$wf}";
        $pushd = "pushd {$_root}/../workflow/{$this->_domain} > /dev/null";
        $popd  = 'popd > /dev/null';
	$this->_initialize_daemon($_wf);
	$str_json = json_encode($json);
	$input = fopen("{$_root}/../workflow/{$this->_domain}/{$_wf}_input", "w");
	fwrite($input, "$str_json\n");
	fclose($input);
        $return = shell_exec("{$pushd}; ./{$_wf}; {$popd};");
        $json = json_decode($return, false, 512, JSON_BIGINT_AS_STRING);
        if (json_last_error() !== JSON_ERROR_NONE){
            throw new Exception\InternalException('Error while processing workflow!');
        }
        return $json;
    }

root's avatar
root committed
    // Insert a mobile version of smartdata
    private function _insertMobileSmartData(MobileSmartData $smart_data) : bool {
        // TODO: check if it is working fine
        $sucess = true;

        $parameters = array(':version'    => $smart_data->version,
                            ':unit'       => $smart_data->unit,
                            ':signature'  => $smart_data->signature,
                            ':time'       => $smart_data->time,
                            ':dev'        => $smart_data->dev,
                            ':domain'     => $this->_domain);

        $is_digital = $smart_data->unit()->is_digital();

        try {

            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME, Config::config()::MYSQL_PORT, Config::config()::MYSQL_DBNAME, Config::config()::MYSQL_USERNAME, Config::config()::MYSQL_PASSWORD);
            $table_trackers = Config::config()::MySQL_Table($smart_data->version);

            $tracker_set = NULL;
            $first = true;

            do {

                $sql="SELECT t.* FROM (SELECT *, min(count) as min FROM trackers WHERE version = :version AND unit = :unit AND signature = :signature AND :time >= t0 AND :time <= t1 AND dev = :dev AND domain = :domain GROUP BY version, unit, dev, t0, t1, signature, workflow, domain) as x inner join trackers as t on t.version = x.version AND t.unit = x.unit AND t.dev = x.dev AND t.t0 = x.t0 AND t.t1 = x.t1 AND t.signature = x.signature AND t.workflow = x.workflow AND t.domain = x.domain AND t.count = x.min GROUP BY version, unit, dev, t0, t1, signature, workflow, domain;";

                $stmt_select = $conn->prepare($sql);
                $stmt_select->execute($parameters);
                $tracker_set = $stmt_select->fetchAll(\PDO::FETCH_OBJ);

                if ($tracker_set == NULL) {
                    // TODO: change do NoMatchingTrackerException
                    throw new Exception\NoMatchingSeriesException('No matching tracker');
                } else {
                    if ($first){
                        foreach ($tracker_set as $tracker) {
                            if($tracker->count>=Config::config()::CASSANDRA_MAX_ROW_SIZE){
                                $stmt_insert = $conn->prepare("INSERT INTO {$table_trackers} VALUES (DEFAULT, :version, :unit, :dev, :t0, :t1, :signature, DEFAULT, :workflow, :domain, (SELECT counter(:domain)), DEFAULT);");
                                $stmt_insert->execute(array(':version'   => $tracker->version,
                                                            ':unit'      => $tracker->unit,
                                                            ':signature' => $tracker->signature,
                                                            ':t0'        => $tracker->t0,
                                                            ':t1'        => $tracker->t1,
                                                            ':dev'       => $tracker->dev,
                                                            ':workflow'  => $tracker->workflow,
                                                            ':domain'    => $this->_domain));
                                //$this->create(new Series($series->version, $series->unit, $series->x, $series->y, $series->z, $series->r, $series->t0, $series->t1));
                                //Logger::debug('creating new Tracker', true);
                            }
                        }
                        $first = false;
                    } else {
                        break;
                    }
                }
            } while (true);

            $entry_type = \Cassandra\Type::userType(
                'value',      ($is_digital) ? \Cassandra\Type::blob() : \Cassandra\Type::double(),
                'error',      \Cassandra\Type::tinyint(),
                'confidence', \Cassandra\Type::tinyint(),
                'x',          \Cassandra\Type::int(),
                'y',          \Cassandra\Type::int(),
                'z',          \Cassandra\Type::int(),
                'gw',         \Cassandra\Type::bigint()
            );

            foreach ($tracker_set as $tracker) {
                self::debug_X('Inserting MobileSmartData on Tracker ['.$tracker->id.'] row ['.$tracker->row_id.']');
                // TODO: alter to workflow
                //if($tracker->workflow != 0)
                //    Logger::debug('Workflow execution', true);

                $arguments = array(
                    new \Cassandra\Bigint($tracker->row_id),
                    new \Cassandra\Varint($smart_data->time),
                    $entry_type->create(
                        'value',      ($is_digital) ? new \Cassandra\Blob($smart_data->value) : (double) $smart_data->value,
                        'error',      new \Cassandra\Tinyint($smart_data->error),
                        'confidence', new \Cassandra\Tinyint($smart_data->confidence),
                        'x',          (int)$smart_data->x,
                        'y',          (int)$smart_data->y,
                        'z',          (int)$smart_data->z,
                        'gw',         new \Cassandra\Bigint($this->_gw_id)
                    )
                );

                // TODO: alter the cassandra table's name to Config file
                $cassandra_table  = $this->_domain.'_v1_2_';
                $cassandra_table .= $is_digital ? 'digital' : 'si';

                $session = self::_cassandraConnect(Config::config()::CASSANDRA_SERVERNAME, Config::config()::CASSANDRA_PORT, $this->_username, $this->_password, Config::config()::CASSANDRA_KEYSPACE);

                $insert_stmt = $session->prepare("INSERT INTO {$cassandra_table} (id, timestamp, entry) VALUES (?, ?, ?);");
                $session->execute($insert_stmt, array('arguments' => $arguments));

                $update_stmt = $conn->prepare("UPDATE {$table_trackers} SET count = count + 1 WHERE id = :id LIMIT 1;");
                $update_stmt->execute(array('id' => $tracker->id));
            }
        } catch (\Exception $e) {
            Logger::exception($e);
            $sucess = false;
        } finally {
            if (isset($session))
                $session->close();
            $conn = null;
        }

        return $sucess;
    }

    private function _insertStaticSmartDataBatch(Series $series, StaticSmartData ...$smart_data) : bool {
        if($series->r != 0)
            throw new Exception\NoMatchingSeriesException('Invalid request'); // TODO: change this exception type

        $sucess = true;
        $smart_data_count = count($smart_data);

        $parameters = array(':version'  => $series->version,
                            ':unit'     => $series->unit,
                            ':x'        => $series->x,
                            ':y'        => $series->y,
                            ':z'        => $series->z,
                            ':r'        => $series->r,
                            //':dev'      => $series->dev, // TODO: The series doesn't has a dev
                            ':t0'       => $series->t0,
                            ':t1'       => $series->t1,
                            ':workflow' => $series->workflow ?? 0,
                            ':domain'   => $this->_domain);
        try {
            $conn = self::_mysqlConnect(Config::config()::MYSQL_SEVERNAME, Config::config()::MYSQL_PORT, Config::config()::MYSQL_DBNAME, Config::config()::MYSQL_USERNAME, Config::config()::MYSQL_PASSWORD);
            $table = Config::config()::MySQL_Table($series->version);
            $series_db = NULL;
            $stmt_select = $conn->prepare("SELECT * FROM {$table} WHERE version = :version AND unit = :unit AND x = :x AND y = :y AND z = :z AND r = :r AND t0 = :t0 AND t1 = :t1 AND workflow = :workflow AND domain = :domain LIMIT 1;");

            $stmt_select->execute($parameters);
            $series_db = $stmt_select->fetch(\PDO::FETCH_OBJ);

            if ($series_db == NULL){// || (($series_db->count + $smart_data_count) >= Config\CASSANDRA_MAX_ROW_SIZE) ) {
                throw new Exception\NoMatchingSeriesException('No matching series');
            }else{
                $rows_table = '`rows`'; // TODO: move to Config file (row table name)
                $count_limit = Config::config()::CASSANDRA_MAX_ROW_SIZE;
                $series_db->row = NULL;
                $first = true;
                do {
                    $stmt_select_row = $conn->prepare("SELECT * FROM {$rows_table} WHERE series_id = :series_id AND x = :x AND y = :y AND z = :z AND dev = :dev AND count < {$count_limit} LIMIT 1;");

                    $parameters_row = array(':series_id'  => $series_db->id,
                                            ':x'          => $series_db->x,
                                            ':y'          => $series_db->y,
                                            ':z'          => $series_db->z,
                                            ':dev'        => $series->dev); // TODO: check this (remove the dev from series)

                    $stmt_select_row->execute($parameters_row);
                    $series_db->row = $stmt_select_row->fetch(\PDO::FETCH_OBJ);

                    if ($first && $series_db->row==NULL) {
                        self::debug_X('There were no rows before');
                        $stmt_insert_row = $conn->prepare("INSERT INTO {$rows_table} VALUES (DEFAULT, :x, :y, :z, :dev, DEFAULT, (SELECT counter(:domain)), :series_id, DEFAULT);");
                        $stmt_insert_row->execute(array_merge($parameters_row, array(':domain' => $this->_domain)));
                        $first = false;
                    } else {
                        break;
                    }

                } while (true);

                self::debug_X('Inserting StaticSmartDataBatch on Series ['.$series_db->id.'] row['.$series_db->row->id.']');

                $is_digital = $series->unit()->is_digital();

                $entry_type = \Cassandra\Type::userType(
                    'value',      ($is_digital) ? \Cassandra\Type::blob() : \Cassandra\Type::double(),
                    'error',      \Cassandra\Type::tinyint(),
                    'confidence', \Cassandra\Type::tinyint(),
                    'gw',         \Cassandra\Type::bigint()
                );

                // TODO: alter the cassandra table's name to Config file
                $cassandra_table  = $this->_domain.'_v1_1_';
                $cassandra_table .= $is_digital ? 'digital' : 'si';
                // -----

                // change this
                // TODO: get this values from the smartdata object
                $row_id     = new \Cassandra\Bigint($series_db->row->row_id);
                $error      = new \Cassandra\Tinyint(0);
                $confidence = new \Cassandra\Tinyint(0);
                $gw         = new \Cassandra\Bigint($this->_gw_id);