Start.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. case 'nginx':
  45. $this->nginx($name, $proginnBranch, $rooterBranch, $proginnFrontendBranch);//同步nginx配置,不用每次都重新拉取
  46. break;
  47. default:
  48. echo "Usage: php index.php --action=start|remove --name=mydev --proginn-branch=dev --rooter-branch=dev --proginn-frontend-branch dev\n";
  49. break;
  50. }
  51. }
  52. public function nginx($name, $proginnBranch, $rooterBranch, $proginnFrontendBranch)
  53. {
  54. if (preg_match('/[^a-zA-Z0-9_]+/', $name)) {
  55. echo "创建失败,容器名:{$name}只能字母、数字及下划线组成。\n";
  56. return;
  57. }
  58. if (preg_match('/[^a-zA-Z0-9_]+/', $proginnBranch)) {
  59. echo "创建失败,proginn分支名:{$name}只能字母、数字及下划线组成。\n";
  60. return;
  61. }
  62. if (preg_match('/[^a-zA-Z0-9_]+/', $rooterBranch)) {
  63. echo "创建失败,rooter分支名:{$name}只能字母、数字及下划线组成。\n";
  64. return;
  65. }
  66. if (preg_match('/[^a-zA-Z0-9_]+/', $proginnFrontendBranch)) {
  67. echo "创建失败,proginn-frontend分支名:{$name}只能字母、数字及下划线组成。\n";
  68. return;
  69. }
  70. $db = $this->getConnection();
  71. $row = $db->get('sites', '*', [
  72. 'name' => $name,
  73. ]);
  74. if (empty($row)) {
  75. echo "获取失败,容器:{$name}不存在,请确认。\n";
  76. return;
  77. }
  78. $ip = $this->getIp();
  79. $ipv4 = long2ip($ip);
  80. $domain = $name;
  81. $this->getConnection()->query('start transaction');
  82. try {
  83. // 容器存储目录
  84. $directory = $this->containersBasePath . $name;
  85. // nginx 配置
  86. $proginn = file_get_contents(ROOT_DIR . '/config/nginx/template/proginn.nginx.conf');
  87. $proginn = str_replace('{{domain}}', $domain, $proginn);
  88. $proginn = str_replace('{{ip}}', $ipv4, $proginn);
  89. file_put_contents("{$directory}/config/nginx.conf", $proginn);
  90. // 重载Nginx
  91. system("docker exec nginx nginx -s reload");
  92. $this->getConnection()->query('commit');
  93. } catch (\Throwable $e) {
  94. echo "exception:" . $e->__toString() . "\n";
  95. $this->getConnection()->query('rollback');
  96. }
  97. }
  98. public function start($name, $proginnBranch, $rooterBranch, $proginnFrontendBranch)
  99. {
  100. if (preg_match('/[^a-zA-Z0-9_]+/', $name)) {
  101. echo "创建失败,容器名:{$name}只能字母、数字及下划线组成。\n";
  102. return;
  103. }
  104. if (preg_match('/[^a-zA-Z0-9_]+/', $proginnBranch)) {
  105. echo "创建失败,proginn分支名:{$name}只能字母、数字及下划线组成。\n";
  106. return;
  107. }
  108. if (preg_match('/[^a-zA-Z0-9_]+/', $rooterBranch)) {
  109. echo "创建失败,rooter分支名:{$name}只能字母、数字及下划线组成。\n";
  110. return;
  111. }
  112. if (preg_match('/[^a-zA-Z0-9_]+/', $proginnFrontendBranch)) {
  113. echo "创建失败,proginn-frontend分支名:{$name}只能字母、数字及下划线组成。\n";
  114. return;
  115. }
  116. $db = $this->getConnection();
  117. $row = $db->get('sites', '*', [
  118. 'name' => $name,
  119. ]);
  120. if (!empty($row)) {
  121. echo "创建失败,容器:{$name}已经存在,请确认。\n";
  122. return;
  123. }
  124. $ip = $this->getIp();
  125. $ipv4 = long2ip($ip);
  126. $domain = $name;
  127. $fullDomain = $name . $this->domainSuffix;
  128. $this->getConnection()->query('start transaction');
  129. try {
  130. $id = $this->getConnection()->insert('sites', [
  131. 'proginn_branch' => $proginnBranch,
  132. 'domain' => $domain,
  133. 'ip' => $ip,
  134. 'ipv4' => $ipv4,
  135. 'created_at' => time(),
  136. 'name' => $name,
  137. 'rooter_branch' => $rooterBranch,
  138. 'proginn_frontend_branch' => $proginnFrontendBranch,
  139. 'full_domain' => $fullDomain,
  140. ]);
  141. if (!$id) {
  142. throw new Exception('创建数据库记录失败');
  143. }
  144. // 容器存储目录
  145. $directory = $this->containersBasePath . $name;
  146. // 创建容器存储目录
  147. mkdir($directory, 0777, true);
  148. // 拷贝项目
  149. system("cp -Rf /workspace/projects/proginn {$directory}");
  150. system("cp -Rf /workspace/projects/proginn-frontend {$directory}");
  151. system("cp -Rf /workspace/projects/boss {$directory}");
  152. system("cp -Rf /workspace/projects/festival {$directory}");
  153. // 创建日志相关目录
  154. mkdir($directory . '/log/pm2', 0777, true); //
  155. mkdir($directory . '/log/proginn_cache', 0777, true); //
  156. // 配置存放目录
  157. mkdir($directory . '/config', 0777, true); //
  158. // yml 文件
  159. $template = file_get_contents(ROOT_DIR . '/dockerfile/template.yml');
  160. $template = str_replace('<containerName>', $name, $template);
  161. $template = str_replace('<ip>', $ipv4, $template);
  162. $template = str_replace('<proginn-branch>', $proginnBranch, $template);
  163. $template = str_replace('<rooter-branch>', $rooterBranch, $template);
  164. $template = str_replace('<proginn-frontend-branch>', $proginnFrontendBranch, $template);
  165. $template = str_replace('<domain>', $domain, $template);
  166. $template = str_replace('<fullDomain>', $fullDomain, $template);
  167. file_put_contents($directory . '/config/docker.yml', $template);
  168. // nginx 配置
  169. $proxy = file_get_contents(ROOT_DIR . '/config/nginx/template/proxy.nginx.conf');
  170. $proxy = str_replace('{{domain}}', $domain, $proxy);
  171. $proxy = str_replace('{{ip}}', $ipv4, $proxy);
  172. file_put_contents("/workspace/commonContainers/nginx/conf.d/{$name}.conf", $proxy);
  173. $proginn = file_get_contents(ROOT_DIR . '/config/nginx/template/proginn.nginx.conf');
  174. $proginn = str_replace('{{domain}}', $domain, $proginn);
  175. $proginn = str_replace('{{ip}}', $ipv4, $proginn);
  176. file_put_contents("{$directory}/config/nginx.conf", $proginn);
  177. $log = file_get_contents(ROOT_DIR . '/config/logrotate/log.conf');
  178. $log = str_replace('{{containerName}}', $name, $log);
  179. file_put_contents($directory . '/config/logrotate.conf', $log);
  180. system("sudo cp -f {$directory}/config/logrotate.conf /etc/logrotate.d/{$name}");
  181. // 写入项目变量 Found orphan containers
  182. file_put_contents($directory . '/config/.env', "COMPOSE_PROJECT_NAME={$name}");
  183. // 启动容器
  184. system("docker-compose -p {$name} -f {$directory}/config/docker.yml up -d");
  185. // 重载Nginx
  186. system("docker exec nginx nginx -s reload");
  187. $this->getConnection()->query('commit');
  188. } catch (\Throwable $e) {
  189. echo "exception:" . $e->__toString() . "\n";
  190. $this->getConnection()->query('rollback');
  191. if (file_exists($directory . '/config/docker.yml')) {
  192. system("docker-compose -p {$name} -f {$directory}/config/docker.yml rm -s -f");
  193. }
  194. $redis = $this->getRedis();
  195. $lockKey = static::IP_LOCK_KEY . $ip;
  196. $redis->del($lockKey);
  197. // 容器存储目录
  198. $directory = $this->containersBasePath . $name;
  199. system("sudo rm -rf {$directory}");
  200. system("rm -f /workspace/commonContainers/nginx/conf.d/{$name}.conf");
  201. system("docker exec nginx nginx -s reload");
  202. system("sudo rm -f /etc/logrotate.d/{$name}");
  203. }
  204. }
  205. protected function remove($name)
  206. {
  207. $db = $this->getConnection();
  208. $row = $db->get('sites', '*', [
  209. 'name' => $name,
  210. ]);
  211. if (empty($row)) {
  212. echo "删除失败,容器:{$name}不存在,请确认。\n";
  213. return;
  214. }
  215. $this->getConnection()->query('start transaction');
  216. try {
  217. // 容器存储目录
  218. $directory = $this->containersBasePath . $name;
  219. $db->delete('sites', [
  220. 'name' => $name,
  221. ]);
  222. if (file_exists($directory . '/config/docker.yml')) {
  223. system("docker-compose -p {$name} -f {$directory}/config/docker.yml rm -s -f");
  224. }
  225. // 容器存储目录
  226. $directory = $this->containersBasePath . $name;
  227. system("sudo rm -rf {$directory}");
  228. system("rm -f /workspace/commonContainers/nginx/conf.d/{$name}.conf");
  229. system("docker exec nginx nginx -s reload");
  230. $redis = $this->getRedis();
  231. $lockKey = static::IP_LOCK_KEY . $row['ip'];
  232. $redis->del($lockKey);
  233. $this->getConnection()->query('commit');
  234. } catch (\Throwable $e) {
  235. echo "exception:" . $e->__toString() . "\n";
  236. $this->getConnection()->query('rollback');
  237. }
  238. }
  239. protected function getIp()
  240. {
  241. $ip = $this->startIP;
  242. $redis = $this->getRedis();
  243. while (true) {
  244. $ip++;
  245. $lockKey = static::IP_LOCK_KEY . $ip;
  246. $lock = $redis->setnx($lockKey, $ip);
  247. if ($lock) {
  248. break;
  249. }
  250. }
  251. return $ip;
  252. }
  253. protected function parseArgs($argv)
  254. {
  255. unset($argv[0]);
  256. $params = [];
  257. foreach ($argv as $i => $arg) {
  258. $arg = explode('=', $arg);
  259. $key = trim($arg[0], "-");
  260. $val = $arg[1] ?? true;
  261. $params[$key] = $val;
  262. }
  263. return $params;
  264. }
  265. protected function getRedis()
  266. {
  267. if (static::$redis === null) {
  268. static::$redis = new Redis();
  269. static::$redis->connect(Config::REDIS_HOST, Config::REDIS_PORT, 3);
  270. static::$redis->auth(Config::REDIS_PASS);
  271. }
  272. return static::$redis;
  273. }
  274. /**
  275. * @return Medoo
  276. */
  277. protected function getConnection()
  278. {
  279. if (static::$connection === null) {
  280. static::$connection = new Medoo([
  281. 'database_type' => 'mysql',
  282. 'database_name' => Config::DB_NAME,
  283. 'server' => Config::DB_HOST,
  284. 'username' => Config::DB_USER,
  285. 'password' => Config::DB_PASS,
  286. 'charset' => Config::DB_CHAR,
  287. 'port' => Config::DB_PORT,
  288. 'prefix' => '',
  289. 'logging' => true,
  290. ]);
  291. }
  292. return static::$connection;
  293. }
  294. }