dev.php 8.4 KB

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