source: admin/WebConsole/rest/common.php @ 2907fc5

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since 2907fc5 was 8ba8712, checked in by ramon <ramongomez@…>, 8 years ago

#718: Creada función para devolver respuesta JSON a agente OGAgent y continuar procesando; revisar que el cliente está en la BD y marcado como reservado antes de redirigir notificaciones al servidor UDS.

git-svn-id: https://opengnsys.es/svn/branches/version1.1@5287 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100644
File size: 7.6 KB
Line 
1<?php
2/**
3 * @file    index.php
4 * @brief   OpenGnsys REST API: common functions and routes
5 * @warning All input and output messages are formatted in JSON.
6 * @note    Some ideas are based on article "How to create REST API for Android app using PHP, Slim and MySQL" by Ravi Tamada, thanx.
7 * @license GNU GPLv3+
8 * @author  Ramón M. Gómez, ETSII Univ. Sevilla
9 * @version 1.1.0 - First version
10 * @date    2016-11-17
11 */
12
13
14// Common functions.
15
16/**
17 * @brief   Compose JSON response.
18 * @param   int status      Status code for HTTP response.
19 * @param   array response  Response data.
20 * @param   int opts        Options to encode JSON data.
21 * @return  string          JSON response.
22 */
23function jsonResponse($status, $response, $opts=0) {
24        $app = \Slim\Slim::getInstance();
25        // HTTP status code.
26        $app->status($status);
27        // Content-type HTTP header.
28        $app->contentType('application/json; charset=utf-8');
29        // JSON response.
30        echo json_encode($response, $opts);
31}
32
33/**
34 * @brief   Print immediately JSON response to continue processing.
35 * @param   int status      Status code for HTTP response.
36 * @param   array response  Response data.
37 * @param   int opts        Options to encode JSON data.
38 * @return  string          JSON response.
39 */
40function jsonResponseNow($status, $response, $opts=0) {
41        // Flush buffer.
42        ob_end_clean();
43        ob_end_flush();
44        header("Connection: close");
45        // Compose headers and content.
46        http_response_code((int)$status);
47        header('Content-type: application/json; charset=utf-8');
48        ignore_user_abort();
49        ob_start();
50        echo json_encode($response, $opts);
51        $size = ob_get_length();
52        header("Content-Length: $size");
53        // Print content.
54        ob_end_flush();
55        flush();
56        session_write_close();
57}
58
59/**
60 * @brief    Validate API key included in "Authorization" HTTP header.
61 * @return   JSON response on error.
62 */
63function validateApiKey() {
64        global $cmd;
65        global $userid;
66        $response = array();
67        $app = \Slim\Slim::getInstance();
68        // Read Authorization HTTP header.
69        $headers = apache_request_headers();
70        if (! empty($headers['Authorization'])) {
71                // Assign user id. that match this key to global variable.
72                $apikey = htmlspecialchars($headers['Authorization']);
73                $cmd->texto = "SELECT idusuario
74                                 FROM usuarios
75                                WHERE apikey='$apikey' LIMIT 1";
76                $rs=new Recordset;
77                $rs->Comando=&$cmd;
78                if ($rs->Abrir()) {
79                        $rs->Primero();
80                        if (!$rs->EOF){
81                                // Fetch user id.
82                                $userid = $rs->campos["idusuario"];
83                        } else {
84                                // Credentials error.
85                                $response['message'] = 'Login failed. Incorrect credentials';
86                                jsonResponse(401, $response);
87                                $app->stop();
88                        }
89                        $rs->Cerrar();
90                } else {
91                        // Access error.
92                        $response['message'] = "An error occurred, please try again";
93                        jsonResponse(500, $response);
94                }
95        } else {
96                // Error: missing API key.
97                $response['message'] = 'Missing API key';
98                jsonResponse(400, $response);
99                $app->stop();
100        }
101}
102
103/**
104 * @brief    Check if parameter is set and print error messages if empty.
105 * @param    string param    Parameter to check.
106 * @return   boolean         "false" if parameter is null, otherwise "true".
107 */
108function checkParameter($param) {
109        if (isset($param)) {
110                return true;
111        } else {
112                // Print error message.
113                $response['message'] = 'Parameter not found';
114                jsonResponse(400, $response);
115                return false;
116        }
117}
118
119/**
120 * @brief    Check if all parameters are positive integer numbers.
121 * @param    int id ...      Identificators to check (variable number of parameters).
122 * @return   boolean         "true" if all ids are int>0, otherwise "false".
123 */
124function checkIds() {
125        $opts = Array('options' => Array('min_range' => 1));    // Check for int>0
126        foreach (func_get_args() as $id) {
127                if (!filter_var($id, FILTER_VALIDATE_INT, $opts)) {
128                        return false;
129                }
130        }
131        return true;
132}
133
134/**
135 * @fn       sendCommand($serverip, $serverport, $reqframe, &$values)
136 * @brief    Send a command to an OpenGnsys ogAdmServer and get request.
137 * @param    string serverip    Server IP address.
138 * @param    string serverport  Server port.
139 * @param    string reqframe    Request frame (field's separator is "\r").
140 * @param    array values       Response values (out parameter).
141 * @return   boolean            "true" if success, otherwise "false".
142 */
143function sendCommand($serverip, $serverport, $reqframe, &$values) {
144        global $LONCABECERA;
145        global $LONHEXPRM;
146
147        // Connect to server.
148        $respvalues = "";
149        $connect = new SockHidra($serverip, $serverport);
150        if ($connect->conectar()) {
151                // Send request frame to server.
152                $result = $connect->envia_peticion($reqframe);
153                if ($result) {
154                        // Parse request frame.
155                        $respframe = $connect->recibe_respuesta();
156                        $connect->desconectar();
157                        $paramlen = hexdec(substr($respframe, $LONCABECERA, $LONHEXPRM));
158                        $params = substr($respframe, $LONCABECERA+$LONHEXPRM, $paramlen);
159                        // Fetch values and return result.
160                        $values = extrae_parametros($params, "\r", '=');
161                        return ($values);
162                } else {
163                        // Return with error.
164                        return (false);
165                }
166        } else {
167                // Return with error.
168                return (false);
169        }
170}
171
172/**
173 * @brief   Show custom message for "not found" error (404).
174 */
175$app->notFound(function() {
176        echo "REST route not found.";
177   }
178);
179
180/**
181 * @brief   Hook to write an error log message.
182 * @warning Message will be written in web server's error file.
183 */
184$app->hook('slim.after', function() use ($app) {
185        if ($app->response->getStatus() != 200 ) {
186                // Compose error message (truncating long lines).
187                $app->log->error(date(DATE_ISO8601) . ': ' .
188                                 $app->getName() . ' ' .
189                                 $app->response->getStatus() . ': ' .
190                                 $app->request->getMethod() . ' ' .
191                                 $app->request->getPathInfo() . ': ' .
192                                 substr($app->response->getBody(), 0, 100));
193        }
194   }
195);
196
197
198// Common routes.
199
200/**
201 * @brief    Get general server information
202 * @note     Route: /info, Method: GET
203 * @param    no
204 * @return   JSON object with basic server information (version, services, etc.)
205 */
206$app->get('/info', function() {
207      // Reading version file.
208      @list($project, $version, $release) = explode(' ', file_get_contents('/opt/opengnsys/doc/VERSION.txt'));
209      $response['project'] = trim($project);
210      $response['version'] = trim($version);
211      $response['release'] = trim($release);
212      // Getting actived services.
213      @$services = parse_ini_file('/etc/default/opengnsys');
214      $response['services'] = Array();
215      if (@$services["RUN_OGADMSERVER"] === "yes") {
216          array_push($response['services'], "server");
217          $hasOglive = true;
218      }
219      if (@$services["RUN_OGADMREPO"] === "yes")  array_push($response['services'], "repository");
220      if (@$services["RUN_BTTRACKER"] === "yes")  array_push($response['services'], "tracker");
221      // Reading installed ogLive information file.
222      if ($hasOglive === true) {
223          $data = json_decode(@file_get_contents('/opt/opengnsys/etc/ogliveinfo.json'));
224          if (isset($data->oglive)) {
225              $response['oglive'] = $data->oglive;
226          }
227      }
228      jsonResponse(200, $response);
229   }
230);
231
232/**
233 * @brief    Get the server status
234 * @note     Route: /status, Method: GET
235 * @param    no
236 * @return   JSON object with all data collected from server status (RAM, %CPU, etc.).
237 */
238$app->get('/status', function() {
239      // Getting memory and CPU information.
240      exec("awk '$1~/Mem/ {print $2}' /proc/meminfo",$memInfo);
241      $memInfo = array("total" => $memInfo[0], "used" => $memInfo[1]);
242      $cpuInfo = exec("awk '$1==\"cpu\" {printf \"%.2f\",($2+$4)*100/($2+$4+$5)}' /proc/stat");
243      $cpuModel = exec("awk -F: '$1~/model name/ {print $2}' /proc/cpuinfo");
244      $response["memInfo"] = $memInfo;
245      $response["cpu"] = array("model" => trim($cpuModel), "usage" => $cpuInfo);
246      jsonResponse(200, $response);
247   }
248);
249?>
Note: See TracBrowser for help on using the repository browser.