Start.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. system("cp -Rf /workspace/projects/docker-test {$directory}");
  154. system("cp -Rf /workspace/projects/proginn-user {$directory}");
  155. system("cp -Rf /workspace/projects/proginn-bituni {$directory}");
  156. system("cp -Rf /workspace/projects/proginn-child {$directory}");
  157. // 创建日志相关目录
  158. mkdir($directory . '/log/pm2', 0777, true); //
  159. mkdir($directory . '/log/proginn_cache', 0777, true); //
  160. // 配置存放目录
  161. mkdir($directory . '/config', 0777, true); //
  162. // yml 文件
  163. $template = file_get_contents(ROOT_DIR . '/dockerfile/template.yml');
  164. $template = str_replace('<containerName>', $name, $template);
  165. $template = str_replace('<ip>', $ipv4, $template);
  166. $template = str_replace('<proginn-branch>', $proginnBranch, $template);
  167. $template = str_replace('<rooter-branch>', $rooterBranch, $template);
  168. $template = str_replace('<proginn-frontend-branch>', $proginnFrontendBranch, $template);
  169. $template = str_replace('<domain>', $domain, $template);
  170. $template = str_replace('<fullDomain>', $fullDomain, $template);
  171. file_put_contents($directory . '/config/docker.yml', $template);
  172. // nginx 配置
  173. $proxy = file_get_contents(ROOT_DIR . '/config/nginx/template/proxy.nginx.conf');
  174. $proxy = str_replace('{{domain}}', $domain, $proxy);
  175. $proxy = str_replace('{{ip}}', $ipv4, $proxy);
  176. file_put_contents("/workspace/commonContainers/nginx/conf.d/{$name}.conf", $proxy);
  177. $proginn = file_get_contents(ROOT_DIR . '/config/nginx/template/proginn.nginx.conf');
  178. $proginn = str_replace('{{domain}}', $domain, $proginn);
  179. $proginn = str_replace('{{ip}}', $ipv4, $proginn);
  180. file_put_contents("{$directory}/config/nginx.conf", $proginn);
  181. $log = file_get_contents(ROOT_DIR . '/config/logrotate/log.conf');
  182. $log = str_replace('{{containerName}}', $name, $log);
  183. file_put_contents($directory . '/config/logrotate.conf', $log);
  184. system("sudo cp -f {$directory}/config/logrotate.conf /etc/logrotate.d/{$name}");
  185. // 写入项目变量 Found orphan containers
  186. file_put_contents($directory . '/config/.env', "COMPOSE_PROJECT_NAME={$name}");
  187. // 启动容器
  188. system("docker-compose -p {$name} -f {$directory}/config/docker.yml up -d");
  189. // 重载Nginx
  190. system("docker exec nginx nginx -s reload");
  191. $this->getConnection()->query('commit');
  192. } catch (\Throwable $e) {
  193. echo "exception:" . $e->__toString() . "\n";
  194. $this->getConnection()->query('rollback');
  195. if (file_exists($directory . '/config/docker.yml')) {
  196. system("docker-compose -p {$name} -f {$directory}/config/docker.yml rm -s -f");
  197. }
  198. $redis = $this->getRedis();
  199. $lockKey = static::IP_LOCK_KEY . $ip;
  200. $redis->del($lockKey);
  201. // 容器存储目录
  202. $directory = $this->containersBasePath . $name;
  203. system("sudo rm -rf {$directory}");
  204. system("rm -f /workspace/commonContainers/nginx/conf.d/{$name}.conf");
  205. system("docker exec nginx nginx -s reload");
  206. system("sudo rm -f /etc/logrotate.d/{$name}");
  207. }
  208. }
  209. protected function remove($name)
  210. {
  211. $db = $this->getConnection();
  212. $row = $db->get('sites', '*', [
  213. 'name' => $name,
  214. ]);
  215. if (empty($row)) {
  216. echo "删除失败,容器:{$name}不存在,请确认。\n";
  217. return;
  218. }
  219. $this->getConnection()->query('start transaction');
  220. try {
  221. // 容器存储目录
  222. $directory = $this->containersBasePath . $name;
  223. $db->delete('sites', [
  224. 'name' => $name,
  225. ]);
  226. if (file_exists($directory . '/config/docker.yml')) {
  227. system("docker-compose -p {$name} -f {$directory}/config/docker.yml rm -s -f");
  228. }
  229. // 容器存储目录
  230. $directory = $this->containersBasePath . $name;
  231. system("sudo rm -rf {$directory}");
  232. system("rm -f /workspace/commonContainers/nginx/conf.d/{$name}.conf");
  233. system("docker exec nginx nginx -s reload");
  234. $redis = $this->getRedis();
  235. $lockKey = static::IP_LOCK_KEY . $row['ip'];
  236. $redis->del($lockKey);
  237. $this->getConnection()->query('commit');
  238. } catch (\Throwable $e) {
  239. echo "exception:" . $e->__toString() . "\n";
  240. $this->getConnection()->query('rollback');
  241. }
  242. }
  243. protected function getIp()
  244. {
  245. $ip = $this->startIP;
  246. $redis = $this->getRedis();
  247. while (true) {
  248. $ip++;
  249. $lockKey = static::IP_LOCK_KEY . $ip;
  250. $lock = $redis->setnx($lockKey, $ip);
  251. if ($lock) {
  252. break;
  253. }
  254. }
  255. return $ip;
  256. }
  257. protected function parseArgs($argv)
  258. {
  259. unset($argv[0]);
  260. $params = [];
  261. foreach ($argv as $i => $arg) {
  262. $arg = explode('=', $arg);
  263. $key = trim($arg[0], "-");
  264. $val = $arg[1] ?? true;
  265. $params[$key] = $val;
  266. }
  267. return $params;
  268. }
  269. protected function getRedis()
  270. {
  271. if (static::$redis === null) {
  272. static::$redis = new Redis();
  273. static::$redis->connect(Config::REDIS_HOST, Config::REDIS_PORT, 3);
  274. static::$redis->auth(Config::REDIS_PASS);
  275. }
  276. return static::$redis;
  277. }
  278. /**
  279. * @return Medoo
  280. */
  281. protected function getConnection()
  282. {
  283. if (static::$connection === null) {
  284. static::$connection = new Medoo([
  285. 'database_type' => 'mysql',
  286. 'database_name' => Config::DB_NAME,
  287. 'server' => Config::DB_HOST,
  288. 'username' => Config::DB_USER,
  289. 'password' => Config::DB_PASS,
  290. 'charset' => Config::DB_CHAR,
  291. 'port' => Config::DB_PORT,
  292. 'prefix' => '',
  293. 'logging' => true,
  294. ]);
  295. }
  296. return static::$connection;
  297. }
  298. }