feat: systemd management (#532)

This commit is contained in:
lollipopkit🏳️‍⚧️
2024-08-14 14:29:03 +08:00
committed by GitHub
parent 46d5840276
commit 41e3fcb23a
18 changed files with 557 additions and 93 deletions

View File

@@ -2,29 +2,47 @@ import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:icons_plus/icons_plus.dart';
import 'package:server_box/core/extension/context/locale.dart';
import 'package:server_box/data/res/store.dart';
part 'server_func.g.dart';
@HiveType(typeId: 6)
enum ServerFuncBtn {
@HiveField(0)
terminal,
terminal._(),
@HiveField(1)
sftp,
sftp._(),
@HiveField(2)
container,
container._(),
@HiveField(3)
process,
process._(),
//@HiveField(4)
//pkg,
@HiveField(5)
snippet,
snippet._(),
@HiveField(6)
iperf,
iperf._(),
// @HiveField(7)
// pve,
@HiveField(8)
systemd._(1058),
;
final int? addedVersion;
const ServerFuncBtn._([this.addedVersion]);
static void autoAddNewFuncs(int cur) {
if (cur >= systemd.addedVersion!) {
final prop = Stores.setting.serverFuncBtns;
final list = prop.fetch();
if (!list.contains(systemd.index)) {
list.add(systemd.index);
prop.put(list);
}
}
}
static final defaultIdxs = [
terminal,
sftp,
@@ -32,6 +50,7 @@ enum ServerFuncBtn {
process,
//pkg,
snippet,
systemd,
].map((e) => e.index).toList();
IconData get icon => switch (this) {
@@ -42,6 +61,7 @@ enum ServerFuncBtn {
process => Icons.list_alt_outlined,
terminal => Icons.terminal,
iperf => Icons.speed,
systemd => MingCute.plugin_2_fill,
};
String get toStr => switch (this) {
@@ -52,5 +72,6 @@ enum ServerFuncBtn {
process => l10n.process,
terminal => l10n.terminal,
iperf => 'iperf',
systemd => 'Systemd',
};
}

View File

@@ -25,6 +25,8 @@ class ServerFuncBtnAdapter extends TypeAdapter<ServerFuncBtn> {
return ServerFuncBtn.snippet;
case 6:
return ServerFuncBtn.iperf;
case 8:
return ServerFuncBtn.systemd;
default:
return ServerFuncBtn.terminal;
}
@@ -51,6 +53,9 @@ class ServerFuncBtnAdapter extends TypeAdapter<ServerFuncBtn> {
case ServerFuncBtn.iperf:
writer.writeByte(6);
break;
case ServerFuncBtn.systemd:
writer.writeByte(8);
break;
}
}

View File

@@ -0,0 +1,118 @@
import 'package:fl_lib/fl_lib.dart';
import 'package:flutter/material.dart';
enum SystemdUnitFunc {
start,
stop,
restart,
reload,
enable,
disable,
status,
;
IconData get icon => switch (this) {
start => Icons.play_arrow,
stop => Icons.stop,
restart => Icons.refresh,
reload => Icons.refresh,
enable => Icons.check,
disable => Icons.close,
status => Icons.info,
};
}
enum SystemdUnitType {
service,
socket,
mount,
timer,
;
static SystemdUnitType? fromString(String? value) {
return values.firstWhereOrNull((e) => e.name == value?.toLowerCase());
}
}
enum SystemdUnitScope {
system,
user,
;
Color? get color => switch (this) {
system => Colors.red,
_ => null,
};
String getCmdPrefix(bool isRoot) {
if (this == system) {
return isRoot ? 'systemctl' : 'sudo systemctl';
}
return 'systemctl --user';
}
}
enum SystemdUnitState {
active,
inactive,
failed,
activating,
deactivating,
;
static SystemdUnitState? fromString(String? value) {
return values.firstWhereOrNull((e) => e.name == value?.toLowerCase());
}
Color? get color => switch (this) {
failed => Colors.red,
_ => null,
};
}
final class SystemdUnit {
final String name;
final String? description;
final SystemdUnitType type;
final SystemdUnitScope scope;
final SystemdUnitState state;
SystemdUnit({
required this.name,
this.description,
required this.type,
required this.scope,
required this.state,
});
String getCmd({
required SystemdUnitFunc func,
required bool isRoot,
}) {
final prefix = scope.getCmdPrefix(isRoot);
return '$prefix ${func.name} $name';
}
List<SystemdUnitFunc> get availableFuncs {
final funcs = <SystemdUnitFunc>{};
switch (state) {
case SystemdUnitState.active:
funcs.addAll([SystemdUnitFunc.stop, SystemdUnitFunc.restart]);
break;
case SystemdUnitState.inactive:
funcs.addAll([SystemdUnitFunc.start]);
break;
case SystemdUnitState.failed:
funcs.addAll([SystemdUnitFunc.restart]);
break;
case SystemdUnitState.activating:
funcs.addAll([SystemdUnitFunc.stop]);
break;
case SystemdUnitState.deactivating:
funcs.addAll([SystemdUnitFunc.start]);
break;
}
funcs.addAll([SystemdUnitFunc.status]);
return funcs.toList();
}
}

View File

@@ -1,30 +1,7 @@
import 'package:device_info_plus/device_info_plus.dart';
import 'package:fl_lib/fl_lib.dart';
import 'package:flutter/material.dart';
class AppProvider extends ChangeNotifier {
BuildContext? ctx;
final class AppProvider {
const AppProvider._();
bool isWearOS = false;
Future<void> init() async {
await _initIsWearOS();
}
Future<void> _initIsWearOS() async {
if (!isAndroid) {
isWearOS = false;
return;
}
final deviceInfo = DeviceInfoPlugin();
final androidInfo = await deviceInfo.androidInfo;
const feat = 'android.hardware.type.watch';
final hasFeat = androidInfo.systemFeatures.contains(feat);
if (hasFeat) {
isWearOS = true;
return;
}
}
static BuildContext? ctx;
}

View File

@@ -0,0 +1,167 @@
import 'package:dartssh2/dartssh2.dart';
import 'package:fl_lib/fl_lib.dart';
import 'package:server_box/core/extension/ssh_client.dart';
import 'package:server_box/data/model/app/shell_func.dart';
import 'package:server_box/data/model/server/server_private_info.dart';
import 'package:server_box/data/model/server/systemd.dart';
import 'package:server_box/data/res/provider.dart';
final class SystemdProvider {
late final SSHClient _client;
SystemdProvider.init(ServerPrivateInfo spi) {
_client = Pros.server.pick(spi: spi)!.client!;
getUnits();
}
final isBusy = false.vn;
final isRoot = false.vn;
final units = <SystemdUnit>[].vn;
Future<void> getUnits() async {
isBusy.value = true;
try {
final result = await _client.runScriptIn(_getUnitsCmd);
final units = result.split('\n');
final isRootRaw = units.firstOrNull;
isRoot.value = isRootRaw == '0';
final userUnits = <String>[];
final systemUnits = <String>[];
for (final unit in units.skip(1)) {
if (unit.startsWith('/etc/systemd/system')) {
systemUnits.add(unit);
} else if (unit.startsWith('~/.config/systemd/user')) {
userUnits.add(unit);
} else if (unit.trim().isNotEmpty) {
Loggers.app.warning('Unknown unit: $unit');
}
}
final parsedUserUnits =
await _parseUnitObj(userUnits, SystemdUnitScope.user);
final parsedSystemUnits =
await _parseUnitObj(systemUnits, SystemdUnitScope.system);
this.units.value = [...parsedUserUnits, ...parsedSystemUnits];
} catch (e, s) {
Loggers.app.warning('Parse systemd', e, s);
}
isBusy.value = false;
}
Future<List<SystemdUnit>> _parseUnitObj(
List<String> unitNames,
SystemdUnitScope scope,
) async {
final unitNames_ = unitNames
.map((e) => e.trim().split('/').last.split('.').first)
.toList();
final script = '''
for unit in ${unitNames_.join(' ')}; do
state=\$(systemctl show --no-pager \$unit)
echo -n "${ShellFunc.seperator}\n\$state"
done
''';
final result = await _client.runScriptIn(script);
final units = result.split(ShellFunc.seperator);
final parsedUnits = <SystemdUnit>[];
for (final unit in units) {
final parts = unit.split('\n');
var name = '';
var type = '';
var state = '';
String? description;
for (final part in parts) {
if (part.startsWith('Id=')) {
final val = _getIniVal(part).split('.');
name = val.first;
type = val.last;
continue;
}
if (part.startsWith('ActiveState=')) {
state = _getIniVal(part);
continue;
}
if (part.startsWith('Description=')) {
description = _getIniVal(part);
continue;
}
}
final unitType = SystemdUnitType.fromString(type);
if (unitType == null) {
Loggers.app.warning('Unit type: $type');
continue;
}
final unitState = SystemdUnitState.fromString(state);
if (unitState == null) {
Loggers.app.warning('Unit state: $state');
continue;
}
parsedUnits.add(SystemdUnit(
name: name,
type: unitType,
scope: scope,
state: unitState,
description: description,
));
}
parsedUnits.sort((a, b) {
// user units first
if (a.scope != b.scope) {
return a.scope == SystemdUnitScope.user ? -1 : 1;
}
// active units first
if (a.state != b.state) {
return a.state == SystemdUnitState.active ? -1 : 1;
}
return a.name.compareTo(b.name);
});
return parsedUnits;
}
}
String _getIniVal(String line) {
return line.split('=').last;
}
const _getUnitsCmd = '''
# If root, get system & user units, otherwise get user units
uid=\$(id -u)
echo \$uid
get_files() {
unit_type=\$1
base_dir=\$2
# If base_dir is not a directory, return
if [ ! -d "\$base_dir" ]; then
return
fi
find "\$base_dir" -type f -name "*.\$unit_type" -print | sort
}
get_type_files() {
unit_type=\$1
base_dir=""
if [ "\$uid" -eq 0 ]; then
get_files \$unit_type /etc/systemd/system
get_files \$unit_type ~/.config/systemd/user
else
get_files \$unit_type ~/.config/systemd/user
fi
}
types="service socket mount timer"
for type in \$types; do
get_type_files \$type
done
''';

View File

@@ -2,6 +2,6 @@
class BuildData {
static const String name = "ServerBox";
static const int build = 1057;
static const int build = 1058;
static const int script = 56;
}

View File

@@ -1,11 +1,9 @@
import 'package:server_box/data/provider/app.dart';
import 'package:server_box/data/provider/private_key.dart';
import 'package:server_box/data/provider/server.dart';
import 'package:server_box/data/provider/sftp.dart';
import 'package:server_box/data/provider/snippet.dart';
abstract final class Pros {
static final app = AppProvider();
static final key = PrivateKeyProvider();
static final server = ServerProvider();
static final sftp = SftpProvider();