selfprivacy.org.app/lib/logic/api_maps/hetzner.dart

416 lines
11 KiB
Dart
Raw Normal View History

import 'dart:convert';
2021-01-06 17:35:57 +00:00
import 'dart:io';
import 'package:dio/dio.dart';
2021-03-25 23:30:34 +00:00
import 'package:selfprivacy/config/get_it_config.dart';
2021-01-06 17:35:57 +00:00
import 'package:selfprivacy/logic/api_maps/api_map.dart';
import 'package:selfprivacy/logic/models/json/hetzner_server_info.dart';
import 'package:selfprivacy/logic/models/hive/server_details.dart';
import 'package:selfprivacy/logic/models/hive/user.dart';
2021-08-18 09:36:40 +00:00
import 'package:selfprivacy/utils/password_generator.dart';
2021-01-06 17:35:57 +00:00
2021-03-25 23:30:34 +00:00
class HetznerApi extends ApiMap {
2022-06-05 19:36:32 +00:00
HetznerApi({this.hasLogger = false, this.isWithToken = true});
2022-05-24 18:55:39 +00:00
@override
2022-02-16 07:28:29 +00:00
bool hasLogger;
2022-05-24 18:55:39 +00:00
@override
2021-03-25 23:30:34 +00:00
bool isWithToken;
2022-05-24 18:55:39 +00:00
@override
2021-03-25 23:30:34 +00:00
BaseOptions get options {
2022-06-05 19:36:32 +00:00
final BaseOptions options = BaseOptions(baseUrl: rootAddress);
2021-03-25 23:30:34 +00:00
if (isWithToken) {
2022-06-05 19:36:32 +00:00
final String? token = getIt<ApiConfigModel>().hetznerKey;
2021-03-25 23:30:34 +00:00
assert(token != null);
options.headers = {'Authorization': 'Bearer $token'};
}
if (validateStatus != null) {
options.validateStatus = validateStatus!;
2021-01-06 17:35:57 +00:00
}
2021-03-25 23:30:34 +00:00
return options;
2021-01-06 17:35:57 +00:00
}
@override
2021-03-25 23:30:34 +00:00
String rootAddress = 'https://api.hetzner.cloud/v1';
2021-01-06 17:35:57 +00:00
2022-06-05 19:36:32 +00:00
Future<bool> isValid(final String token) async {
validateStatus = (final int? status) =>
status == HttpStatus.ok || status == HttpStatus.unauthorized;
2022-06-05 19:36:32 +00:00
final Dio client = await getClient();
final Response response = await client.get(
2021-03-25 23:30:34 +00:00
'/servers',
options: Options(
headers: {'Authorization': 'Bearer $token'},
),
2021-01-06 17:35:57 +00:00
);
2021-03-26 13:38:39 +00:00
close(client);
2021-01-06 17:35:57 +00:00
if (response.statusCode == HttpStatus.ok) {
return true;
} else if (response.statusCode == HttpStatus.unauthorized) {
return false;
} else {
2021-01-13 16:45:46 +00:00
throw Exception('code: ${response.statusCode}');
2021-01-06 17:35:57 +00:00
}
}
Future<ServerVolume?> createVolume() async {
ServerVolume? volume;
final Response dbCreateResponse;
2022-06-05 19:36:32 +00:00
final Dio client = await getClient();
try {
dbCreateResponse = await client.post(
'/volumes',
data: {
'size': 10,
'name': StringGenerators.dbStorageName(),
'labels': {'labelkey': 'value'},
'location': 'fsn1',
'automount': false,
'format': 'ext4'
},
);
final dbId = dbCreateResponse.data['volume']['id'];
final dbName = dbCreateResponse.data['volume']['name'];
volume = ServerVolume(
id: dbId,
name: dbName,
);
} catch (e) {
print(e);
} finally {
client.close();
}
return volume;
}
Future<List<ServerVolume>> getVolumes(final String? status) async {
final List<ServerVolume> volumes = [];
final Response dbGetResponse;
final Dio client = await getClient();
try {
dbGetResponse = await client.get(
'/volumes',
queryParameters: {
'status': status,
},
);
final List<dynamic> rawVolumes = dbGetResponse.data['volumes'];
for (final rawVolume in rawVolumes) {
final int dbId = rawVolume['id'];
final String dbName = rawVolume['name'];
final volume = ServerVolume(
id: dbId,
name: dbName,
);
volumes.add(volume);
}
} catch (e) {
print(e);
} finally {
client.close();
}
return volumes;
}
Future<ServerVolume?> getVolume(final int id) async {
ServerVolume? volume;
final Response dbGetResponse;
final Dio client = await getClient();
try {
dbGetResponse = await client.get('/volumes/$id');
final int dbId = dbGetResponse.data['volume']['id'];
final String dbName = dbGetResponse.data['volume']['name'];
volume = ServerVolume(
id: dbId,
name: dbName,
);
} catch (e) {
print(e);
} finally {
client.close();
}
return volume;
}
void deleteVolume(final int id) async {
final Dio client = await getClient();
try {
await client.delete('/volumes/$id');
} catch (e) {
print(e);
} finally {
client.close();
}
}
Future<bool> attachVolume(final int volumeId, final int serverId) async {
bool success = false;
final Response dbPostResponse;
final Dio client = await getClient();
try {
dbPostResponse = await client.post(
'/volumes/$volumeId/actions/attach',
data: {
'automount': true,
'server': serverId,
},
);
success = dbPostResponse.data['action']['status'].toString() != 'error';
} catch (e) {
print(e);
} finally {
client.close();
}
return success;
}
Future<bool> detachVolume(final int volumeId) async {
bool success = false;
final Response dbPostResponse;
final Dio client = await getClient();
try {
dbPostResponse = await client.post('/volumes/$volumeId/actions/detach');
success = dbPostResponse.data['action']['status'].toString() != 'error';
} catch (e) {
print(e);
} finally {
client.close();
}
return success;
}
Future<bool> resizeVolume(final int volumeId, final int sizeGb) async {
bool success = false;
final Response dbPostResponse;
final Dio client = await getClient();
try {
dbPostResponse = await client.post(
'/volumes/$volumeId/actions/resize',
data: {
'size': sizeGb,
},
);
success = dbPostResponse.data['action']['status'].toString() != 'error';
} catch (e) {
print(e);
} finally {
client.close();
}
return success;
2021-10-11 21:10:04 +00:00
}
2022-06-09 06:51:29 +00:00
Future<ServerHostingDetails?> createServer({
2022-06-05 19:36:32 +00:00
required final String cloudFlareKey,
required final User rootUser,
required final String domainName,
required final ServerVolume dataBase,
2021-10-11 21:10:04 +00:00
}) async {
2022-06-05 19:36:32 +00:00
final Dio client = await getClient();
2021-10-11 21:10:04 +00:00
2022-06-05 19:36:32 +00:00
final String dbPassword = StringGenerators.dbPassword();
final int dbId = dataBase.id;
2021-04-20 11:44:33 +00:00
2022-06-05 19:36:32 +00:00
final String apiToken = StringGenerators.apiToken();
2021-11-18 19:10:40 +00:00
2022-06-05 19:36:32 +00:00
final String hostname = getHostnameFromDomain(domainName);
2021-11-18 19:10:40 +00:00
2022-06-05 19:36:32 +00:00
final String base64Password =
2022-04-29 10:49:33 +00:00
base64.encode(utf8.encode(rootUser.password ?? 'PASS'));
2022-05-24 18:55:39 +00:00
print('hostname: $hostname');
2022-02-02 12:53:21 +00:00
2021-08-29 13:54:28 +00:00
/// add ssh key when you need it: e.g. "ssh_keys":["kherel"]
/// check the branch name, it could be "development" or "master".
2022-02-08 06:59:35 +00:00
///
2022-06-05 19:36:32 +00:00
final String userdataString =
2022-04-29 10:49:33 +00:00
"#cloud-config\nruncmd:\n- curl https://git.selfprivacy.org/SelfPrivacy/selfprivacy-nixos-infect/raw/branch/master/nixos-infect | PROVIDER=hetzner NIX_CHANNEL=nixos-21.05 DOMAIN='$domainName' LUSER='${rootUser.login}' ENCODED_PASSWORD='$base64Password' CF_TOKEN=$cloudFlareKey DB_PASSWORD=$dbPassword API_TOKEN=$apiToken HOSTNAME=$hostname bash 2>&1 | tee /tmp/infect.log";
2022-02-02 12:53:21 +00:00
print(userdataString);
2022-06-05 19:36:32 +00:00
final Map<String, Object> data = {
2022-05-24 18:55:39 +00:00
'name': hostname,
'server_type': 'cx11',
'start_after_create': false,
'image': 'ubuntu-20.04',
'volumes': [dbId],
'networks': [],
'user_data': userdataString,
'labels': {},
'automount': true,
'location': 'fsn1'
2022-02-02 12:53:21 +00:00
};
2022-05-24 18:55:39 +00:00
print('Decoded data: $data');
2021-01-19 08:38:02 +00:00
2022-06-09 06:51:29 +00:00
ServerHostingDetails? serverDetails;
try {
final Response serverCreateResponse = await client.post(
'/servers',
data: data,
);
print(serverCreateResponse.data);
serverDetails = ServerHostingDetails(
id: serverCreateResponse.data['server']['id'],
ip4: serverCreateResponse.data['server']['public_net']['ipv4']['ip'],
createTime: DateTime.now(),
volume: dataBase,
apiToken: apiToken,
provider: ServerProvider.hetzner,
);
} on DioError catch (e) {
print(e);
rethrow;
} catch (e) {
print(e);
} finally {
client.close();
}
2021-04-20 11:44:33 +00:00
2022-06-09 06:51:29 +00:00
return serverDetails;
2021-01-19 12:05:40 +00:00
}
2022-06-05 19:36:32 +00:00
static String getHostnameFromDomain(final String domain) {
2022-04-29 10:49:33 +00:00
// Replace all non-alphanumeric characters with an underscore
2022-06-05 19:36:32 +00:00
String hostname =
2022-04-29 10:49:33 +00:00
domain.split('.')[0].replaceAll(RegExp(r'[^a-zA-Z0-9]'), '-');
if (hostname.endsWith('-')) {
hostname = hostname.substring(0, hostname.length - 1);
}
if (hostname.startsWith('-')) {
hostname = hostname.substring(1);
}
if (hostname.isEmpty) {
hostname = 'selfprivacy-server';
}
return hostname;
}
2021-03-31 11:37:39 +00:00
Future<void> deleteSelfprivacyServerAndAllVolumes({
2022-06-05 19:36:32 +00:00
required final String domainName,
2021-03-31 11:37:39 +00:00
}) async {
2022-06-05 19:36:32 +00:00
final Dio client = await getClient();
2021-02-15 18:58:29 +00:00
2022-06-05 19:36:32 +00:00
final String hostname = getHostnameFromDomain(domainName);
2022-04-29 10:49:33 +00:00
2022-06-05 19:36:32 +00:00
final Response serversReponse = await client.get('/servers');
final List servers = serversReponse.data['servers'];
final Map server = servers.firstWhere((final el) => el['name'] == hostname);
final List volumes = server['volumes'];
final List<Future> laterFutures = <Future>[];
2021-10-11 21:10:04 +00:00
2022-06-05 19:36:32 +00:00
for (final volumeId in volumes) {
2021-10-11 21:10:04 +00:00
await client.post('/volumes/$volumeId/actions/detach');
2021-03-30 17:38:40 +00:00
}
2022-05-24 18:55:39 +00:00
await Future.delayed(const Duration(seconds: 10));
2021-03-30 17:38:40 +00:00
2022-06-05 19:36:32 +00:00
for (final volumeId in volumes) {
2021-10-11 21:10:04 +00:00
laterFutures.add(client.delete('/volumes/$volumeId'));
2021-03-30 17:38:40 +00:00
}
2021-10-11 21:10:04 +00:00
laterFutures.add(client.delete('/servers/${server['id']}'));
await Future.wait(laterFutures);
close(client);
2021-02-15 18:58:29 +00:00
}
Future<ServerHostingDetails> reset() async {
2022-06-05 19:36:32 +00:00
final ServerHostingDetails server = getIt<ApiConfigModel>().serverDetails!;
2021-03-25 23:30:34 +00:00
2022-06-05 19:36:32 +00:00
final Dio client = await getClient();
2021-03-31 14:33:58 +00:00
await client.post('/servers/${server.id}/actions/reset');
2021-03-26 13:38:39 +00:00
close(client);
2021-01-19 12:05:40 +00:00
2021-03-31 14:33:58 +00:00
return server.copyWith(startTime: DateTime.now());
2021-01-06 17:35:57 +00:00
}
2021-02-03 19:51:07 +00:00
Future<ServerHostingDetails> powerOn() async {
2022-06-05 19:36:32 +00:00
final ServerHostingDetails server = getIt<ApiConfigModel>().serverDetails!;
2021-03-31 14:33:58 +00:00
2022-06-05 19:36:32 +00:00
final Dio client = await getClient();
2021-03-25 23:30:34 +00:00
await client.post('/servers/${server.id}/actions/poweron');
2021-03-26 13:38:39 +00:00
close(client);
2021-03-31 14:33:58 +00:00
return server.copyWith(startTime: DateTime.now());
2021-02-03 19:51:07 +00:00
}
2021-03-25 23:30:34 +00:00
2021-04-20 11:44:33 +00:00
Future<Map<String, dynamic>> getMetrics(
final DateTime start,
final DateTime end,
final String type,
) async {
final ServerHostingDetails? hetznerServer =
getIt<ApiConfigModel>().serverDetails;
2022-06-05 19:36:32 +00:00
final Dio client = await getClient();
2021-04-10 03:04:23 +00:00
2022-06-05 19:36:32 +00:00
final Map<String, dynamic> queryParameters = {
2022-05-24 18:55:39 +00:00
'start': start.toUtc().toIso8601String(),
'end': end.toUtc().toIso8601String(),
'type': type
2021-04-10 03:04:23 +00:00
};
2022-06-05 19:36:32 +00:00
final Response res = await client.get(
2021-04-10 03:04:23 +00:00
'/servers/${hetznerServer!.id}/metrics',
queryParameters: queryParameters,
);
2021-03-26 13:38:39 +00:00
close(client);
2021-04-10 03:04:23 +00:00
return res.data;
2021-03-25 23:30:34 +00:00
}
2021-03-26 13:38:39 +00:00
Future<HetznerServerInfo> getInfo() async {
final ServerHostingDetails? hetznerServer =
getIt<ApiConfigModel>().serverDetails;
2022-06-05 19:36:32 +00:00
final Dio client = await getClient();
final Response response = await client.get('/servers/${hetznerServer!.id}');
2021-03-26 13:38:39 +00:00
close(client);
return HetznerServerInfo.fromJson(response.data!['server']);
2021-03-25 23:30:34 +00:00
}
2021-05-17 12:38:38 +00:00
Future<List<HetznerServerInfo>> getServers() async {
2022-06-05 19:36:32 +00:00
final Dio client = await getClient();
final Response response = await client.get('/servers');
close(client);
return (response.data!['servers'] as List)
// ignore: unnecessary_lambdas
2022-06-05 19:36:32 +00:00
.map((final e) => HetznerServerInfo.fromJson(e))
.toList();
}
2021-05-17 12:38:38 +00:00
Future<void> createReverseDns({
2022-06-05 19:36:32 +00:00
required final String ip4,
required final String domainName,
2021-05-17 12:38:38 +00:00
}) async {
final ServerHostingDetails? hetznerServer =
getIt<ApiConfigModel>().serverDetails;
2022-06-09 06:51:29 +00:00
2022-06-05 19:36:32 +00:00
final Dio client = await getClient();
2022-06-09 06:51:29 +00:00
try {
await client.post(
'/servers/${hetznerServer!.id}/actions/change_dns_ptr',
data: {
'ip': ip4,
'dns_ptr': domainName,
},
);
} catch (e) {
print(e);
} finally {
close(client);
}
2021-05-17 12:38:38 +00:00
}
2021-01-06 17:35:57 +00:00
}