Start.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. <?php
  2. namespace Proginn;
  3. use Exception;
  4. use Medoo\Medoo;
  5. use Proginn\Config;
  6. use Redis;
  7. class Start
  8. {
  9. const IP_LOCK_KEY = 'docker:ip:';
  10. /**
  11. * 数据库链接
  12. *
  13. * @var Medoo $connection
  14. *
  15. */
  16. protected static $connection;
  17. /**
  18. * 数据库链接
  19. *
  20. * @var Redis $redis
  21. *
  22. */
  23. protected static $redis;
  24. protected $startIP = 180936414; // 10.200.222.222
  25. protected $domainSuffix = '.test.proginn.com';
  26. protected $containersBasePath = '/workspace/containers/';
  27. public function __construct($argv)
  28. {
  29. // 防止git仓库有人改了文件权限,容器里面shell脚本无法执行
  30. system("sudo chmod +x " . ROOT_DIR . '/shell/*');
  31. $params = $this->parseArgs($argv);
  32. $action = $params['action'];
  33. $proginnBranch = $params['proginn-branch'] ?? 'master';
  34. $rooterBranch = $params['rooter-branch'] ?? 'master';
  35. $proginnFrontendBranch = $params['proginn-frontend-branch'] ?? 'master';
  36. $name = $params['name'];
  37. switch ($action) {
  38. case 'start':
  39. $this->start($name, $proginnBranch, $rooterBranch, $proginnFrontendBranch);
  40. break;
  41. case 'remove':
  42. $this->remove($name);
  43. break;
  44. default:
  45. echo "Usage: php index.php --action=start|remove --name=mydev --proginn-branch=dev --rooter-branch=dev --proginn-frontend-branch dev\n";
  46. break;
  47. }
  48. }
  49. public function start($name, $proginnBranch, $rooterBranch, $proginnFrontendBranch)
  50. {
  51. if (preg_match('/[^a-zA-Z0-9_]+/', $name)) {
  52. echo "创建失败,容器名:{$name}只能字母、数字及下划线组成。\n";
  53. return;
  54. }
  55. if (preg_match('/[^a-zA-Z0-9_]+/', $proginnBranch)) {
  56. echo "创建失败,proginn分支名:{$name}只能字母、数字及下划线组成。\n";
  57. return;
  58. }
  59. if (preg_match('/[^a-zA-Z0-9_]+/', $rooterBranch)) {
  60. echo "创建失败,rooter分支名:{$name}只能字母、数字及下划线组成。\n";
  61. return;
  62. }
  63. if (preg_match('/[^a-zA-Z0-9_]+/', $proginnFrontendBranch)) {
  64. echo "创建失败,proginn-frontend分支名:{$name}只能字母、数字及下划线组成。\n";
  65. return;
  66. }
  67. $db = $this->getConnection();
  68. $row = $db->get('sites', '*', [
  69. 'name' => $name,
  70. ]);
  71. if (!empty($row)) {
  72. echo "创建失败,容器:{$name}已经存在,请确认。\n";
  73. return;
  74. }
  75. $ip = $this->getIp();
  76. $ipv4 = long2ip($ip);
  77. $domain = $name;
  78. $fullDomain = $name . $this->domainSuffix;
  79. $this->getConnection()->query('start transaction');
  80. try {
  81. $id = $this->getConnection()->insert('sites', [
  82. 'proginn_branch' => $proginnBranch,
  83. 'domain' => $domain,
  84. 'ip' => $ip,
  85. 'ipv4' => $ipv4,
  86. 'created_at' => time(),
  87. 'name' => $name,
  88. 'rooter_branch' => $rooterBranch,
  89. 'proginn_frontend_branch' => $proginnFrontendBranch,
  90. 'full_domain' => $fullDomain,
  91. ]);
  92. if (!$id) {
  93. throw new Exception('创建数据库记录失败');
  94. }
  95. // 容器存储目录
  96. $directory = $this->containersBasePath . $name;
  97. // 创建容器存储目录
  98. mkdir($directory, 0777, true);
  99. // 拷贝项目
  100. system("cp -Rf /workspace/projects/proginn {$directory}");
  101. system("cp -Rf /workspace/projects/proginn-frontend {$directory}");
  102. system("cp -Rf /workspace/projects/boss {$directory}");
  103. system("cp -Rf /workspace/projects/festival {$directory}");
  104. // 创建日志相关目录
  105. mkdir($directory . '/log/pm2', 0777, true); //
  106. mkdir($directory . '/log/proginn_cache', 0777, true); //
  107. // 配置存放目录
  108. mkdir($directory . '/config', 0777, true); //
  109. // yml 文件
  110. $template = file_get_contents(ROOT_DIR . '/dockerfile/template.yml');
  111. $template = str_replace('<containerName>', $name, $template);
  112. $template = str_replace('<ip>', $ipv4, $template);
  113. $template = str_replace('<proginn-branch>', $proginnBranch, $template);
  114. $template = str_replace('<rooter-branch>', $rooterBranch, $template);
  115. $template = str_replace('<proginn-frontend-branch>', $proginnFrontendBranch, $template);
  116. $template = str_replace('<domain>', $fullDomain, $template);
  117. file_put_contents($directory . '/config/docker.yml', $template);
  118. // nginx 配置
  119. $proxy = file_get_contents(ROOT_DIR . '/config/nginx/template/proxy.nginx.conf');
  120. $proxy = str_replace('{{domain}}', $domain, $proxy);
  121. $proxy = str_replace('{{ip}}', $ipv4, $proxy);
  122. file_put_contents("/workspace/commonContainers/nginx/conf.d/{$name}.conf", $proxy);
  123. $proginn = file_get_contents(ROOT_DIR . '/config/nginx/template/proginn.nginx.conf');
  124. $proginn = str_replace('{{domain}}', $domain, $proginn);
  125. $proginn = str_replace('{{ip}}', $ipv4, $proginn);
  126. file_put_contents("{$directory}/config/nginx.conf", $proginn);
  127. $log = file_get_contents(ROOT_DIR . '/config/logrotate/log.conf');
  128. $log = str_replace('{{containerName}}', $name, $log);
  129. file_put_contents($directory . '/config/logrotate.conf', $log);
  130. system("sudo cp -f {$directory}/config/logrotate.conf /etc/logrotate.d/{$name}");
  131. // 启动容器
  132. system("docker-compose -f {$directory}/config/docker.yml up -d");
  133. // 重载Nginx
  134. system("docker exec nginx nginx -s reload");
  135. $this->getConnection()->query('commit');
  136. } catch (\Throwable $e) {
  137. echo "exception:" . $e->__toString() . "\n";
  138. $this->getConnection()->query('rollback');
  139. if (file_exists($directory . '/config/docker.yml')) {
  140. system("docker-compose -f {$directory}/config/docker.yml rm -s -f");
  141. }
  142. // 容器存储目录
  143. $directory = $this->containersBasePath . $name;
  144. system("sudo rm -rf {$directory}");
  145. system("rm -f /workspace/commonContainers/nginx/conf.d/{$name}.conf");
  146. system("docker exec nginx nginx -s reload");
  147. system("sudo rm -f /etc/logrotate.d/{$name}");
  148. }
  149. }
  150. protected function remove($name)
  151. {
  152. $db = $this->getConnection();
  153. $row = $db->get('sites', '*', [
  154. 'name' => $name,
  155. ]);
  156. if (empty($row)) {
  157. echo "删除失败,容器:{$name}不存在,请确认。\n";
  158. return;
  159. }
  160. $this->getConnection()->query('start transaction');
  161. try {
  162. // 容器存储目录
  163. $directory = $this->containersBasePath . $name;
  164. $db->delete('sites', [
  165. 'name' => $name,
  166. ]);
  167. if (file_exists($directory . '/config/docker.yml')) {
  168. system("docker-compose -f {$directory}/config/docker.yml rm -s -f");
  169. }
  170. // 容器存储目录
  171. $directory = $this->containersBasePath . $name;
  172. system("sudo rm -rf {$directory}");
  173. system("rm -f /workspace/commonContainers/nginx/conf.d/{$name}.conf");
  174. system("docker exec nginx nginx -s reload");
  175. $redis = $this->getRedis();
  176. $lockKey = static::IP_LOCK_KEY . $row['ip'];
  177. $redis->del($lockKey);
  178. $this->getConnection()->query('commit');
  179. } catch (\Throwable $e) {
  180. echo "exception:" . $e->__toString() . "\n";
  181. $this->getConnection()->query('rollback');
  182. }
  183. }
  184. protected function getIp()
  185. {
  186. $ip = $this->startIP;
  187. $redis = $this->getRedis();
  188. while (true) {
  189. $ip++;
  190. $lockKey = static::IP_LOCK_KEY . $ip;
  191. $lock = $redis->setnx($lockKey, $ip);
  192. if ($lock) {
  193. break;
  194. }
  195. }
  196. return $ip;
  197. }
  198. protected function parseArgs($argv)
  199. {
  200. unset($argv[0]);
  201. $params = [];
  202. foreach ($argv as $i => $arg) {
  203. $arg = explode('=', $arg);
  204. $key = trim($arg[0], "-");
  205. $val = $arg[1] ?? true;
  206. $params[$key] = $val;
  207. }
  208. return $params;
  209. }
  210. protected function getRedis()
  211. {
  212. if (static::$redis === null) {
  213. static::$redis = new Redis();
  214. static::$redis->connect(Config::REDIS_HOST, Config::REDIS_PORT, 3);
  215. static::$redis->auth(Config::REDIS_PASS);
  216. }
  217. return static::$redis;
  218. }
  219. /**
  220. * @return Medoo
  221. */
  222. protected function getConnection()
  223. {
  224. if (static::$connection === null) {
  225. static::$connection = new Medoo([
  226. 'database_type' => 'mysql',
  227. 'database_name' => Config::DB_NAME,
  228. 'server' => Config::DB_HOST,
  229. 'username' => Config::DB_USER,
  230. 'password' => Config::DB_PASS,
  231. 'charset' => Config::DB_CHAR,
  232. 'port' => Config::DB_PORT,
  233. 'prefix' => '',
  234. 'logging' => true,
  235. ]);
  236. }
  237. return static::$connection;
  238. }
  239. }