PageRenderTime 25ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/branches/1.0/src/class.DBInstance.php

http://scalr.googlecode.com/
PHP | 229 lines | 160 code | 36 blank | 33 comment | 14 complexity | 38670949cb60c8a4bf2ec2a02f95afc4 MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0, GPL-3.0
  1. <?php
  2. class DBInstance
  3. {
  4. const PROPERTY_SCALARIZR_PACKAGE_VERSION = 'scalarizr_pkg_version';
  5. public
  6. $ID,
  7. $FarmID,
  8. $ClientID,
  9. $InstanceID,
  10. $State,
  11. $AMIID,
  12. $InternalIP,
  13. $ExternalIP,
  14. $IsDBMaster,
  15. $IncludeInDNS,
  16. $RoleName,
  17. $AvailZone,
  18. $Index,
  19. $Region,
  20. $ScalarizrPackageVersion;
  21. private $DB;
  22. private $Client;
  23. private $Farm;
  24. private static $FieldPropertyMap = array(
  25. 'id' => 'ID',
  26. 'farmid' => 'FarmID',
  27. 'instance_id' => 'Email',
  28. 'state' => 'State',
  29. 'ami_id' => 'AMIID',
  30. 'internal_ip' => 'InternalIP',
  31. 'external_ip' => 'ExternalIP',
  32. 'isdbmaster' => 'IsDBMaster',
  33. 'isactive' => 'IncludeInDNS',
  34. 'role_name' => 'RoleName',
  35. 'avail_zone' => 'AvailZone',
  36. 'index' => 'Index',
  37. 'Region' => 'Region',
  38. self::PROPERTY_SCALARIZR_PACKAGE_VERSION => 'ScalarizrPackageVersion'
  39. );
  40. /**
  41. * Constructor
  42. * @param $instance_id
  43. * @return void
  44. */
  45. public function __construct($instance_id)
  46. {
  47. $this->InstanceID = $instance_id;
  48. $this->DB = Core::GetDBInstance();
  49. $this->Logger = Logger::getLogger(__CLASS__);
  50. }
  51. /**
  52. * Load DBInstance by database id
  53. * @param $id
  54. * @return DBInstance
  55. */
  56. static public function LoadByID($id)
  57. {
  58. $db = Core::GetDBInstance();
  59. $instance_info = $db->GetRow("SELECT * FROM farm_instances WHERE id=?", array($id));
  60. if (!$instance_info)
  61. throw new Exception(sprintf(_("Instance ID#%s not found in database"), $id));
  62. $DBInstance = new DBInstance($instance_info['instance_id']);
  63. foreach(self::$FieldPropertyMap as $k=>$v)
  64. {
  65. if ($instance_info[$k])
  66. $DBInstance->{$v} = $instance_info[$k];
  67. }
  68. return $DBInstance;
  69. }
  70. /**
  71. * Load DBInstance by Amazon Instance ID
  72. * @param $iid
  73. * @return DBInstance
  74. */
  75. static public function LoadByIID($iid)
  76. {
  77. $db = Core::GetDBInstance();
  78. $id = $db->GetRow("SELECT id FROM farm_instances WHERE instance_id=?", array($iid));
  79. if (!$id)
  80. throw new Exception(sprintf(_("Instance Amazon ID#%s not found in database"), $iid));
  81. return self::LoadByID($id);
  82. }
  83. /**
  84. * Update specified property
  85. * @param string $prop
  86. * @param string $value
  87. * @return bool
  88. */
  89. public function UpdateProperty($prop, $value)
  90. {
  91. if (!self::$FieldPropertyMap[$prop])
  92. throw new Exception(sprintf(_("Invalid property name: %s"), $prop));
  93. return $this->DB->Execute("UPDATE farm_instances SET `{$prop}`=? WHERE id=?", array($value, $this->ID));
  94. }
  95. /**
  96. * Return information about scalarizr version installed on instance
  97. * @return array
  98. */
  99. public function GetScalarizrVersion()
  100. {
  101. preg_match("/^([0-9]+)\.([0-9]+)-([0-9]+)$/", $this->ScalarizrPackageVersion, $matches);
  102. return array("major" => $matches[1], "minor" => $matches[2], "revision" => $matches[3]);
  103. }
  104. public function IsSupported($v)
  105. {
  106. preg_match("/^([0-9]+)\.([0-9]+)\-([0-9]+)$/si", $v, $matches);
  107. $version = $this->GetScalarizrVersion();
  108. if ($version['major'] > $matches[1])
  109. return true;
  110. elseif ($version['major'] == $matches[1] && $version['minor'] > $matches[2])
  111. return true;
  112. elseif ($version['major'] == $matches[1] && $version['minor'] == $matches[2] && $version['revision'] >= $matches[3])
  113. return true;
  114. return false;
  115. }
  116. public function GetScalarizrConfig()
  117. {
  118. $farminfo = $this->DB->GetRow("SELECT * FROM farms WHERE id=?", array($this->FarmID));
  119. $Client = Client::Load($farminfo['clientid']);
  120. $config = "<config>
  121. <aws>
  122. <account-id>{$Client->AWSAccountID}</account-id>
  123. <access>
  124. <key>{$Client->AWSAccessKey}</key>
  125. <key-id>{$Client->AWSAccessKeyID}</key-id>
  126. </access>
  127. <keypair>
  128. <cert>{$Client->AWSCertificate}</cert>
  129. <pkey>{$Client->AWSPrivateKey}</pkey>
  130. </keypair>
  131. </aws>
  132. <scalr>
  133. <access>
  134. <key>{$Client->GetScalrAPIKey()}</key>
  135. <key-id>{$Client->ScalrKeyID}</key-id>
  136. </access>
  137. <callback-service-url>".CONFIG::$HTTP_PROTO."://".CONFIG::$EVENTHANDLER_URL."/cb_service.php</callback-service-url>
  138. </scalr>
  139. </config>";
  140. }
  141. /**
  142. * Send message to instance
  143. * @param ScalrMessage $message
  144. * @return bool
  145. */
  146. public function SendMessage(ScalrMessage $message)
  147. {
  148. //TODO: Create MessagingTransport object that implements IMessagingTransport.
  149. //TODO: SNMPMessagingTransport & AmazonSQSMessagingTransport
  150. // Add message to database
  151. $this->DB->Execute("INSERT INTO messages SET
  152. messageid = ?,
  153. instance_id = ?,
  154. message = ?,
  155. dtlastdeliveryattempt = NOW()
  156. ON DUPLICATE KEY UPDATE delivery_attempts = delivery_attempts+1, dtlastdeliveryattempt = NOW()
  157. ", array(
  158. $message->MessageID,
  159. $this->InstanceID,
  160. XMLMessageSerializer::Serialize($message)
  161. ));
  162. if ($this->IsSupported("0.5-1"))
  163. {
  164. if (!$this->ClientID)
  165. $this->ClientID = $this->DB->GetOne("SELECT clientid FROM farms WHERE id=?", array($this->FarmID));
  166. $Client = Client::Load($this->ClientID);
  167. $AmazonSQS = AmazonSQS::GetInstance($Client->AWSAccessKeyID, $Client->AWSAccessKey);
  168. try
  169. {
  170. $AmazonSQS->CreateQueue("queue-{$this->InstanceID}", 30);
  171. }
  172. catch(Exception $e)
  173. {
  174. $this->Logger->warn("Cannot create queue: {$e->getMessage()}");
  175. }
  176. $messageID = $AmazonSQS->SendMessage("queue-{$this->InstanceID}", XMLMessageSerializer::Serialize($message));
  177. $this->Logger->info("SQSMessage sent. MessageID: {$messageID}");
  178. }
  179. else
  180. {
  181. if ($this->ExternalIP)
  182. {
  183. $community = $this->DB->GetOne("SELECT hash FROM farms WHERE id=?", array($this->FarmID));
  184. $SNMP = new SNMP();
  185. $SNMP->Connect($this->ExternalIP, null, $community, null, null, true);
  186. $trap = $message->GetSNMPTrap();
  187. $res = $SNMP->SendTrap($trap);
  188. $this->Logger->info("[FarmID: {$this->FarmID}] Sending message ".get_class($message)." via SNMP ({$trap}) to '{$this->InstanceID}' ('{$this->ExternalIP}') complete ({$res})");
  189. }
  190. }
  191. }
  192. }
  193. ?>