BaseJob.php 12 KB

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