source: admin/WebConsole/rest/repository.php @ 7d8c134

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

#743: Usar formato JSON en entrada a ruta REST POST /repository/poweron.

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

  • Property mode set to 100644
File size: 7.1 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
13// Auxiliar functions.
14/**
15 * @brief    Validate API key included in "Authorization" HTTP header.
16 * @return   JSON response on error.
17 */
18function validateRepositoryApiKey() {
19        $response = array();
20        $app = \Slim\Slim::getInstance();
21
22        // Assign user id. that match this key to global variable.
23        @$apikey = htmlspecialchars(function_exists('apache_request_headers') ? apache_request_headers()['Authorization'] : $_SERVER['HTTP_AUTHORIZATION']);
24        if (isset($apikey)) {
25                // fetch repository token from ogAdmRepo.cfg configuration file.
26                @$confFile = parse_ini_file('../../etc/ogAdmRepo.cfg', 'r');
27                if ($confFile) {
28                        if(@strcmp($apikey, $confFile['ApiToken']) == 0) {
29                                // Credentials OK.
30                                return true;
31                        } else {
32                                // Credentials error.
33                                $response['message'] = 'Login failed. Incorrect credentials';
34                                jsonResponse(401, $response);
35                                $app->stop();
36                        }
37                } else {
38                        // Cannot access configuration file.
39                        $response['message'] = "An error occurred, please try again";
40                        jsonResponse(500, $response);
41                        $app->stop();
42                }
43        } else {
44                // Error: missing API key.
45                $response['message'] = 'Missing Repository API key';
46                jsonResponse(400, $response);
47                $app->stop();
48        }
49}
50
51function commandExist($cmd) {
52    $returnVal = shell_exec("which $cmd");
53    return (empty($returnVal) ? false : true);
54}
55
56
57// Define REST routes.
58
59
60/**
61 * @brief    List all images in the repository
62 * @note     Route: /repository/images, Method: GET
63 * @param    no
64 * @return   JSON object with directory, images array, ous array and disk data.
65 */
66$app->get('/repository/images(/)', 'validateRepositoryApiKey',
67    function() use ($app) {
68        $response = array();
69        // Read repository information file.
70        $cfgFile = '/opt/opengnsys/etc/repoinfo.json';
71        $response = json_decode(@file_get_contents($cfgFile), true);
72        // Check if directory exists.
73        $imgPath = @$response['directory'];
74        if (is_dir($imgPath)) {
75                // Complete global image information.
76                for ($i=0; $i<sizeof(@$response['images']); $i++) {
77                        $img = $response['images'][$i];
78                        $file = $imgPath."/".($img['type']==="dir" ? $img["name"] : $img["name"].".".$img["type"]);
79                        $response['images'][$i]['size'] = @stat($file)['size'];
80                        $response['images'][$i]['modified'] = date("Y-m-d H:i:s", @stat($file)['mtime']);
81                        $response['images'][$i]['mode'] = substr(decoct(@stat($file)['mode']), -4);
82                        $backupfile = "$file.ant";
83                        if (file_exists($backupfile)) {
84                                $response['images'][$i]['backedup'] = true;
85                                $response['images'][$i]['backupsize'] = @stat($backupfile)['size'];
86                        } else {
87                                $response['images'][$i]['backedup'] = false;
88                        }
89                        $lockfile = "$file.lock";
90                        $response['images'][$i]['locked'] = file_exists($lockfile);
91                }
92                // Complete image in OUs information.
93                for ($j=0; $j<sizeof(@$response['ous']); $j++) {
94                        for ($i=0; $i<sizeof(@$response['ous'][$j]['images']); $i++) {
95                                $img = $response['ous'][$j]['images'][$i];
96                                $file = $imgPath."/".$response['ous'][$j]['subdir']."/".($img['type']==="dir" ? $img["name"] : $img["name"].".".$img["type"]);
97                                $response['ous'][$j]['images'][$i]['size'] = @stat($file)['size'];
98                                $response['ous'][$j]['images'][$i]['modified'] = date("Y-m-d H:i:s", @stat($file)['mtime']);
99                                $response['ous'][$j]['images'][$i]['mode'] = substr(decoct(@stat($file)['mode']), -4);
100                                $response['ous'][$j]['images'][$i]['backedup'] = false;
101                                $lockfile = "$file.lock";
102                                $response['ous'][$j]['images'][$i]['locked'] = file_exists($lockfile);
103                        }
104                }
105                // Retrieve disk information.
106                $total = disk_total_space($imgPath);
107                $free = disk_free_space($imgPath);
108                $response['disk']['total'] = $total;
109                $response['disk']['free'] = $free;
110                // JSON response.
111                jsonResponse(200, $response);
112        } else {
113                // Print error message.
114                $response['message'] = 'Images directory not found';
115                jsonResponse(404, $response);
116        }
117        $app->stop();
118    }
119);
120
121
122/**
123 * @brief    List image data
124 * @note     Route: /repository/image/:imagename, Method: GET
125 * @param    no
126 * @return   JSON object with image data.
127 */
128$app->get('/repository/image(/:ouname)/:imagename(/)', 'validateRepositoryApiKey',
129    function($ouname="/", $imagename) use ($app) {
130        $images = array();
131        $response = array();
132        // Search image name in repository information file.
133        $cfgFile = '/opt/opengnsys/etc/repoinfo.json';
134        $json = json_decode(@file_get_contents($cfgFile), true);
135        $imgPath = @$json['directory'];
136        if (empty($ouname) or $ouname == "/") {
137                // Search in global directory.
138                $images = @$json['images'];
139        } else {
140                // Search in OU directory.
141                for ($i=0; $i<sizeof(@$json['ous']); $i++) {
142                        if ($json['ous'][$i]['subdir'] == $ouname) {
143                                $images = $json['ous'][$i]['images'];
144                        }
145                }
146        }
147        // Search image.
148        foreach ($images as $img) {
149                if ($img['name'] == $imagename) {
150                        $response = $img;
151                        $file = "$imgPath/$ouname/" . ($img['type']==="dir" ? $img["name"] : $img["name"].".".$img["type"]);
152                        $response['size'] = @stat($file)['size'];
153                        $response['modified'] = date("Y-m-d H:i:s", @stat($file)['mtime']);
154                        $response['mode'] = substr(decoct(@stat($file)['mode']), -4);
155                        $backupfile = "$file.ant";
156                        if (file_exists($backupfile)) {
157                                $response['backedup'] = true;
158                                $response['backupsize'] = @stat($backupfile)['size'];
159                        } else {
160                                $response['backedup'] = false;
161                        }
162                        $lockfile = "$file.lock";
163                        $response['locked'] = file_exists($lockfile);
164                }
165        }
166        if (isset ($response)) {
167                // JSON response.
168                jsonResponse(200, $response);
169        } else {
170                // Print error message.
171                $response['message'] = 'Image not found';
172                jsonResponse(404, $response);
173        }
174        $app->stop();
175    }
176);
177
178
179/**
180 * @brief    Power on a pc or group of pcs with the MAC specified in POST parameters
181 * @note     Route: /poweron, Method: POST
182 * @param    macs      OU id.
183 * @return   JSON string ok if the power on command was sent
184 */
185$app->post('/repository/poweron', 'validateRepositoryApiKey',
186    function() use($app) {
187                // Debe venir el parametro macs en el post (objeto JSON con array de MACs)
188                $data = json_decode($app->request()->getBody());
189                if(empty($data->macs)){
190                        // Print error message.
191                        $response['message'] = 'Required param macs not found';
192                        jsonResponse(400, $response);
193                }
194                else{
195                        $strMacs = "";
196                        foreach($data->macs as $mac){
197                                $strMacs .= " ".$mac;
198                        }
199                        // Ejecutar comando wakeonlan, debe estar disponible en el sistema operativo
200                        if(commandExist("wakeonlan")){
201                                $response["output"] = "Executing wakeonlan ".trim($strMacs)."\n";
202                                $response["output"] .= shell_exec("wakeonlan ".trim($strMacs));
203                                // Comprobar si el comando se ejecutórrectamente
204                        jsonResponse(200, $response);
205                        }
206                        else{
207                                // Print error message.
208                                $response['message'] = 'Wakeonlan command not found in this repository';
209                                jsonResponse(404, $response);
210                        }
211                }
212        }
213);
214
215?>
Note: See TracBrowser for help on using the repository browser.