PageRenderTime 41ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/branches/1.0RC4/www/server/server.php

http://scalr.googlecode.com/
PHP | 454 lines | 355 code | 94 blank | 5 comment | 73 complexity | 78aa18159297824782398578dc9a6003 MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0, GPL-3.0
  1. <?
  2. require("../src/prepend.inc.php");
  3. switch($_GET["_cmd"])
  4. {
  5. case "get_script_args":
  6. $scriptid = (int)$req_scriptid;
  7. $dbversions = $db->GetAll("SELECT * FROM script_revisions WHERE scriptid=? AND approval_state=? ORDER BY revision DESC",
  8. array($scriptid, APPROVAL_STATE::APPROVED)
  9. );
  10. $versions = array();
  11. foreach ($dbversions as $version)
  12. {
  13. preg_match_all("/\%([^\%\s]+)\%/si", $version["script"], $matches);
  14. $vars = $matches[1];
  15. $data = array();
  16. foreach ($vars as $var)
  17. {
  18. if (!in_array($var, CONFIG::$SCRIPT_BUILTIN_VARIABLES))
  19. $data[$var] = ucwords(str_replace("_", " ", $var));
  20. }
  21. $data = json_encode($data);
  22. $versions[] = array("revision" => $version['revision'], "fields" => $data);
  23. }
  24. print json_encode($versions);
  25. exit();
  26. break;
  27. case "check_role_name":
  28. $role_name = $req_name;
  29. $ami_id = $req_ami_id;
  30. if (!preg_match("/^[A-Za-z0-9-]+$/", $role_name))
  31. die(_("Allowed chars for role name is [A-Za-z0-9-]"));
  32. $role_info = $db->GetRow("SELECT * FROM ami_roles WHERE ami_id=? AND clientid=? AND roletype=?",
  33. array($ami_id, $_SESSION['uid'], ROLE_TYPE::CUSTOM)
  34. );
  35. if (!$role_info)
  36. die("REDIRECT");
  37. if ($role_info['name'] == $role_name)
  38. die("ok");
  39. $chk = $db->GetOne("SELECT id FROM ami_roles WHERE name=? AND iscompleted != '2' AND ami_id != ? AND region=?",
  40. array($role_name, $ami_id, $role_info['region'])
  41. );
  42. if (!$chk)
  43. die("ok");
  44. else
  45. die(_("Name is already used by an existing role. Please choose another name."));
  46. break;
  47. case "get_script_props":
  48. $script_id = (int)$req_id;
  49. $version = (int)$req_version;
  50. $script_info = $db->GetRow("SELECT * FROM scripts WHERE id=?",
  51. array($script_id)
  52. );
  53. $script_info['revision'] = $version;
  54. $script_info['script'] = $db->GetOne("SELECT script FROM script_revisions WHERE scriptid=? AND revision=?",
  55. array($script_id, $version)
  56. );
  57. if ($_SESSION['uid'] != 0)
  58. {
  59. if ($script_info['origin'] != SCRIPT_ORIGIN_TYPE::SHARED && $script_info['clientid'] != $_SESSION['uid'])
  60. die();
  61. }
  62. print json_encode($script_info);
  63. exit();
  64. break;
  65. case "get_role_params":
  66. $farmid = (int)$req_farmid;
  67. $ami_info = $db->GetRow("SELECT * FROM ami_roles WHERE ami_id=?", array($req_ami_id));
  68. if ($ami_info['clientid'] != 0 && $ami_info['clientid'] != $_SESSION['uid'] && $_SESSION['uid'] != 0)
  69. die(_("There are no parameters for this role"));
  70. $params = $db->GetAll("SELECT * FROM role_options WHERE ami_id=?", array($req_ami_id));
  71. if (count($params) > 0)
  72. {
  73. $DataForm = new DataForm();
  74. foreach ($params as $param)
  75. {
  76. // Prepare options array
  77. if ($param['options'])
  78. {
  79. $options = json_decode($param['options'], true);
  80. $fopts = array();
  81. foreach ($options as $option)
  82. $fopts[$option[0]] = $option[1];
  83. }
  84. // Get field value
  85. $value = $db->GetOne("SELECT value FROM farm_role_options WHERE farmid=? AND ami_id=? AND name=?",
  86. array($farmid, $req_ami_id, $param['name'])
  87. );
  88. if ($value === false)
  89. $value = $param['defval'];
  90. $field = new DataFormField(
  91. $param['name'],
  92. $param['type'],
  93. $param['name'],
  94. $param['isrequired'],
  95. $fopts,
  96. $param['defval'],
  97. $value,
  98. null,
  99. $param['allow_multiple_choice']
  100. );
  101. $DataForm->AppendField($field);
  102. }
  103. $fields = $DataForm->ListFields();
  104. if (count($fields) != 0)
  105. {
  106. $Smarty->assign(array("DataForm" => $DataForm, "elem_id"=> "role_params", "field_prefix" => "", "field_suffix" => ""));
  107. print $Smarty->fetch("inc/dynamicform.tpl");
  108. }
  109. else
  110. die(_("There are no parameters for this role"));
  111. }
  112. else
  113. die(_("There are no parameters for this role"));
  114. exit();
  115. break;
  116. case "get_script_template_source":
  117. $id = (int)$req_scriptid;
  118. $version = $req_version;
  119. $templateinfo = $db->GetRow("SELECT * FROM scripts WHERE id=?", array($id));
  120. if ($_SESSION['uid'] != 0)
  121. {
  122. if ($templateinfo['origin'] == SCRIPT_ORIGIN_TYPE::CUSTOM && $templateinfo['clientid'] != $_SESSION['uid'])
  123. die(_('There is no source avaiable for selected script'));
  124. }
  125. $sql = "SELECT * FROM script_revisions WHERE scriptid='{$id}'";
  126. if ($version == "latest")
  127. $sql .= " AND revision=(SELECT MAX(revision) FROM script_revisions WHERE scriptid='{$id}' AND approval_state='".APPROVAL_STATE::APPROVED."')";
  128. else
  129. {
  130. $version = (int)$version;
  131. $sql .= " AND revision='{$version}'";
  132. }
  133. $script = $db->GetRow($sql);
  134. if ($templateinfo['origin'] == SCRIPT_ORIGIN_TYPE::USER_CONTRIBUTED)
  135. {
  136. if ($templateinfo['clientid'] != $_SESSION['uid'] && $script['approval_state'] != APPROVAL_STATE::APPROVED)
  137. die(_('There is no source avaiable for selected script'));
  138. }
  139. if ($script)
  140. {
  141. print $script['script'];
  142. }
  143. else
  144. print _('There is no source avaiable for selected script');
  145. exit();
  146. break;
  147. case "get_array_snapshots":
  148. $snaps = $db->GetAll("SELECT * FROM ebs_array_snaps WHERE clientid=? ORDER BY id DESC", array($_SESSION['uid']));
  149. $Smarty->assign(array("snaps" => $snaps, "error" => $error));
  150. $content = $Smarty->fetch("ajax_tables/ebs_array_snaps_list.tpl");
  151. print $content;
  152. exit();
  153. break;
  154. case "get_snapshots_list":
  155. if ($req_volumeid)
  156. {
  157. try
  158. {
  159. $DBEBSVolume = DBEBSVolume::Load($req_volumeid);
  160. $region = $DBEBSVolume->Region;
  161. }
  162. catch(Exception $e)
  163. {
  164. $region = $_SESSION['aws_region'];
  165. }
  166. }
  167. else
  168. $region = $_SESSION['aws_region'];
  169. $AmazonEC2Client = AmazonEC2::GetInstance(AWSRegions::GetAPIURL($region));
  170. $AmazonEC2Client->SetAuthKeys($_SESSION["aws_private_key"], $_SESSION["aws_certificate"]);
  171. // Rows
  172. $response = $AmazonEC2Client->DescribeSnapshots();
  173. $rowz = $response->snapshotSet->item;
  174. if ($rowz instanceof stdClass)
  175. $rowz = array($rowz);
  176. foreach ($rowz as $pk=>$pv)
  177. {
  178. $pv->startTime = date("Y-m-d H:i:s", strtotime($pv->startTime));
  179. $item = $pv;
  180. $item->comment = $db->GetOne("SELECT comment FROM ebs_snaps_info WHERE snapid=?", array(
  181. $item->snapshotId
  182. ));
  183. $item->progress = (int)preg_replace("/[^0-9]+/", "", $item->progress);
  184. $item->free = 100 - $item->progress;
  185. $item->bar_begin = ($item->progress == 0) ? "empty" : "filled";
  186. $item->bar_end = ($item->free != 0) ? "empty" : "filled";
  187. $item->used_percent_width = round(120/100*$item->progress, 2);
  188. $item->free_percent_width = round(120/100*$item->free, 2);
  189. if ($req_volumeid)
  190. {
  191. if ($req_volumeid == $item->volumeId)
  192. {
  193. $snaps[] = $item;
  194. }
  195. $display["snaps_header"] = sprintf(_("Snapshots for %s"), $item->volumeId);
  196. }
  197. elseif (!$req_snapid || $req_snapid == $item->snapshotId)
  198. {
  199. $snaps[] = $item;
  200. }
  201. }
  202. $Smarty->assign(array("snaps" => $snaps, "error" => $error));
  203. $content = $Smarty->fetch("ajax_tables/snapshots_list.tpl");
  204. print $content;
  205. exit();
  206. break;
  207. case "get_instance_process_list":
  208. Core::Load("NET/SNMP");
  209. $SNMP = new SNMP();
  210. // Check cache
  211. $plist_cache = CACHEPATH."/ajax_plist.{$get_iid}.cache";
  212. if (file_exists($plist_cache))
  213. {
  214. clearstatcache();
  215. $time = filemtime($plist_cache);
  216. if ($time > time()-CONFIG::$AJAX_PROCESSLIST_CACHE_LIFETIME) //TODO: Move to config
  217. {
  218. readfile($plist_cache);
  219. exit();
  220. }
  221. }
  222. try
  223. {
  224. $instanceinfo = $db->GetRow("SELECT * FROM farm_instances WHERE instance_id=?", array($get_iid));
  225. if (!$instanceinfo)
  226. throw new Exception(_("Instance not found in database."));
  227. $farminfo = $db->GetRow("SELECT * FROM farms WHERE id=?", array($instanceinfo['farmid']));
  228. if (!$farminfo || ($_SESSION['uid'] != 0 && $farminfo['clientid'] != $_SESSION['uid']))
  229. throw new Exception("Instance not found in database.");
  230. $SNMP->Connect($instanceinfo['external_ip'], null, $farminfo['hash'], null, null, true);
  231. $res = $SNMP->GetFullTree(".1.3.6.1.2.1.25.4.2");
  232. foreach ((array)$res as $k=>$v)
  233. {
  234. if (stristr($k, "HOST-RESOURCES-MIB::hrSWRunIndex"))
  235. {
  236. //
  237. }
  238. elseif (stristr($k, "HOST-RESOURCES-MIB::hrSWRunName"))
  239. {
  240. preg_match("/HOST-RESOURCES-MIB::hrSWRunName.([0-9]+)/si", $k, $matches);
  241. $processes[$matches[1]]["hrSWRunName"] = $v;
  242. }
  243. elseif (stristr($k, "HOST-RESOURCES-MIB::hrSWRunPath"))
  244. {
  245. preg_match("/HOST-RESOURCES-MIB::hrSWRunPath.([0-9]+)/si", $k, $matches);
  246. $processes[$matches[1]]["hrSWRunPath"] = $v;
  247. }
  248. elseif (stristr($k, "HOST-RESOURCES-MIB::hrSWRunParameters"))
  249. {
  250. preg_match("/HOST-RESOURCES-MIB::hrSWRunParameters.([0-9]+)/si", $k, $matches);
  251. $processes[$matches[1]]["hrSWRunParameters"] = trim($v);
  252. }
  253. elseif (stristr($k, "HOST-RESOURCES-MIB::hrSWRunType"))
  254. {
  255. preg_match("/HOST-RESOURCES-MIB::hrSWRunType.([0-9]+)/si", $k, $matches);
  256. switch(trim($v))
  257. {
  258. case 1:
  259. $processes[$matches[1]]["hrSWRunType"] = "unknown";
  260. break;
  261. case 2:
  262. $processes[$matches[1]]["hrSWRunType"] = "operatingSystem";
  263. break;
  264. case 3:
  265. $processes[$matches[1]]["hrSWRunType"] = "deviceDriver";
  266. break;
  267. case 4:
  268. $processes[$matches[1]]["hrSWRunType"] = "application";
  269. break;
  270. }
  271. }
  272. elseif (stristr($k, "HOST-RESOURCES-MIB::hrSWRunStatus"))
  273. {
  274. preg_match("/HOST-RESOURCES-MIB::hrSWRunStatus.([0-9]+)/si", $k, $matches);
  275. switch(trim($v))
  276. {
  277. case 1:
  278. $processes[$matches[1]]["hrSWRunStatus"] = "running";
  279. break;
  280. case 2:
  281. $processes[$matches[1]]["hrSWRunStatus"] = "runnable";
  282. break;
  283. case 3:
  284. $processes[$matches[1]]["hrSWRunStatus"] = "notRunnable";
  285. break;
  286. case 4:
  287. $processes[$matches[1]]["hrSWRunStatus"] = "invalid";
  288. break;
  289. }
  290. }
  291. }
  292. $res = $SNMP->GetFullTree(".1.3.6.1.2.1.25.5.1");
  293. foreach ((array)$res as $k=>$v)
  294. {
  295. if (stristr($k, "hrSWRunPerfCPU"))
  296. {
  297. preg_match("/HOST-RESOURCES-MIB::hrSWRunPerfCPU.([0-9]+)/si", $k, $matches);
  298. $processes[$matches[1]]["hrSWRunPerfCPU"] = trim($v);
  299. }
  300. elseif (stristr($k, "HOST-RESOURCES-MIB::hrSWRunPerfMem"))
  301. {
  302. preg_match("/HOST-RESOURCES-MIB::hrSWRunPerfMem.([0-9]+)/si", $k, $matches);
  303. $processes[$matches[1]]["hrSWRunPerfMem"] = Formater::Bytes2String(((int)trim($v))*1024);
  304. }
  305. }
  306. sort($processes);
  307. }
  308. catch(Exception $e)
  309. {
  310. $error = $e->getMessage();
  311. }
  312. $Smarty->assign(array("processes" => $processes, "error" => $error));
  313. $content = $Smarty->fetch("ajax_tables/process_list.tpl");
  314. @file_put_contents($plist_cache, $content);
  315. print $content;
  316. exit();
  317. break;
  318. case "get_instance_info":
  319. Core::Load("NET/SNMP");
  320. $SNMP = new SNMP();
  321. $instanceinfo = $db->GetRow("SELECT * FROM farm_instances WHERE instance_id=?", array($get_iid));
  322. if (!$instanceinfo)
  323. die(_("Instance not found in database."));
  324. $farminfo = $db->GetRow("SELECT * FROM farms WHERE id=?", array($instanceinfo['farmid']));
  325. if (!$farminfo || ($_SESSION['uid'] != 0 && $farminfo['clientid'] != $_SESSION['uid']))
  326. die(_("Instance not found in database."));
  327. $Client = Client::Load($farminfo['clientid']);
  328. try
  329. {
  330. $AmazonEC2Client = AmazonEC2::GetInstance(AWSRegions::GetAPIURL($farminfo['region']));
  331. $AmazonEC2Client->SetAuthKeys($Client->AWSPrivateKey, $Client->AWSCertificate);
  332. $response = $AmazonEC2Client->DescribeInstances($get_iid);
  333. $instanceset = $response->reservationSet->item->instancesSet;
  334. $instanceinfo['type'] = $instanceset->item->instanceType;
  335. $instanceinfo['placement'] = $instanceset->item->placement->availabilityZone;
  336. $instanceinfo['launchtime'] = date("Y-m-d H:i:s", strtotime($instanceset->item->launchTime));
  337. }
  338. catch(Exception $e)
  339. {
  340. die(sprintf(_("Cannot fetch instance information from EC2: %s"), $e->getMessage()));
  341. }
  342. $instanceinfo['LA'] = _("Unknown");
  343. if ($instanceinfo['external_ip'])
  344. {
  345. $SNMP->Connect($instanceinfo['external_ip'], null, $farminfo['hash'], null, null, true);
  346. $res = $SNMP->Get(".1.3.6.1.4.1.2021.10.1.3.3");
  347. if ($res)
  348. $instanceinfo['LA'] = number_format((float)$res, 2);
  349. }
  350. $eip = $db->GetOne("SELECT id FROM elastic_ips WHERE ipaddress=? AND farmid=?",
  351. array($instanceinfo["external_ip"], $instanceinfo['farmid'])
  352. );
  353. $instanceinfo['IsElastic'] = ($instanceinfo['custom_elastic_ip'] || $eip) ? 1 : 0;
  354. $instanceinfo['role_alias'] = $db->GetOne("SELECT alias FROM ami_roles WHERE ami_id=?", array($instanceinfo['ami_id']));
  355. $Smarty->assign(array("i" => $instanceinfo));
  356. $Smarty->display("inc/popup_instanceinfo.tpl");
  357. break;
  358. }
  359. exit();
  360. ?>