Start.php 8.8 KB

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