source: admin/WebConsole/rest/repository.php @ b9d5756

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-instalacion
Last change on this file since b9d5756 was a5f7c30, checked in by Ramón M. Gómez <ramongomez@…>, 6 years ago

#892: extract ogAdmServer data from the configuration file

  • Property mode set to 100644
File size: 8.0 KB
RevLine 
[15acccd]1<?php
2/**
[fb2ee20]3 * @file    repository.php
4 * @brief   OpenGnsys Repository REST API manager.
[15acccd]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  Juan Manuel Bardallo SIC Universidad de Huelva
9 * @version 1.0
10 * @date    2016-04-06
11 */
12
[2b00219]13include_once("../clases/SockHidra.php");
14
15include_once("../includes/comunes.php");
16
17define("LENHEXPRM", 5); // Length of hexdecimal chain containing total frame length
18define("LENHEAD", 16); // Frame head length
19
[15acccd]20// Auxiliar functions.
21/**
22 * @brief    Validate API key included in "Authorization" HTTP header.
23 * @return   JSON response on error.
24 */
25function validateRepositoryApiKey() {
26        $response = array();
[e3b5585]27        $app = \Slim\Slim::getInstance();
[15acccd]28
[41c430a]29        // Assign user id. that match this key to global variable.
30        @$apikey = htmlspecialchars(function_exists('apache_request_headers') ? apache_request_headers()['Authorization'] : $_SERVER['HTTP_AUTHORIZATION']);
31        if (isset($apikey)) {
32                // fetch repository token from ogAdmRepo.cfg configuration file.
33                @$confFile = parse_ini_file('../../etc/ogAdmRepo.cfg', 'r');
[15acccd]34                if ($confFile) {
[41c430a]35                        if(@strcmp($apikey, $confFile['ApiToken']) == 0) {
36                                // Credentials OK.
37                                return true;
38                        } else {
[15acccd]39                                // Credentials error.
40                                $response['message'] = 'Login failed. Incorrect credentials';
41                                jsonResponse(401, $response);
42                                $app->stop();
43                        }
44                } else {
[a38cb26]45                        // Cannot access configuration file.
[15acccd]46                        $response['message'] = "An error occurred, please try again";
47                        jsonResponse(500, $response);
[41c430a]48                        $app->stop();
[15acccd]49                }
50        } else {
51                // Error: missing API key.
52                $response['message'] = 'Missing Repository API key';
53                jsonResponse(400, $response);
[41c430a]54                $app->stop();
[15acccd]55        }
56}
57
58function commandExist($cmd) {
59    $returnVal = shell_exec("which $cmd");
60    return (empty($returnVal) ? false : true);
61}
62
[338b30e]63
[15acccd]64// Define REST routes.
65
66
67/**
68 * @brief    List all images in the repository
[72bbcf8]69 * @note     Route: /repository/images, Method: GET
[15acccd]70 * @param    no
[72bbcf8]71 * @return   JSON object with directory, images array, ous array and disk data.
[15acccd]72 */
[72bbcf8]73$app->get('/repository/images(/)', 'validateRepositoryApiKey',
[338b30e]74    function() use ($app) {
75        $response = array();
76        // Read repository information file.
77        $cfgFile = '/opt/opengnsys/etc/repoinfo.json';
78        $response = json_decode(@file_get_contents($cfgFile), true);
79        // Check if directory exists.
80        $imgPath = @$response['directory'];
81        if (is_dir($imgPath)) {
[e3b5585]82                // Complete global image information.
[338b30e]83                for ($i=0; $i<sizeof(@$response['images']); $i++) {
[72bbcf8]84                        $img = $response['images'][$i];
85                        $file = $imgPath."/".($img['type']==="dir" ? $img["name"] : $img["name"].".".$img["type"]);
[338b30e]86                        $response['images'][$i]['size'] = @stat($file)['size'];
[72bbcf8]87                        $response['images'][$i]['modified'] = date("Y-m-d H:i:s", @stat($file)['mtime']);
[338b30e]88                        $response['images'][$i]['mode'] = substr(decoct(@stat($file)['mode']), -4);
[3b8d1ea]89                        $backupfile = "$file.ant";
[9d773c0]90                        if (file_exists($backupfile)) {
91                                $response['images'][$i]['backedup'] = true;
92                                $response['images'][$i]['backupsize'] = @stat($backupfile)['size'];
93                        } else {
94                                $response['images'][$i]['backedup'] = false;
95                        }
[3b8d1ea]96                        $lockfile = "$file.lock";
97                        $response['images'][$i]['locked'] = file_exists($lockfile);
[15acccd]98                }
[e3b5585]99                // Complete image in OUs information.
100                for ($j=0; $j<sizeof(@$response['ous']); $j++) {
101                        for ($i=0; $i<sizeof(@$response['ous'][$j]['images']); $i++) {
[72bbcf8]102                                $img = $response['ous'][$j]['images'][$i];
103                                $file = $imgPath."/".$response['ous'][$j]['subdir']."/".($img['type']==="dir" ? $img["name"] : $img["name"].".".$img["type"]);
[e3b5585]104                                $response['ous'][$j]['images'][$i]['size'] = @stat($file)['size'];
[72bbcf8]105                                $response['ous'][$j]['images'][$i]['modified'] = date("Y-m-d H:i:s", @stat($file)['mtime']);
[e3b5585]106                                $response['ous'][$j]['images'][$i]['mode'] = substr(decoct(@stat($file)['mode']), -4);
[3b8d1ea]107                                $response['ous'][$j]['images'][$i]['backedup'] = false;
108                                $lockfile = "$file.lock";
109                                $response['ous'][$j]['images'][$i]['locked'] = file_exists($lockfile);
[e3b5585]110                        }
111                }
[338b30e]112                // Retrieve disk information.
[72bbcf8]113                $total = disk_total_space($imgPath);
114                $free = disk_free_space($imgPath);
[d610135]115                $response['disk']['total'] = $total;
116                $response['disk']['free'] = $free;
[338b30e]117                // JSON response.
118                jsonResponse(200, $response);
119        } else {
120                // Print error message.
121                $response['message'] = 'Images directory not found';
122                jsonResponse(404, $response);
[15acccd]123        }
[338b30e]124        $app->stop();
125    }
[15acccd]126);
127
128
129/**
[bdee878]130 * @brief    List image data
131 * @note     Route: /repository/image/:imagename, Method: GET
132 * @param    no
133 * @return   JSON object with image data.
134 */
[e368226]135$app->get('/repository/image(/:ouname)/:imagename(/)', 'validateRepositoryApiKey',
136    function($ouname="/", $imagename) use ($app) {
137        $images = array();
[bdee878]138        $response = array();
139        // Search image name in repository information file.
140        $cfgFile = '/opt/opengnsys/etc/repoinfo.json';
141        $json = json_decode(@file_get_contents($cfgFile), true);
142        $imgPath = @$json['directory'];
[e368226]143        if (empty($ouname) or $ouname == "/") {
144                // Search in global directory.
145                $images = @$json['images'];
146        } else {
147                // Search in OU directory.
148                for ($i=0; $i<sizeof(@$json['ous']); $i++) {
149                        if ($json['ous'][$i]['subdir'] == $ouname) {
150                                $images = $json['ous'][$i]['images'];
151                        }
152                }
153        }
154        // Search image.
155        foreach ($images as $img) {
[bdee878]156                if ($img['name'] == $imagename) {
[e368226]157                        $response = $img;
158                        $file = "$imgPath/$ouname/" . ($img['type']==="dir" ? $img["name"] : $img["name"].".".$img["type"]);
159                        $response['size'] = @stat($file)['size'];
160                        $response['modified'] = date("Y-m-d H:i:s", @stat($file)['mtime']);
161                        $response['mode'] = substr(decoct(@stat($file)['mode']), -4);
[3b8d1ea]162                        $backupfile = "$file.ant";
[bdee878]163                        if (file_exists($backupfile)) {
[e368226]164                                $response['backedup'] = true;
165                                $response['backupsize'] = @stat($backupfile)['size'];
[bdee878]166                        } else {
[e368226]167                                $response['backedup'] = false;
[bdee878]168                        }
[3b8d1ea]169                        $lockfile = "$file.lock";
170                        $response['locked'] = file_exists($lockfile);
[bdee878]171                }
172        }
[e368226]173        if (isset ($response)) {
[bdee878]174                // JSON response.
175                jsonResponse(200, $response);
176        } else {
177                // Print error message.
178                $response['message'] = 'Image not found';
179                jsonResponse(404, $response);
180        }
181        $app->stop();
182    }
183);
184
185
186/**
[15acccd]187 * @brief    Power on a pc or group of pcs with the MAC specified in POST parameters
188 * @note     Route: /poweron, Method: POST
189 * @param    macs      OU id.
190 * @return   JSON string ok if the power on command was sent
191 */
192$app->post('/repository/poweron', 'validateRepositoryApiKey',
[fce0af3]193    function() use($app) {
[a5f7c30]194                // Fetch repository token from ogAdmServer.cfg configuration file.
195                @$confFile = parse_ini_file('../../etc/ogAdmServer.cfg', 'r');
196                if ($confFile) {
197                        // The macs parameter must come in the post (JSON object with array of MACs)
198                        $data = json_decode($app->request()->getBody());
199                        if (empty($data->macs)) {
200                                // Print error message.
201                                $response['message'] = 'Required param macs not found';
202                                jsonResponse(400, $response);
203                        } else {
204                                // Execute WakeOnLan command with ogAdmServer
205                                $strMacs = implode(';', $data->macs);
206                                $strMacs = str_replace(':', '', $strMacs);
207                                $strIps = implode(';', $data->ips);
208                                $params="nfn=Arrancar" . chr(13) . "mac=" . $strMacs . chr(13) . "iph=" . $strIps . chr(13) .
209                                        "mar=" . $data->mar . chr(13);
210                                $shidra=new SockHidra($confFile['ServidorAdm'], $confFile['PUERTO']);
211                                if ($shidra->conectar()) { // The connection to the hydra server has been established
212                                        $resul=$shidra->envia_comando($params);
213                                        if($resul) {
214                                                $frame=$shidra->recibe_respuesta();
215                                                $hlonprm=hexdec(substr($frame, LENHEAD, LENHEXPRM));
216                                                $params=substr($frame, LENHEAD + LENHEXPRM, $hlonprm);
217                                                $ParamsValue=extrae_parametros($params, chr(13), '=');
218                                                $resul=$ParamsValue["res"];
219                                                jsonResponse(200, $resul);
220                                        } else {
221                                                $response['message'] = 'Error in ogAdmServer';
222                                                jsonResponse(404, $response);
223                                        }
224                                        $shidra->desconectar();
[2b00219]225                                }
[15acccd]226                        }
[a5f7c30]227                } else {
228                        // Cannot access configuration file.
229                        $response['message'] = "An error occurred, please try again";
230                        jsonResponse(500, $response);
231                        $app->stop();
[15acccd]232                }
233        }
234);
235
[b6ec162]236
Note: See TracBrowser for help on using the repository browser.