dev.php 8.4 KB

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