BaseJob.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <?php
  2. namespace ModulesGarden\ProxmoxAddon\App\Jobs;
  3. use Illuminate\Database\Capsule\Manager as DB;
  4. use MGProvision\Proxmox\v2\models\Node;
  5. use MGProvision\Proxmox\v2\VmFactory;
  6. use ModulesGarden\ProxmoxAddon\App\Models\RangeVm;
  7. use ModulesGarden\ProxmoxAddon\App\Models\TaskHistory;
  8. use ModulesGarden\ProxmoxAddon\App\Models\VmModel;
  9. use ModulesGarden\ProxmoxAddon\App\Models\Whmcs\ActivityLog;
  10. use ModulesGarden\ProxmoxAddon\App\Models\Whmcs\ToDoList;
  11. use ModulesGarden\ProxmoxAddon\App\Repositories\RangeVmRepository;
  12. use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
  13. use ModulesGarden\ProxmoxAddon\App\Services\EmailService;
  14. use ModulesGarden\ProxmoxAddon\App\Services\Vps\AdditionalDiskService;
  15. use ModulesGarden\ProxmoxAddon\App\Services\Vps\AdditionalMountPointService;
  16. use ModulesGarden\ProxmoxAddon\App\Services\Vps\AgentService;
  17. use ModulesGarden\ProxmoxAddon\App\Services\Vps\ContainerService;
  18. use ModulesGarden\ProxmoxAddon\App\Services\Vps\HostingService;
  19. use ModulesGarden\ProxmoxAddon\Core\Models\Whmcs\Configuration;
  20. use ModulesGarden\ProxmoxAddon\Core\ModuleConstants;
  21. use ModulesGarden\ProxmoxAddon\Core\Queue\Job;
  22. use ModulesGarden\ProxmoxAddon\Core\UI\Traits\WhmcsParams;
  23. use ModulesGarden\ProxmoxAddon\Core\Traits\Smarty;
  24. use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;
  25. abstract class BaseJob extends Job
  26. {
  27. use ApiService;
  28. use WhmcsParams;
  29. use HostingService;
  30. use Smarty;
  31. /**
  32. * @var VmModel
  33. */
  34. protected $vmModel;
  35. protected $params = [];
  36. /**
  37. * @var EmailService
  38. */
  39. protected $emailService;
  40. /**
  41. * @var ContainerService
  42. */
  43. protected $containerService;
  44. /**
  45. * @var AgentService
  46. */
  47. protected $agentService;
  48. /**
  49. * @var AdditionalDiskService
  50. */
  51. protected $additionalDiskService;
  52. /**
  53. * @var AdditionalMountPointService
  54. */
  55. protected $additionalMountPointService;
  56. protected function initServices()
  57. {
  58. }
  59. /**
  60. * @return VmModel
  61. */
  62. public function getVmModel(){
  63. return $this->vmModel = VmModel::ofHostingId($this->model->rel_id)->where('id', $this->model->custom_id)->firstOrFail();
  64. }
  65. public function initVm(){
  66. $vm = (new VmFactory())->fromVmModel($this->getVmModel());
  67. sl('Vm')->setVm($vm);
  68. sl('Vm')->setVmModel($this->getVmModel());
  69. return $this;
  70. }
  71. public function initParams()
  72. {
  73. if (!$this->model->rel_id)
  74. {
  75. new \InvalidArgumentException(sprintf("Job model: #%s rel_id cannot be empty", $this->model->id));
  76. }
  77. if (!function_exists('ModuleBuildParams'))
  78. {
  79. require_once ModuleConstants::getFullPathWhmcs('includes') . DIRECTORY_SEPARATOR . "modulefunctions.php";
  80. }
  81. $this->params = \ModuleBuildParams($this->model->rel_id);
  82. sl("whmcsParams")->setParams($this->params);
  83. if(function_exists('\ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\sl')){
  84. \ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\sl("whmcsParams")->setParams($this->params);
  85. }
  86. $this->setHostingId($this->params['serviceid']);
  87. return $this;
  88. }
  89. protected function sleep($seconds = 60)
  90. {
  91. $this->model->setWaiting();
  92. $this->model->setRetryAfter(date("Y-m-d H:i:s", strtotime("+{$seconds} seconds")));
  93. $this->model->increaseRetryCount();
  94. }
  95. protected function vmidExistInWhmcs($vmid)
  96. {
  97. //vps
  98. $cfv = 'tblcustomfieldsvalues';
  99. $cfn = 'tblcustomfields';
  100. $h = 'tblhosting';
  101. $query = DB::table($cfv)
  102. ->rightJoin($cfn, "{$cfn}.id", "=", "{$cfv}.fieldid")
  103. ->leftJoin($h, "{$h}.id", "=", "{$cfv}.relid")
  104. ->where("{$cfn}.fieldname", "like", "vmid%")
  105. ->where("{$cfv}.value", $vmid)
  106. ->whereIn("{$h}.domainstatus", ['Active', "Suspended"]);
  107. if ($query->count())
  108. {
  109. return true;
  110. }
  111. //cloud
  112. try
  113. {
  114. $query = VmModel::where("vmid", $vmid);
  115. return $query->count() > 0;
  116. }
  117. catch (\Exception $ex)
  118. { // table does not exist
  119. }
  120. return false;
  121. }
  122. protected function findFreeVmid($vmid)
  123. {
  124. for ($i = $vmid; $i <= 1000000; $i++)
  125. {
  126. if ($this->vmidExistInWhmcs($i))
  127. {
  128. continue;
  129. }
  130. try
  131. {
  132. $res = $this->api()->get("/cluster/nextid", ['vmid' => $i]);
  133. }
  134. catch (\Exception $ex)
  135. {
  136. continue;
  137. }
  138. if ($res == $i)
  139. {
  140. return $i;
  141. }
  142. }
  143. throw new \Exception("Unable to obtain vmid");
  144. }
  145. protected function isVmRange()
  146. {
  147. if (RangeVm::ofServerId($this->getWhmcsParamByKey("serverid"))->count())
  148. {
  149. return true;
  150. }
  151. return Configuration::where("setting", "proxmoxVPSMinimumVMID")->count() > 0;
  152. }
  153. protected function nextVmid()
  154. {
  155. $data = $this->api()->get("/cluster/nextid", []);
  156. $vmid = (int)$data ? (int)$data : 100;
  157. $vmid = $this->findFreeVmid($vmid);
  158. if ($this->isVmRange())
  159. {
  160. $rageVm = new RangeVmRepository($this->getWhmcsParamByKey('serverid'));
  161. if (!$rageVm->has() && !$rageVm->getMin())
  162. {
  163. return $vmid;
  164. }
  165. else
  166. {
  167. if (!$rageVm->getMax() && $rageVm->getMin())
  168. {
  169. $from = (int)$rageVm->getMin();
  170. $to = (int)$rageVm->getMin() * 100;
  171. }
  172. else
  173. {
  174. $from = (int)$rageVm->getMin();
  175. $to = (int)$rageVm->getMax();
  176. }
  177. }
  178. for ($i = $from; $i <= $to; $i++)
  179. {
  180. try
  181. {
  182. if ($this->vmidExistInWhmcs($i))
  183. {
  184. continue;
  185. }
  186. $res = $this->api()->get("/cluster/nextid", ['vmid' => $i]);
  187. if ((int)$res == $i)
  188. {
  189. $vmID = $i;
  190. break;
  191. }
  192. }
  193. catch (\Exception $ex)
  194. {
  195. continue;
  196. }
  197. }
  198. if (!$vmID)
  199. {
  200. throw new \Exception("VM Ranges have been exited for this server. Please setup VM Ranges", 321);
  201. }
  202. }
  203. return $vmID ? $vmID : $vmid;
  204. }
  205. protected function createTaskHistory($taskId, $action)
  206. {
  207. $type = str_replace(["qemu", "lxc"], ["VM", "CT"], $this->getVmModel()->virtualization);
  208. $task = new TaskHistory();
  209. $task->fill([
  210. 'hosting_id' => $this->getWhmcsParamByKey("serviceid"),
  211. 'upid' => $taskId,
  212. 'name' => sprintf("%s %s - %s", $type, $this->getVmModel()->vmid, $action),
  213. 'vmid' => $this->getVmModel()->vmid,
  214. 'node' => $this->getVmModel()->node,
  215. 'status' => 0
  216. ])->save();
  217. }
  218. protected function getModelData()
  219. {
  220. return unserialize($this->model->data);
  221. }
  222. protected function putModelDataAndSave(array $newData)
  223. {
  224. $data = $this->getModelData();
  225. $data += $newData;
  226. $this->setModelDataAndSave($data);
  227. return $this;
  228. }
  229. protected function setModelDataAndSave(array $data)
  230. {
  231. $this->model->data = serialize($data);
  232. $this->model->save();
  233. return $this;
  234. }
  235. /**
  236. * @return \MGProvision\Proxmox\v2\models\Task
  237. * @throws \MGProvision\Proxmox\v2\ProxmoxApiException
  238. */
  239. protected function getTask()
  240. {
  241. $taskId = $this->getModelData()['taskId'];
  242. //Init API service
  243. if($this->getModelData()['templateNode']){
  244. $node = new Node($this->getModelData()['templateNode']);
  245. }else{
  246. $node = new Node($this->getModelData()['node']);
  247. }
  248. $node->setApi($this->api());
  249. return $node->task($taskId);
  250. }
  251. protected function isTask()
  252. {
  253. return !is_null($this->getModelData()['taskId']);
  254. }
  255. protected function isDone()
  256. {
  257. $taskId = $this->getModelData()['taskId'];
  258. if (!$taskId || !$this->getModelData()['node'])
  259. {
  260. return false;
  261. }
  262. $task = $this->getTask();
  263. if ($task->getStatus() == "running")
  264. {
  265. $this->log->success(sprintf("Waiting to finish. Task Id %s Node: %s ", $task->getUpid(), $task->getNode()));
  266. return false;
  267. }
  268. //Failed
  269. if ($task->getExitstatus() && $task->getExitstatus() != "OK")
  270. {
  271. $this->log->error($task->getExitstatus());
  272. $this->failed($task->getExitstatus());
  273. $data = $this->getModelData();
  274. unset($data['taskId'], $data['node']);
  275. $this->setModelDataAndSave($data);
  276. return false;
  277. }
  278. return true;
  279. }
  280. protected function isTaskRunning()
  281. {
  282. return $this->isTask() && $this->getTask()->isRunning();
  283. }
  284. protected function isFailed()
  285. {
  286. $task = $this->getTask();
  287. return $task->getExitstatus() && $task->getExitstatus() != "OK";
  288. }
  289. protected function failed($error)
  290. {
  291. if ((int)$this->model->retry_count != 21)
  292. {
  293. return;
  294. }
  295. if (!preg_match("/Create/", $this->model->job) || preg_match("/Clone/", $this->model->job))
  296. {
  297. return;
  298. }
  299. //create new entery on to do list
  300. if ($this->configuration()->isToDoList())
  301. {
  302. $title = sprintf('Creation Failed - Service ID: %s', $this->getWhmcsParamByKey('serviceid'));
  303. if (ToDoList::ofTitle($title)->pending()->count())
  304. {
  305. return;
  306. }
  307. $entity = new ToDoList();
  308. $entity->fill(
  309. [
  310. 'date' => date("Y-m-d H:i:s"),
  311. "duedate" => date("Y-m-d H:i:s"),
  312. 'title' => $title,
  313. "status" => "Pending",
  314. "description" => $error,
  315. "admin" => 0,
  316. ]
  317. );
  318. $entity->save();
  319. }
  320. //send admin message
  321. if ($this->configuration()->getServiceCreationFailedTemplateId())
  322. {
  323. //init email template
  324. $this->emailService->template($this->configuration()->getServiceCreationFailedTemplateId());
  325. //check if already send
  326. $description = printf('Email Sent to Admin (%s) - Service ID: %s', $this->emailService->getVars()['messagename'], $this->getWhmcsParamByKey('serviceid'));
  327. if (ActivityLog::ofDescription($description)->today()->count() > 0)
  328. {
  329. return;
  330. }
  331. //email vars
  332. global $customadminpath;
  333. $adminDir = $customadminpath ? $customadminpath : "admin";
  334. $adminAreaLink = $GLOBALS['CONFIG']['SystemURL'] . "/{$adminDir}";
  335. $hosting = $GLOBALS['CONFIG']['SystemURL'] . "/{$adminDir}/clientsservices.php?id=" . $this->getWhmcsParamByKey('serviceid');
  336. $emailVars = [
  337. "client_id" => $this->getWhmcsParamByKey('clientsdetails')['id'],
  338. "service_id" => $this->getWhmcsParamByKey('serviceid'),
  339. "service_product" => "<a href='{$hosting}/'>{$hosting}</a>",
  340. "service_domain" => $this->getWhmcsParamByKey('domain'),
  341. "error_msg" => $error,
  342. "whmcs_admin_link" => "<a href='{$adminAreaLink}/'>{$adminAreaLink}</a>",
  343. ];
  344. $this->emailService->vars($emailVars)->sendToAdmin();
  345. logActivity($description);
  346. }
  347. }
  348. /**
  349. * @return \ModulesGarden\ProxmoxAddon\App\Models\Job:
  350. */
  351. protected function getParentModel()
  352. {
  353. if (is_null($this->model->parent_id))
  354. {
  355. throw new \InvalidArgumentException("The Parent Id is not valid");
  356. }
  357. if ($this->parent)
  358. {
  359. return $this->parent;
  360. }
  361. return $this->parent = \ModulesGarden\ProxmoxAddon\App\Models\Job::ofId($this->model->parent_id)->firstOrFail();
  362. }
  363. protected function getParentModelData()
  364. {
  365. return unserialize($this->getParentModel()->data);
  366. }
  367. }