source: admin/WebConsole/rest/common.php @ cff57e6

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

#708: Establecer tiempo máximo de reserva para que un equipo pueda ser usado en acceso remoto.

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

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