Start.php 12 KB

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