model.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. <?php
  2. /**
  3. * The model file of compile module of ZenTaoPMS.
  4. *
  5. * @copyright Copyright 2009-2023 禅道软件(青岛)有限公司(ZenTao Software (Qingdao) Co., Ltd. www.cnezsoft.com)
  6. * @license ZPL(http://zpl.pub/page/zplv12.html) or AGPL(https://www.gnu.org/licenses/agpl-3.0.en.html)
  7. * @author Yidong Wang <yidong@cnezsoft.com>
  8. * @package compile
  9. * @version $Id$
  10. * @link https://www.zentao.net
  11. * @property jobModel $job
  12. */
  13. class compileModel extends model
  14. {
  15. /**
  16. * 判断按钮是否可点击。
  17. * Judge an action is clickable or not.
  18. *
  19. * @param object $compile
  20. * @param string $action
  21. * @static
  22. * @access public
  23. * @return bool
  24. */
  25. public static function isClickable($compile, $action)
  26. {
  27. if($action == 'result') return !empty($compile->testtask);
  28. return true;
  29. }
  30. /**
  31. * Get by id
  32. *
  33. * @param int $buildID
  34. * @access public
  35. * @return object|false
  36. */
  37. public function getByID($buildID)
  38. {
  39. return $this->dao->select('*')->from(TABLE_COMPILE)->where('id')->eq($buildID)->fetch();
  40. }
  41. /**
  42. * Get build list.
  43. *
  44. * @param int $repoID
  45. * @param int $jobID
  46. * @param string $browseType
  47. * @param int $queryID
  48. * @param string $orderBy
  49. * @param object $pager
  50. * @access public
  51. * @return array
  52. */
  53. public function getList($repoID, $jobID, $browseType = '', $queryID = 0, $orderBy = 'id_desc', $pager = null)
  54. {
  55. $compileQuery = '';
  56. if($browseType == 'bySearch')
  57. {
  58. $query = $this->loadModel('search')->getQuery($queryID);
  59. if($query)
  60. {
  61. $this->session->set('compileQuery', $query->sql);
  62. $this->session->set('compileForm', $query->form);
  63. }
  64. elseif(!$this->session->compileQuery)
  65. {
  66. $this->session->set('compileQuery', ' 1 = 1');
  67. }
  68. $compileQuery = $this->session->compileQuery;
  69. $compileQuery = preg_replace('/`(\w+)`/', 't1.`$1`', $compileQuery);
  70. $compileQuery = preg_replace('/t1.`(engine|repo|triggerType)`/', 't2.`$1`', $compileQuery);
  71. $this->session->set('compileQueryCondition', $compileQuery, $this->app->tab);
  72. $this->session->set('compileOnlyCondition', true, $this->app->tab);
  73. }
  74. if(strpos($orderBy, 'id') === false) $orderBy .= ', id_desc';
  75. return $this->dao->select('t1.id, t1.branch, t1.name, t1.job, t1.status, t1.createdDate, t1.testtask, t2.pipeline, t2.triggerType, t2.svnDir, t2.comment, t2.atDay, t2.atTime, t2.engine, t2.triggerActions, t3.name as repoName, t4.name as jenkinsName')->from(TABLE_COMPILE)->alias('t1')
  76. ->leftJoin(TABLE_JOB)->alias('t2')->on('t1.job=t2.id')
  77. ->leftJoin(TABLE_REPO)->alias('t3')->on('t2.repo=t3.id')
  78. ->leftJoin(TABLE_PIPELINE)->alias('t4')->on('t2.server=t4.id')
  79. ->where('t1.deleted')->eq('0')
  80. ->andWhere('t1.job')->ne('0')
  81. ->beginIF(!empty($repoID))->andWhere('t3.id')->eq($repoID)->fi()
  82. ->beginIF(!empty($jobID))->andWhere('t1.job')->eq($jobID)->fi()
  83. ->beginIF($compileQuery)->andWhere($compileQuery)->fi()
  84. ->orderBy($orderBy)
  85. ->page($pager)
  86. ->fetchAll('id');
  87. }
  88. /**
  89. * Get list by jobID.
  90. *
  91. * @param int $jobID
  92. * @return array
  93. */
  94. public function getListByJobID($jobID)
  95. {
  96. return $this->dao->select('id, name, status')->from(TABLE_COMPILE)
  97. ->where('deleted')->eq('0')
  98. ->andWhere('job')->ne('0')
  99. ->beginIF(!empty($jobID))->andWhere('job')->eq($jobID)->fi()
  100. ->orderBy('id_desc')
  101. ->fetchAll('id');
  102. }
  103. /**
  104. * Get unexecuted list.
  105. *
  106. * @access public
  107. * @return array
  108. */
  109. public function getUnexecutedList()
  110. {
  111. return $this->dao->select('*')->from(TABLE_COMPILE)->where('status')->eq('')->andWhere('deleted')->eq('0')->fetchAll();
  112. }
  113. /**
  114. * Get last result.
  115. *
  116. * @param int $jobID
  117. * @access public
  118. * @return object|false
  119. */
  120. public function getLastResult($jobID)
  121. {
  122. return $this->dao->select('*')->from(TABLE_COMPILE)->where('job')->eq($jobID)->andWhere('status')->ne('')->orderBy('createdDate_desc')->limit(1)->fetch();
  123. }
  124. /**
  125. * Get success jobs by job id list.
  126. *
  127. * @param array $jobIDList
  128. * @access public
  129. * @return array
  130. */
  131. public function getSuccessJobs($jobIDList)
  132. {
  133. return $this->dao->select('job')->from(TABLE_COMPILE)
  134. ->where('job')->in($jobIDList)
  135. ->andWhere('status')->eq('success')
  136. ->fetchPairs();
  137. }
  138. /**
  139. * Get build url.
  140. *
  141. * @param object $job
  142. * @access public
  143. * @return object
  144. */
  145. public function getBuildUrl($job)
  146. {
  147. $url = new stdclass();
  148. $url->userPWD = $this->loadModel('jenkins')->getApiUserPWD($job);
  149. $urlPrefix = $this->compileTao->getJenkinsUrlPrefix($job->url, $job->pipeline);
  150. $detailUrl = $urlPrefix . 'api/json';
  151. $hasParameterizedBuild = $this->loadModel('job')->checkParameterizedBuild($detailUrl, $url->userPWD);
  152. $buildInterface = $hasParameterizedBuild ? 'buildWithParameters' : 'build';
  153. $url->url = "{$urlPrefix}{$buildInterface}/api/json";
  154. return $url;
  155. }
  156. /**
  157. * Get compile logs.
  158. *
  159. * @param object $job
  160. * @param object $compile
  161. * @access public
  162. * @return string
  163. */
  164. public function getLogs($job, $compile)
  165. {
  166. $logs = '';
  167. /* Get jobs by pipeline. */
  168. $pipeline = json_decode($job->pipeline);
  169. if($job->engine == 'jenkins')
  170. {
  171. $jenkins = $this->loadModel('pipeline')->getByID($job->server);
  172. $userPWD = $this->loadModel('jenkins')->getApiUserPWD($jenkins);
  173. $urlPrefix = $this->compileTao->getJenkinsUrlPrefix($jenkins->url, $job->pipeline);
  174. $infoUrl = $urlPrefix . sprintf('api/xml?tree=builds[id,number,queueId]&xpath=//build[queueId=%s]', $compile->queue);
  175. $result = common::http($infoUrl, '', array(CURLOPT_USERPWD => $userPWD), array(), 'data', 'POST', 30, true);
  176. /* Check error. */
  177. $httpCode = $result[1];
  178. if($httpCode == 404) return '';
  179. $response = $result['body'];
  180. if($response)
  181. {
  182. $buildInfo = simplexml_load_string($response);
  183. $buildNumber = $buildInfo->number;
  184. if(empty($buildNumber)) return '';
  185. $logUrl = sprintf($urlPrefix . '%s/consoleText', $buildNumber);
  186. $logs = common::http($logUrl, '', array(CURLOPT_USERPWD => $userPWD));
  187. $this->dao->update(TABLE_COMPILE)->set('logs')->eq($logs)->where('id')->eq($compile->id)->exec();
  188. }
  189. }
  190. else
  191. {
  192. $projectID = isset($pipeline->project) ? $pipeline->project : 0;
  193. $jobs = $this->loadModel('gitlab')->apiGetJobs($job->server, (int)$projectID, $compile->queue);
  194. $this->loadModel('ci');
  195. foreach($jobs as $gitlabJob)
  196. {
  197. if(!is_object($gitlabJob)) continue;
  198. if(empty($gitlabJob->duration)) $gitlabJob->duration = '-';
  199. $logs .= "<font style='font-weight:bold'>&gt;&gt;&gt; Job: $gitlabJob->name, Stage: $gitlabJob->stage, Status: $gitlabJob->status, Duration: $gitlabJob->duration Sec\r\n </font>";
  200. $logs .= "Job URL: <a href=\"$gitlabJob->web_url\" target='_blank'>$gitlabJob->web_url</a> \r\n";
  201. $logs .= $this->ci->transformAnsiToHtml($this->gitlab->apiGetJobLog($job->server, (int)$projectID, $gitlabJob->id));
  202. }
  203. }
  204. if(!empty($logs)) $this->dao->update(TABLE_COMPILE)->set('logs')->eq($logs)->where('id')->eq($compile->id)->exec();
  205. return $logs;
  206. }
  207. /**
  208. * Save build by job
  209. *
  210. * @param int $jobID
  211. * @param string $data
  212. * @param string $type
  213. * @access public
  214. * @return int|false
  215. */
  216. public function createByJob($jobID, $data = '', $type = 'tag')
  217. {
  218. $job = $this->dao->select('id,name')->from(TABLE_JOB)->where('id')->eq($jobID)->fetch();
  219. if(!$job) return false;
  220. $build = new stdClass();
  221. $build->job = $job->id;
  222. $build->name = $job->name;
  223. if($type) $build->$type = $data;
  224. $build->createdBy = $this->app->user ? $this->app->user->account : 'system';
  225. $build->createdDate = helper::now();
  226. $this->dao->insert(TABLE_COMPILE)->data($build)->exec();
  227. return $this->dao->lastInsertId();
  228. }
  229. /**
  230. * Sync compiles.
  231. *
  232. * @param int $repoID
  233. * @param int $repoID
  234. * @access public
  235. * @return bool
  236. * @param int $jobID
  237. */
  238. public function syncCompile($repoID = 0, $jobID = 0)
  239. {
  240. if($jobID)
  241. {
  242. $jobList[$jobID] = $this->loadModel('job')->getByID($jobID);
  243. }
  244. else
  245. {
  246. $jobList = $this->loadModel('job')->getList($repoID);
  247. }
  248. $servers = $this->loadModel('pipeline')->getList('');
  249. foreach($jobList as $job)
  250. {
  251. $server = zget($servers, $job->server);
  252. $method = "sync{$job->engine}BuildList";
  253. $this->$method($server, $job);
  254. $this->compileTao->updateJobLastSyncDate($job->id, helper::now());
  255. }
  256. return !dao::isError();
  257. }
  258. /**
  259. * Sync jenkins build list.
  260. *
  261. * @param object $jenkins
  262. * @param object $job
  263. * @access public
  264. * @return bool
  265. */
  266. public function syncJenkinsBuildList($jenkins, $job)
  267. {
  268. if(empty($jenkins->account)) return false;
  269. $userPWD = $this->loadModel('jenkins')->getApiUserPWD($jenkins);
  270. /* Get build list by API. */
  271. $urlPrefix = $this->compileTao->getJenkinsUrlPrefix($jenkins->url, $job->pipeline);
  272. $url = $urlPrefix . 'api/json?tree=builds[id,number,result,queueId,timestamp]';
  273. $response = common::http($url, '', array(CURLOPT_USERPWD => $userPWD));
  274. if(!$response) return false;
  275. $jobInfo = json_decode($response);
  276. if(empty($jobInfo)) return false;
  277. $compilePairs = $this->dao->select('queue,job')->from(TABLE_COMPILE)->where('job')->eq($job->id)->andWhere('queue')->gt(0)->fetchPairs();
  278. foreach($jobInfo->builds as $build)
  279. {
  280. $lastSyncTime = strtotime($job->lastSyncDate);
  281. if($build->timestamp < $lastSyncTime * 1000) break;
  282. if(isset($compilePairs[$build->queueId])) continue;
  283. $this->compileTao->createByBuildInfo($job->name, $job->id, $build, 'jenkins');
  284. }
  285. return !dao::isError();
  286. }
  287. /**
  288. * Sync gitlab build list.
  289. *
  290. * @param object $gitlab
  291. * @param object $job
  292. * @access public
  293. * @return bool
  294. */
  295. public function syncGitlabBuildList($gitlab, $job)
  296. {
  297. if(empty($gitlab->id)) return false;
  298. $pipeline = json_decode($job->pipeline);
  299. $projectID = isset($pipeline->project) ? $pipeline->project : '';
  300. $ref = isset($pipeline->reference) ? $pipeline->reference : '';
  301. $url = sprintf($this->loadModel('gitlab')->getApiRoot($gitlab->id, false), "/projects/{$projectID}/pipelines");
  302. /* Get build list by API. */
  303. for($page = 1; true; $page++)
  304. {
  305. $param = $job->lastSyncDate ? '&updated_after=' . date('YYYY-MM-DDThh:mm:ssZ', strtotime($job->lastSyncDate)) : '';
  306. $builds = json_decode(commonModel::http($url . "&ref={$ref}&order_by=id&sort=asc&page={$page}&per_page=100" . $param));
  307. if(!is_array($builds)) break;
  308. if(!empty($builds))
  309. {
  310. $queueIDList = array();
  311. foreach($builds as $build) $queueIDList[] = $build->id;
  312. $compilePairs = $this->dao->select('queue,job')->from(TABLE_COMPILE)->where('job')->eq($job->id)->andWhere('queue')->in($queueIDList)->fetchPairs();
  313. foreach($builds as $build)
  314. {
  315. if(isset($compilePairs[$build->id])) continue;
  316. $this->compileTao->createByBuildInfo($job->name, $job->id, $build, 'gitlab');
  317. }
  318. }
  319. if(count($builds) < 100) break;
  320. }
  321. return !dao::isError();
  322. }
  323. /**
  324. * Execute compile
  325. *
  326. * @param object $compile
  327. * @access public
  328. * @return bool
  329. */
  330. public function exec($compile)
  331. {
  332. $job = $this->dao->select('t1.id,t1.name,t1.repo,t1.engine,t1.product,t1.pipeline,t2.name as jenkinsName,t2.url,t2.account,t2.token,t2.password,t1.triggerType,t1.customParam,t1.server,t1.lastTag')
  333. ->from(TABLE_JOB)->alias('t1')
  334. ->leftJoin(TABLE_PIPELINE)->alias('t2')->on('t1.server=t2.id')
  335. ->where('t1.id')->eq($compile->job)
  336. ->fetch();
  337. if(!$job) return false;
  338. $compileID = $compile->id;
  339. $repo = $this->loadModel('repo')->getByID($job->repo);
  340. $this->loadModel('job');
  341. if(!empty($compile->tag))
  342. {
  343. $job->lastTag = $compile->tag;
  344. $this->job->updateLastTag($job->id, $compile->tag);
  345. $this->dao->update(TABLE_COMPILE)->set('tag')->eq($compile->tag)->where('id')->eq($compile->id)->exec();
  346. }
  347. $method = 'exec' . ucfirst($job->engine) . 'Pipeline';
  348. if(!method_exists($this->job, $method)) return false;
  349. $result = $this->job->$method($job, $repo, $compileID);
  350. if(dao::isError()) dao::getError();
  351. $result->updateDate = helper::now();
  352. $this->dao->update(TABLE_COMPILE)->data($result)->where('id')->eq($compileID)->exec();
  353. $this->dao->update(TABLE_JOB)
  354. ->set('lastStatus')->eq($result->status)
  355. ->set('lastExec')->eq($compile->updateDate ? $compile->updateDate : helper::now())
  356. ->where('id')->eq($job->id)
  357. ->exec();
  358. return !dao::isError();
  359. }
  360. }