BaseJob.php 12 KB

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