source: admin/WebConsole/rest/repository.php @ 0ad92e4

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 0ad92e4 was 2b00219, checked in by Ramón M. Gómez <ramongomez@…>, 6 years ago

#892: Use ogAdmServer Wake on Lan

  • gestor_Comando.php only execute wakeonlan_repo.php when wake up command is called.
  • wakeonlan_repo.php send new needed parameters for ogAdmServer WoL.
  • repository.php use ogAdmServer WoL instead of wakeonlan perl script.
  • opengnsys_installer.sh and opengnsys_update.sh don't have wakeonlan perl script dependency anymore.

# Please enter the commit message for your changes. Lines starting
# with '#' will be kept; you may remove them yourself if you want to.
# An empty message aborts the commit.
#
# Date: Mon Jan 28 10:22:57 2019 +0100
#
# On branch devel
# Your branch is ahead of 'origin/devel' by 1 commit.
# (use "git push" to publish your local commits)
#
# Changes to be committed:
# modified: admin/WebConsole/comandos/gestores/gestor_Comandos.php
# modified: admin/WebConsole/comandos/gestores/wakeonlan_repo.php
# modified: admin/WebConsole/rest/repository.php
# modified: installer/opengnsys_installer.sh
# modified: installer/opengnsys_update.sh
#
# Untracked files:
# 0001-892-Use-ogAdmServer-Wake-on-Lan.patch
# 0001-892-Use-ogAdmServer-Wake-on-Lan.zip
#

  • Property mode set to 100644
File size: 7.6 KB
Line 
1<?php
2/**
3 * @file    repository.php
4 * @brief   OpenGnsys Repository REST API manager.
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
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
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();
27        $app = \Slim\Slim::getInstance();
28
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');
34                if ($confFile) {
35                        if(@strcmp($apikey, $confFile['ApiToken']) == 0) {
36                                // Credentials OK.
37                                return true;
38                        } else {
39                                // Credentials error.
40                                $response['message'] = 'Login failed. Incorrect credentials';
41                                jsonResponse(401, $response);
42                                $app->stop();
43                        }
44                } else {
45                        // Cannot access configuration file.
46                        $response['message'] = "An error occurred, please try again";
47                        jsonResponse(500, $response);
48                        $app->stop();
49                }
50        } else {
51                // Error: missing API key.
52                $response['message'] = 'Missing Repository API key';
53                jsonResponse(400, $response);
54                $app->stop();
55        }
56}
57
58function commandExist($cmd) {
59    $returnVal = shell_exec("which $cmd");
60    return (empty($returnVal) ? false : true);
61}
62
63
64// Define REST routes.
65
66
67/**
68 * @brief    List all images in the repository
69 * @note     Route: /repository/images, Method: GET
70 * @param    no
71 * @return   JSON object with directory, images array, ous array and disk data.
72 */
73$app->get('/repository/images(/)', 'validateRepositoryApiKey',
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)) {
82                // Complete global image information.
83                for ($i=0; $i<sizeof(@$response['images']); $i++) {
84                        $img = $response['images'][$i];
85                        $file = $imgPath."/".($img['type']==="dir" ? $img["name"] : $img["name"].".".$img["type"]);
86                        $response['images'][$i]['size'] = @stat($file)['size'];
87                        $response['images'][$i]['modified'] = date("Y-m-d H:i:s", @stat($file)['mtime']);
88                        $response['images'][$i]['mode'] = substr(decoct(@stat($file)['mode']), -4);
89                        $backupfile = "$file.ant";
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                        }
96                        $lockfile = "$file.lock";
97                        $response['images'][$i]['locked'] = file_exists($lockfile);
98                }
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++) {
102                                $img = $response['ous'][$j]['images'][$i];
103                                $file = $imgPath."/".$response['ous'][$j]['subdir']."/".($img['type']==="dir" ? $img["name"] : $img["name"].".".$img["type"]);
104                                $response['ous'][$j]['images'][$i]['size'] = @stat($file)['size'];
105                                $response['ous'][$j]['images'][$i]['modified'] = date("Y-m-d H:i:s", @stat($file)['mtime']);
106                                $response['ous'][$j]['images'][$i]['mode'] = substr(decoct(@stat($file)['mode']), -4);
107                                $response['ous'][$j]['images'][$i]['backedup'] = false;
108                                $lockfile = "$file.lock";
109                                $response['ous'][$j]['images'][$i]['locked'] = file_exists($lockfile);
110                        }
111                }
112                // Retrieve disk information.
113                $total = disk_total_space($imgPath);
114                $free = disk_free_space($imgPath);
115                $response['disk']['total'] = $total;
116                $response['disk']['free'] = $free;
117                // JSON response.
118                jsonResponse(200, $response);
119        } else {
120                // Print error message.
121                $response['message'] = 'Images directory not found';
122                jsonResponse(404, $response);
123        }
124        $app->stop();
125    }
126);
127
128
129/**
130 * @brief    List image data
131 * @note     Route: /repository/image/:imagename, Method: GET
132 * @param    no
133 * @return   JSON object with image data.
134 */
135$app->get('/repository/image(/:ouname)/:imagename(/)', 'validateRepositoryApiKey',
136    function($ouname="/", $imagename) use ($app) {
137        $images = array();
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'];
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) {
156                if ($img['name'] == $imagename) {
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);
162                        $backupfile = "$file.ant";
163                        if (file_exists($backupfile)) {
164                                $response['backedup'] = true;
165                                $response['backupsize'] = @stat($backupfile)['size'];
166                        } else {
167                                $response['backedup'] = false;
168                        }
169                        $lockfile = "$file.lock";
170                        $response['locked'] = file_exists($lockfile);
171                }
172        }
173        if (isset ($response)) {
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/**
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',
193    function() use($app) {
194                // The macs parameter must come in the post (JSON object with array of MACs)
195                $data = json_decode($app->request()->getBody());
196                if(empty($data->macs)){
197                        // Print error message.
198                        $response['message'] = 'Required param macs not found';
199                        jsonResponse(400, $response);
200                }
201                else{
202                        // Execute WakeOnLan command with ogAdmServer
203                        $strMacs = implode(';', $data->macs);
204                        $strMacs = str_replace(':', '', $strMacs);
205                        $strIps = implode(';', $data->ips);
206                        $params="nfn=Arrancar" . chr(13) . "mac=" . $strMacs . chr(13) . "iph=" . $strIps . chr(13) . "mar=" . $data->mar .
207                                chr(13);
208                        $shidra=new SockHidra("127.0.0.1", "2008");
209                        if ($shidra->conectar()) { // The connection to the hydra server has been established
210                                $resul=$shidra->envia_comando($params);
211                                if($resul) {
212                                        $frame=$shidra->recibe_respuesta();
213                                        $hlonprm=hexdec(substr($frame, LENHEAD, LENHEXPRM));
214                                        $params=substr($frame, LENHEAD + LENHEXPRM, $hlonprm);
215                                        $ParamsValue=extrae_parametros($params, chr(13), '=');
216                                        $resul=$ParamsValue["res"];
217                                        jsonResponse(200, $resul);
218                                } else {
219                                        $response['message'] = 'Error in ogAdmServer';
220                                        jsonResponse(404, $response);
221                                }
222                                $shidra->desconectar();
223                        }
224                }
225        }
226);
227
228
Note: See TracBrowser for help on using the repository browser.