PageRenderTime 50ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/branches/1.0RC5/www/server/server.php

http://scalr.googlecode.com/
PHP | 456 lines | 357 code | 94 blank | 5 comment | 73 complexity | 7740bf85b5f2a26d02a87756b5bf9b08 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. $info = $db->GetRow("SELECT * FROM ebs_snaps_info WHERE snapid=?", array(
  181. $item->snapshotId
  182. ));
  183. $item->comment = $info['comment'];
  184. $item->is_array_snapshot = ($info['arraysnapshotid'] > 0) ? true : false;
  185. $item->progress = (int)preg_replace("/[^0-9]+/", "", $item->progress);
  186. $item->free = 100 - $item->progress;
  187. $item->bar_begin = ($item->progress == 0) ? "empty" : "filled";
  188. $item->bar_end = ($item->free != 0) ? "empty" : "filled";
  189. $item->used_percent_width = round(120/100*$item->progress, 2);
  190. $item->free_percent_width = round(120/100*$item->free, 2);
  191. if ($req_volumeid)
  192. {
  193. if ($req_volumeid == $item->volumeId)
  194. {
  195. $snaps[] = $item;
  196. }
  197. $display["snaps_header"] = sprintf(_("Snapshots for %s"), $item->volumeId);
  198. }
  199. elseif (!$req_snapid || $req_snapid == $item->snapshotId)
  200. {
  201. $snaps[] = $item;
  202. }
  203. }
  204. $Smarty->assign(array("snaps" => $snaps, "error" => $error));
  205. $content = $Smarty->fetch("ajax_tables/snapshots_list.tpl");
  206. print $content;
  207. exit();
  208. break;
  209. case "get_instance_process_list":
  210. Core::Load("NET/SNMP");
  211. $SNMP = new SNMP();
  212. // Check cache
  213. $plist_cache = CACHEPATH."/ajax_plist.{$get_iid}.cache";
  214. if (file_exists($plist_cache))
  215. {
  216. clearstatcache();
  217. $time = filemtime($plist_cache);
  218. if ($time > time()-CONFIG::$AJAX_PROCESSLIST_CACHE_LIFETIME) //TODO: Move to config
  219. {
  220. readfile($plist_cache);
  221. exit();
  222. }
  223. }
  224. try
  225. {
  226. $instanceinfo = $db->GetRow("SELECT * FROM farm_instances WHERE instance_id=?", array($get_iid));
  227. if (!$instanceinfo)
  228. throw new Exception(_("Instance not found in database."));
  229. $farminfo = $db->GetRow("SELECT * FROM farms WHERE id=?", array($instanceinfo['farmid']));
  230. if (!$farminfo || ($_SESSION['uid'] != 0 && $farminfo['clientid'] != $_SESSION['uid']))
  231. throw new Exception("Instance not found in database.");
  232. $SNMP->Connect($instanceinfo['external_ip'], null, $farminfo['hash'], null, null, true);
  233. $res = $SNMP->GetFullTree(".1.3.6.1.2.1.25.4.2");
  234. foreach ((array)$res as $k=>$v)
  235. {
  236. if (stristr($k, "HOST-RESOURCES-MIB::hrSWRunIndex"))
  237. {
  238. //
  239. }
  240. elseif (stristr($k, "HOST-RESOURCES-MIB::hrSWRunName"))
  241. {
  242. preg_match("/HOST-RESOURCES-MIB::hrSWRunName.([0-9]+)/si", $k, $matches);
  243. $processes[$matches[1]]["hrSWRunName"] = $v;
  244. }
  245. elseif (stristr($k, "HOST-RESOURCES-MIB::hrSWRunPath"))
  246. {
  247. preg_match("/HOST-RESOURCES-MIB::hrSWRunPath.([0-9]+)/si", $k, $matches);
  248. $processes[$matches[1]]["hrSWRunPath"] = $v;
  249. }
  250. elseif (stristr($k, "HOST-RESOURCES-MIB::hrSWRunParameters"))
  251. {
  252. preg_match("/HOST-RESOURCES-MIB::hrSWRunParameters.([0-9]+)/si", $k, $matches);
  253. $processes[$matches[1]]["hrSWRunParameters"] = trim($v);
  254. }
  255. elseif (stristr($k, "HOST-RESOURCES-MIB::hrSWRunType"))
  256. {
  257. preg_match("/HOST-RESOURCES-MIB::hrSWRunType.([0-9]+)/si", $k, $matches);
  258. switch(trim($v))
  259. {
  260. case 1:
  261. $processes[$matches[1]]["hrSWRunType"] = "unknown";
  262. break;
  263. case 2:
  264. $processes[$matches[1]]["hrSWRunType"] = "operatingSystem";
  265. break;
  266. case 3:
  267. $processes[$matches[1]]["hrSWRunType"] = "deviceDriver";
  268. break;
  269. case 4:
  270. $processes[$matches[1]]["hrSWRunType"] = "application";
  271. break;
  272. }
  273. }
  274. elseif (stristr($k, "HOST-RESOURCES-MIB::hrSWRunStatus"))
  275. {
  276. preg_match("/HOST-RESOURCES-MIB::hrSWRunStatus.([0-9]+)/si", $k, $matches);
  277. switch(trim($v))
  278. {
  279. case 1:
  280. $processes[$matches[1]]["hrSWRunStatus"] = "running";
  281. break;
  282. case 2:
  283. $processes[$matches[1]]["hrSWRunStatus"] = "runnable";
  284. break;
  285. case 3:
  286. $processes[$matches[1]]["hrSWRunStatus"] = "notRunnable";
  287. break;
  288. case 4:
  289. $processes[$matches[1]]["hrSWRunStatus"] = "invalid";
  290. break;
  291. }
  292. }
  293. }
  294. $res = $SNMP->GetFullTree(".1.3.6.1.2.1.25.5.1");
  295. foreach ((array)$res as $k=>$v)
  296. {
  297. if (stristr($k, "hrSWRunPerfCPU"))
  298. {
  299. preg_match("/HOST-RESOURCES-MIB::hrSWRunPerfCPU.([0-9]+)/si", $k, $matches);
  300. $processes[$matches[1]]["hrSWRunPerfCPU"] = trim($v);
  301. }
  302. elseif (stristr($k, "HOST-RESOURCES-MIB::hrSWRunPerfMem"))
  303. {
  304. preg_match("/HOST-RESOURCES-MIB::hrSWRunPerfMem.([0-9]+)/si", $k, $matches);
  305. $processes[$matches[1]]["hrSWRunPerfMem"] = Formater::Bytes2String(((int)trim($v))*1024);
  306. }
  307. }
  308. sort($processes);
  309. }
  310. catch(Exception $e)
  311. {
  312. $error = $e->getMessage();
  313. }
  314. $Smarty->assign(array("processes" => $processes, "error" => $error));
  315. $content = $Smarty->fetch("ajax_tables/process_list.tpl");
  316. @file_put_contents($plist_cache, $content);
  317. print $content;
  318. exit();
  319. break;
  320. case "get_instance_info":
  321. Core::Load("NET/SNMP");
  322. $SNMP = new SNMP();
  323. $instanceinfo = $db->GetRow("SELECT * FROM farm_instances WHERE instance_id=?", array($get_iid));
  324. if (!$instanceinfo)
  325. die(_("Instance not found in database."));
  326. $farminfo = $db->GetRow("SELECT * FROM farms WHERE id=?", array($instanceinfo['farmid']));
  327. if (!$farminfo || ($_SESSION['uid'] != 0 && $farminfo['clientid'] != $_SESSION['uid']))
  328. die(_("Instance not found in database."));
  329. $Client = Client::Load($farminfo['clientid']);
  330. try
  331. {
  332. $AmazonEC2Client = AmazonEC2::GetInstance(AWSRegions::GetAPIURL($farminfo['region']));
  333. $AmazonEC2Client->SetAuthKeys($Client->AWSPrivateKey, $Client->AWSCertificate);
  334. $response = $AmazonEC2Client->DescribeInstances($get_iid);
  335. $instanceset = $response->reservationSet->item->instancesSet;
  336. $instanceinfo['type'] = $instanceset->item->instanceType;
  337. $instanceinfo['placement'] = $instanceset->item->placement->availabilityZone;
  338. $instanceinfo['launchtime'] = date("Y-m-d H:i:s", strtotime($instanceset->item->launchTime));
  339. }
  340. catch(Exception $e)
  341. {
  342. die(sprintf(_("Cannot fetch instance information from EC2: %s"), $e->getMessage()));
  343. }
  344. $instanceinfo['LA'] = _("Unknown");
  345. if ($instanceinfo['external_ip'])
  346. {
  347. $SNMP->Connect($instanceinfo['external_ip'], null, $farminfo['hash'], null, null, true);
  348. $res = $SNMP->Get(".1.3.6.1.4.1.2021.10.1.3.3");
  349. if ($res)
  350. $instanceinfo['LA'] = number_format((float)$res, 2);
  351. }
  352. $eip = $db->GetOne("SELECT id FROM elastic_ips WHERE ipaddress=? AND farmid=?",
  353. array($instanceinfo["external_ip"], $instanceinfo['farmid'])
  354. );
  355. $instanceinfo['IsElastic'] = ($instanceinfo['custom_elastic_ip'] || $eip) ? 1 : 0;
  356. $instanceinfo['role_alias'] = $db->GetOne("SELECT alias FROM ami_roles WHERE ami_id=?", array($instanceinfo['ami_id']));
  357. $Smarty->assign(array("i" => $instanceinfo));
  358. $Smarty->display("inc/popup_instanceinfo.tpl");
  359. break;
  360. }
  361. exit();
  362. ?>