Start.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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>', $domain, $template);
  117. $template = str_replace('<fullDomain>', $fullDomain, $template);
  118. file_put_contents($directory . '/config/docker.yml', $template);
  119. // nginx 配置
  120. $proxy = file_get_contents(ROOT_DIR . '/config/nginx/template/proxy.nginx.conf');
  121. $proxy = str_replace('{{domain}}', $domain, $proxy);
  122. $proxy = str_replace('{{ip}}', $ipv4, $proxy);
  123. file_put_contents("/workspace/commonContainers/nginx/conf.d/{$name}.conf", $proxy);
  124. $proginn = file_get_contents(ROOT_DIR . '/config/nginx/template/proginn.nginx.conf');
  125. $proginn = str_replace('{{domain}}', $domain, $proginn);
  126. $proginn = str_replace('{{ip}}', $ipv4, $proginn);
  127. file_put_contents("{$directory}/config/nginx.conf", $proginn);
  128. $log = file_get_contents(ROOT_DIR . '/config/logrotate/log.conf');
  129. $log = str_replace('{{containerName}}', $name, $log);
  130. file_put_contents($directory . '/config/logrotate.conf', $log);
  131. system("sudo cp -f {$directory}/config/logrotate.conf /etc/logrotate.d/{$name}");
  132. // 写入项目变量 Found orphan containers
  133. file_put_contents($directory . '/config/.env', "COMPOSE_PROJECT_NAME={$name}");
  134. // 启动容器
  135. system("docker-compose -p {$name} -f {$directory}/config/docker.yml up -d");
  136. // 重载Nginx
  137. system("docker exec nginx nginx -s reload");
  138. $this->getConnection()->query('commit');
  139. } catch (\Throwable $e) {
  140. echo "exception:" . $e->__toString() . "\n";
  141. $this->getConnection()->query('rollback');
  142. if (file_exists($directory . '/config/docker.yml')) {
  143. system("docker-compose -p {$name} -f {$directory}/config/docker.yml rm -s -f");
  144. }
  145. $redis = $this->getRedis();
  146. $lockKey = static::IP_LOCK_KEY . $ip;
  147. $redis->del($lockKey);
  148. // 容器存储目录
  149. $directory = $this->containersBasePath . $name;
  150. system("sudo rm -rf {$directory}");
  151. system("rm -f /workspace/commonContainers/nginx/conf.d/{$name}.conf");
  152. system("docker exec nginx nginx -s reload");
  153. system("sudo rm -f /etc/logrotate.d/{$name}");
  154. }
  155. }
  156. protected function remove($name)
  157. {
  158. $db = $this->getConnection();
  159. $row = $db->get('sites', '*', [
  160. 'name' => $name,
  161. ]);
  162. if (empty($row)) {
  163. echo "删除失败,容器:{$name}不存在,请确认。\n";
  164. return;
  165. }
  166. $this->getConnection()->query('start transaction');
  167. try {
  168. // 容器存储目录
  169. $directory = $this->containersBasePath . $name;
  170. $db->delete('sites', [
  171. 'name' => $name,
  172. ]);
  173. if (file_exists($directory . '/config/docker.yml')) {
  174. system("docker-compose -p {$name} -f {$directory}/config/docker.yml rm -s -f");
  175. }
  176. // 容器存储目录
  177. $directory = $this->containersBasePath . $name;
  178. system("sudo rm -rf {$directory}");
  179. system("rm -f /workspace/commonContainers/nginx/conf.d/{$name}.conf");
  180. system("docker exec nginx nginx -s reload");
  181. $redis = $this->getRedis();
  182. $lockKey = static::IP_LOCK_KEY . $row['ip'];
  183. $redis->del($lockKey);
  184. $this->getConnection()->query('commit');
  185. } catch (\Throwable $e) {
  186. echo "exception:" . $e->__toString() . "\n";
  187. $this->getConnection()->query('rollback');
  188. }
  189. }
  190. protected function getIp()
  191. {
  192. $ip = $this->startIP;
  193. $redis = $this->getRedis();
  194. while (true) {
  195. $ip++;
  196. $lockKey = static::IP_LOCK_KEY . $ip;
  197. $lock = $redis->setnx($lockKey, $ip);
  198. if ($lock) {
  199. break;
  200. }
  201. }
  202. return $ip;
  203. }
  204. protected function parseArgs($argv)
  205. {
  206. unset($argv[0]);
  207. $params = [];
  208. foreach ($argv as $i => $arg) {
  209. $arg = explode('=', $arg);
  210. $key = trim($arg[0], "-");
  211. $val = $arg[1] ?? true;
  212. $params[$key] = $val;
  213. }
  214. return $params;
  215. }
  216. protected function getRedis()
  217. {
  218. if (static::$redis === null) {
  219. static::$redis = new Redis();
  220. static::$redis->connect(Config::REDIS_HOST, Config::REDIS_PORT, 3);
  221. static::$redis->auth(Config::REDIS_PASS);
  222. }
  223. return static::$redis;
  224. }
  225. /**
  226. * @return Medoo
  227. */
  228. protected function getConnection()
  229. {
  230. if (static::$connection === null) {
  231. static::$connection = new Medoo([
  232. 'database_type' => 'mysql',
  233. 'database_name' => Config::DB_NAME,
  234. 'server' => Config::DB_HOST,
  235. 'username' => Config::DB_USER,
  236. 'password' => Config::DB_PASS,
  237. 'charset' => Config::DB_CHAR,
  238. 'port' => Config::DB_PORT,
  239. 'prefix' => '',
  240. 'logging' => true,
  241. ]);
  242. }
  243. return static::$connection;
  244. }
  245. }