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

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

#708: Incluir método REST en registro de errores.

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

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