add backup and admin dist

This commit is contained in:
xiaomlove
2021-05-02 17:24:05 +08:00
parent a46256e019
commit 1b2a2ecf62
54 changed files with 439 additions and 145 deletions
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace App\Console\Commands;
use App\Repositories\ToolRepository;
use Illuminate\Console\Command;
class BackuAll extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'backup:all';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Backup all data, include web root and database';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$rep = new ToolRepository();
$result = $rep->backupAll();
$log = sprintf('[%s], %s, result: %s', REQUEST_ID, __METHOD__, var_export($result, true));
$this->info($log);
do_log($log);
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace App\Console\Commands;
use App\Repositories\ToolRepository;
use Illuminate\Console\Command;
class BackupDatabase extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'backup:database';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Backup database data';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$rep = new ToolRepository();
$result = $rep->backupDatabase();
$log = sprintf('[%s], %s, result: %s', REQUEST_ID, __METHOD__, var_export($result, true));
$this->info($log);
do_log($log);
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace App\Console\Commands;
use App\Repositories\ToolRepository;
use Illuminate\Console\Command;
class BackupWeb extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'backup:web';
/**
* The console command description.
*
* @var string
*/
protected $description = 'BackupWeb webRoot data';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$rep = new ToolRepository();
$result = $rep->backupWebRoot();
$log = sprintf('[%s], %s, result: %s', REQUEST_ID, __METHOD__, var_export($result, true));
$this->info($log);
do_log($log);
}
}
+3 -1
View File
@@ -45,7 +45,9 @@ class ExamAssign extends Command
$end = $this->option('end');
$this->info(sprintf('uid: %s, examId: %s, begin: %s, end: %s', $uid, $examId, $begin, $end));
$result = $examRep->assignToUser($uid, $examId, $begin, $end);
$this->info(sprintf('%s, [assignToUser], result: %s, request_id: %s', __METHOD__, var_export($result, true), REQUEST_ID));
$log = sprintf('[%s], %s, result: %s', REQUEST_ID, __METHOD__, var_export($result, true));
$this->info($log);
do_log($log);
return 0;
}
}
+3 -1
View File
@@ -40,7 +40,9 @@ class ExamAssignCronjob extends Command
{
$examRep = new ExamRepository();
$result = $examRep->cronjonAssign();
$this->info(sprintf('%s, [cronjonAssign], result: %s, request_id: %s', __METHOD__, var_export($result, true), REQUEST_ID));
$log = sprintf('[%s], %s, result: %s', REQUEST_ID, __METHOD__, var_export($result, true));
$this->info($log);
do_log($log);
return 0;
}
}
+3 -1
View File
@@ -42,7 +42,9 @@ class ExamCheckoutCronjob extends Command
$ignoreTimeRange = $this->option('ignore-time-range');
$this->info('ignore-time-range: ' . var_export($ignoreTimeRange, true));
$result = $examRep->cronjobCheckout($ignoreTimeRange);
$this->info(sprintf('%s, [cronjobCheckout], result: %s, request_id: %s', __METHOD__, var_export($result, true), REQUEST_ID));
$log = sprintf('[%s], %s, result: %s', REQUEST_ID, __METHOD__, var_export($result, true));
$this->info($log);
do_log($log);
return 0;
}
}
+9 -7
View File
@@ -46,15 +46,17 @@ class Test extends Command
{
$rep = new ExamRepository();
// $r = $rep->assignToUser(1, 1);
$r = $rep->addProgress(1, 1, [
1 => 25*1024*1024*1024,
2 => 55*3600,
3 => 10*1024*1024*1024,
4 => 1252
]);
dd($r);
// $r = $rep->addProgress(1, 1, [
// 1 => 25*1024*1024*1024,
// 2 => 55*3600,
// 3 => 10*1024*1024*1024,
// 4 => 1252
// ]);
// dd($r);
// $rep->assignCronjob();
// $rep->cronjobCheckout();
$r = DB::select(DB::raw('select version() as info'))[0]->info;
dd($r);
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Controllers;
use App\Repositories\ToolRepository;
use Illuminate\Http\Request;
class ToolController extends Controller
{
private $repository;
public function __construct(ToolRepository $repository)
{
$this->repository = $repository;
}
public function systemInfo()
{
$result = $this->repository->getSystemInfo();
return $this->success($result);
}
}
+2
View File
@@ -29,6 +29,8 @@ class ExamResource extends JsonResource
'indexes_formatted' => $this->formatIndexes($this->resource),
'status' => $this->status,
'status_text' => $this->statusText,
'is_discovered' => $this->is_discovered,
'is_discovered_text' => $this->is_discovered_text,
];
}
+17 -4
View File
@@ -4,7 +4,7 @@ namespace App\Models;
class Exam extends NexusModel
{
protected $fillable = ['name', 'description', 'begin', 'end', 'status', 'filters', 'indexes'];
protected $fillable = ['name', 'description', 'begin', 'end', 'status', 'is_discovered', 'filters', 'indexes'];
public $timestamps = true;
@@ -21,6 +21,14 @@ class Exam extends NexusModel
self::STATUS_DISABLED => ['text' => 'Disabled'],
];
const DISCOVERED_YES = 1;
const DISCOVERED_NO = 0;
public static $discovers = [
self::DISCOVERED_NO => ['text' => 'No'],
self::DISCOVERED_YES => ['text' => 'Yes'],
];
const INDEX_UPLOADED = 1;
const INDEX_SEED_TIME_AVERAGE = 2;
const INDEX_DOWNLOADED = 3;
@@ -28,7 +36,7 @@ class Exam extends NexusModel
public static $indexes = [
self::INDEX_UPLOADED => ['name' => 'Uploaded', 'unit' => 'GB'],
self::INDEX_SEED_TIME_AVERAGE => ['name' => 'Seed Time Average', 'unit' => 'Hour'],
self::INDEX_SEED_TIME_AVERAGE => ['name' => 'Seed time average', 'unit' => 'Hour'],
self::INDEX_DOWNLOADED => ['name' => 'Downloaded', 'unit' => 'GB'],
self::INDEX_BONUS => ['name' => 'Bonus', 'unit' => ''],
];
@@ -37,8 +45,8 @@ class Exam extends NexusModel
const FILTER_USER_REGISTER_TIME_RANGE = 'register_time_range';
public static $filters = [
self::FILTER_USER_CLASS => ['name' => 'User Class'],
self::FILTER_USER_REGISTER_TIME_RANGE => ['name' => 'User Register Time Range'],
self::FILTER_USER_CLASS => ['name' => 'User class'],
self::FILTER_USER_REGISTER_TIME_RANGE => ['name' => 'User register time range'],
];
public function getStatusTextAttribute(): string
@@ -46,4 +54,9 @@ class Exam extends NexusModel
return self::$status[$this->status]['text'] ?? '';
}
public function getIsDiscoveredTextAttribute(): string
{
return self::$discovers[$this->is_discovered]['text'] ?? '';
}
}
+28 -28
View File
@@ -27,9 +27,9 @@ class ExamRepository extends BaseRepository
public function store(array $params)
{
$this->checkIndexes($params);
$valid = $this->listValid();
$valid = $this->listValid(null, Exam::DISCOVERED_YES);
if ($valid->isNotEmpty() && $params['status'] == Exam::STATUS_ENABLED) {
throw new NexusException("Valid exam already exists.");
throw new NexusException("Enabled and discovered exam already exists.");
}
$exam = Exam::query()->create($params);
return $exam;
@@ -38,9 +38,9 @@ class ExamRepository extends BaseRepository
public function update(array $params, $id)
{
$this->checkIndexes($params);
$valid = $this->listValid($id);
$valid = $this->listValid($id, Exam::DISCOVERED_YES);
if ($valid->isNotEmpty() && $params['status'] == Exam::STATUS_ENABLED) {
throw new NexusException("Valid exam already exists.");
throw new NexusException("Enabled and discovered exam already exists.");
}
$exam = Exam::query()->findOrFail($id);
$exam->update($params);
@@ -52,10 +52,18 @@ class ExamRepository extends BaseRepository
if (empty($params['indexes'])) {
throw new \InvalidArgumentException("Require index.");
}
$validIndex = array_filter($params['indexes'], function ($value) {
return isset($value['checked']) && $value['checked']
&& isset($value['require_value']) && $value['require_value'] > 0;
});
$validIndex = [];
foreach ($params['indexes'] as $index) {
if (!isset($index['checked']) || !$index['checked']) {
continue;
}
if (!isset($index['require_value']) || !ctype_digit((string)$index['require_value'])) {
throw new \InvalidArgumentException(sprintf(
'Invalid require value for index: %s.', $index['name']
));
}
$validIndex[] = $index;
}
if (empty($validIndex)) {
throw new \InvalidArgumentException("Require valid index.");
}
@@ -91,7 +99,7 @@ class ExamRepository extends BaseRepository
* @param null $excludeId
* @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
*/
public function listValid($excludeId = null)
public function listValid($excludeId = null, $isDiscovered = null)
{
$now = Carbon::now();
$query = Exam::query()
@@ -99,9 +107,12 @@ class ExamRepository extends BaseRepository
->where('end', '>=', $now)
->where('status', Exam::STATUS_ENABLED)
->orderBy('id', 'desc');
if ($excludeId) {
if (!is_null($excludeId)) {
$query->whereNotIn('id', Arr::wrap($excludeId));
}
if (!is_null($isDiscovered)) {
$query->where('is_discovered', $isDiscovered);
}
return $query->get();
}
@@ -175,27 +186,15 @@ class ExamRepository extends BaseRepository
* assign exam to user
*
* @param int $uid
* @param null $examId
* @param int $examId
* @param null $begin
* @param null $end
* @return mixed
*/
public function assignToUser(int $uid, $examId = null, $begin = null, $end = null)
public function assignToUser(int $uid, int $examId, $begin = null, $end = null)
{
$logPrefix = "uid: $uid, examId: $examId, begin: $begin, end: $end";
if ($examId > 0) {
$exam = Exam::query()->find($examId);
} else {
$exams = $this->listValid();
if ($exams->isEmpty()) {
throw new NexusException("No valid exam.");
}
if ($exams->count() > 1) {
do_log(last_query());
throw new NexusException("valid exam more than 1.");
}
$exam = $exams->first();
}
$exam = Exam::query()->find($examId);
$user = User::query()->findOrFail($uid);
if (!$this->isExamMatchUser($exam, $user)) {
throw new NexusException("Exam: {$exam->id} no match this user.");
@@ -414,6 +413,7 @@ class ExamRepository extends BaseRepository
$currentValueFormatted = $currentValue;
$requireValueAtomic = $requireValue;
}
$index['name'] = Exam::$indexes[$index['index']]['name'] ?? '';
$index['index_formatted'] = nexus_trans('exam.index_text_' . $index['index']);
$index['require_value_formatted'] = "$requireValue " . ($index['unit'] ?? '');
$index['current_value'] = $currentValue;
@@ -437,13 +437,13 @@ class ExamRepository extends BaseRepository
public function cronjonAssign()
{
$exams = $this->listValid();
$exams = $this->listValid(null, Exam::DISCOVERED_YES);
if ($exams->isEmpty()) {
do_log("No valid exam.");
do_log("No valid and discovered exam.");
return false;
}
if ($exams->count() > 1) {
do_log("Valid exam more than 1.", "warning");
do_log("Valid and discovered exam more than 1.", "warning");
}
/** @var Exam $exam */
$exam = $exams->first();
+82
View File
@@ -0,0 +1,82 @@
<?php
namespace App\Repositories;
use Illuminate\Support\Facades\DB;
class ToolRepository extends BaseRepository
{
public function getSystemInfo()
{
$systemInfo = [
'nexus_version' => config('app.nexus_version'),
'laravel_version' => \Illuminate\Foundation\Application::VERSION,
'php_version' => PHP_VERSION,
'mysql_version' => DB::select(DB::raw('select version() as info'))[0]->info,
'os' => PHP_OS,
'server_software' => $_SERVER['SERVER_SOFTWARE'],
];
return $systemInfo;
}
public function backupWebRoot()
{
$webRoot = base_path();
$dirName = basename($webRoot);
$filename = sprintf('%s/%s.%s.tar.gz', sys_get_temp_dir(), $dirName, date('Ymd.His'));
$command = sprintf(
'tar --exclude=vendor --exclude=.git -czf %s -C %s %s',
$filename, dirname($webRoot), $dirName
);
$result = exec($command, $output, $resultCode);
do_log(sprintf(
"command: %s, output: %s, resultCode: %s, result: %s, filename: %s",
$command, json_encode($output), $resultCode, $result, $filename
));
return compact('result', 'filename');
}
public function backupDatabase()
{
$connectionName = config('database.default');
$config = config("database.connections.$connectionName");
$filename = sprintf('%s/%s.database.%s.sql', sys_get_temp_dir(), basename(base_path()), date('Ymd.His'));
$command = sprintf(
'mysqldump --user=%s --password=%s --port=%s --single-transaction --databases %s >> %s',
$config['username'], $config['password'], $config['port'], $config['database'], $filename,
);
$result = exec($command, $output, $resultCode);
do_log(sprintf(
"command: %s, output: %s, resultCode: %s, result: %s, filename: %s",
$command, json_encode($output), $resultCode, $result, $filename
));
return compact('result', 'filename');
}
public function backupAll()
{
$backupWeb = $this->backupWebRoot();
if ($backupWeb['result'] != 0) {
throw new \RuntimeException("backup web fail: " . json_encode($backupWeb));
}
$backupDatabase = $this->backupDatabase();
if ($backupDatabase['result'] != 0) {
throw new \RuntimeException("backup database fail: " . json_encode($backupDatabase));
}
$filename = sprintf('%s/%s.%s.tar.gz', sys_get_temp_dir(), basename(base_path()), date('Ymd.His'));
$command = sprintf(
'tar -czf %s -C %s %s -C %s %s',
$filename,
dirname($backupWeb['filename']), basename($backupWeb['filename']),
dirname($backupDatabase['filename']), basename($backupDatabase['filename'])
);
$result = exec($command, $output, $resultCode);
do_log(sprintf(
"command: %s, output: %s, resultCode: %s, result: %s, filename: %s",
$command, json_encode($output), $resultCode, $result, $filename
));
return compact('result', 'filename');
}
}