source: admin/WebConsole/rest/common.php @ 357352b

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 357352b was 357352b, checked in by ramon <ramongomez@…>, 8 years ago

#708: Obtener datos y código HTTP en llamadas curl_multi de PHP; usar fecha en formato ISO 8601 y quitar líneas en blanco al final de ficheros.

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

  • Property mode set to 100644
File size: 6.4 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 * @return  string          JSON response.
21 */
22function jsonResponse($status, $response) {
23        $app = \Slim\Slim::getInstance();
24        // HTTP status code.
25        $app->status($status);
26        // Content-type HTTP header.
27        $app->contentType('application/json');
28        // JSON response.
29        echo json_encode($response);
30}
31
32/**
33 * @brief    Validate API key included in "Authorization" HTTP header.
34 * @return   JSON response on error.
35 */
36function validateApiKey() {
37        global $cmd;
38        global $userid;
39        $response = array();
40        $app = \Slim\Slim::getInstance();
41        // Read Authorization HTTP header.
42        $headers = apache_request_headers();
43        if (! empty($headers['Authorization'])) {
44                // Assign user id. that match this key to global variable.
45                $apikey = htmlspecialchars($headers['Authorization']);
46                $cmd->texto = "SELECT idusuario
47                                 FROM usuarios
48                                WHERE apikey='$apikey' LIMIT 1";
49                $rs=new Recordset;
50                $rs->Comando=&$cmd;
51                if ($rs->Abrir()) {
52                        $rs->Primero();
53                        if (!$rs->EOF){
54                                // Fetch user id.
55                                $userid = $rs->campos["idusuario"];
56                        } else {
57                                // Credentials error.
58                                $response['message'] = 'Login failed. Incorrect credentials';
59                                jsonResponse(401, $response);
60                                $app->stop();
61                        }
62                        $rs->Cerrar();
63                } else {
64                        // Access error.
65                        $response['message'] = "An error occurred, please try again";
66                        jsonResponse(500, $response);
67                }
68        } else {
69                // Error: missing API key.
70                $response['message'] = 'Missing API key';
71                jsonResponse(400, $response);
72                $app->stop();
73        }
74}
75
76/**
77 * @brief    Check if parameter is set and print error messages if empty.
78 * @param    string param    Parameter to check.
79 * @return   boolean         "false" if parameter is null, otherwise "true".
80 */
81function checkParameter($param) {
82        if (isset($param)) {
83                return true;
84        } else {
85                // Print error message.
86                $response['message'] = 'Parameter not found';
87                jsonResponse(400, $response);
88                return false;
89        }
90}
91
92/**
93 * @fn       sendCommand($serverip, $serverport, $reqframe, &$values)
94 * @brief    Send a command to an OpenGnsys ogAdmServer and get request.
95 * @param    string serverip    Server IP address.
96 * @param    string serverport  Server port.
97 * @param    string reqframe    Request frame (field's separator is "\r").
98 * @param    array values       Response values (out parameter).
99 * @return   boolean            "true" if success, otherwise "false".
100 */
101function sendCommand($serverip, $serverport, $reqframe, &$values) {
102        global $LONCABECERA;
103        global $LONHEXPRM;
104
105        // Connect to server.
106        $respvalues = "";
107        $connect = new SockHidra($serverip, $serverport);
108        if ($connect->conectar()) {
109                // Send request frame to server.
110                $result = $connect->envia_peticion($reqframe);
111                if ($result) {
112                        // Parse request frame.
113                        $respframe = $connect->recibe_respuesta();
114                        $connect->desconectar();
115                        $paramlen = hexdec(substr($respframe, $LONCABECERA, $LONHEXPRM));
116                        $params = substr($respframe, $LONCABECERA+$LONHEXPRM, $paramlen);
117                        // Fetch values and return result.
118                        $values = extrae_parametros($params, "\r", '=');
119                        return ($values);
120                } else {
121                        // Return with error.
122                        return (false);
123                }
124        } else {
125                // Return with error.
126                return (false);
127        }
128}
129
130/**
131 * @brief   Show custom message for "not found" error (404).
132 */
133$app->notFound(function() {
134        echo "REST route not found.\n";
135   }
136);
137
138/**
139 * @brief   Hook to write an error log message.
140 * @warning Message will be written in web server's error file.
141 */
142$app->hook('slim.after', function() use ($app) {
143        if ($app->response->getStatus() != 200 ) {
144                // Compose error message (truncating long lines).
145                $app->log->error(date(DATE_ISO8601) . ': ' .
146                                 $app->getName() . ' ' .
147                                 $app->response->getStatus() . ': ' .
148                                 $app->request->getMethod() . ' ' .
149                                 $app->request->getPathInfo() . ': ' .
150                                 substr($app->response->getBody(), 0, 100));
151        }
152   }
153);
154
155
156// Common routes.
157
158/**
159 * @brief    Get general server information
160 * @note     Route: /info, Method: GET
161 * @param    no
162 * @return   JSON object with basic server information (version, services, etc.)
163 */
164$app->get('/info', function() {
165      // Reading version file.
166      @list($project, $version, $release) = explode(' ', file_get_contents('/opt/opengnsys/doc/VERSION.txt'));
167      $response['project'] = trim($project);
168      $response['version'] = trim($version);
169      $response['release'] = trim($release);
170      // Getting actived services.
171      @$services = parse_ini_file('/etc/default/opengnsys');
172      $response['services'] = Array();
173      if (@$services["RUN_OGADMSERVER"] === "yes") {
174          array_push($response['services'], "server");
175          $hasOglive = true;
176      }
177      if (@$services["RUN_OGADMREPO"] === "yes")  array_push($response['services'], "repository");
178      if (@$services["RUN_BTTRACKER"] === "yes")  array_push($response['services'], "tracker");
179      // Reading installed ogLive information file.
180      if ($hasOglive === true) {
181          $data = json_decode(@file_get_contents('/opt/opengnsys/etc/ogliveinfo.json'));
182          if (isset($data->oglive)) {
183              $response['oglive'] = $data->oglive;
184          }
185      }
186      jsonResponse(200, $response);
187   }
188);
189
190/**
191 * @brief    Get the server status
192 * @note     Route: /status, Method: GET
193 * @param    no
194 * @return   JSON object with all data collected from server status (RAM, %CPU, etc.).
195 */
196$app->get('/status', function() {
197      // Getting memory and CPU information.
198      exec("awk '$1~/Mem/ {print $2}' /proc/meminfo",$memInfo);
199      $memInfo = array("total" => $memInfo[0], "used" => $memInfo[1]);
200      $cpuInfo = exec("awk '$1==\"cpu\" {printf \"%.2f\",($2+$4)*100/($2+$4+$5)}' /proc/stat");
201      $cpuModel = exec("awk -F: '$1~/model name/ {print $2}' /proc/cpuinfo");
202      $response["memInfo"] = $memInfo;
203      $response["cpu"] = array("model" => trim($cpuModel), "usage" => $cpuInfo);
204      jsonResponse(200, $response);
205   }
206);
207?>
Note: See TracBrowser for help on using the repository browser.