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

267 lines
7.9 KiB
Dart
Raw Normal View History

2021-01-19 08:38:02 +00:00
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';
2021-03-26 13:38:39 +00:00
import 'package:selfprivacy/logic/models/hetzner_server_info.dart';
2021-01-06 17:35:57 +00:00
import 'package:selfprivacy/logic/models/server_details.dart';
import 'package:selfprivacy/logic/models/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 {
bool hasLoger;
bool isWithToken;
HetznerApi({this.hasLoger = false, this.isWithToken = true});
BaseOptions get options {
var options = BaseOptions(baseUrl: rootAddress);
if (isWithToken) {
var token = getIt<ApiConfigModel>().hetznerKey;
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
Future<bool> isValid(String token) async {
2021-03-25 23:30:34 +00:00
validateStatus = (status) {
return status == HttpStatus.ok || status == HttpStatus.unauthorized;
};
var client = await getClient();
Response response = await client.get(
'/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
}
}
2021-03-30 17:38:40 +00:00
Future<bool> isFreeToCreate() async {
var client = await getClient();
Response serversReponse = await client.get('/servers');
List servers = serversReponse.data['servers'];
var server = servers.firstWhere(
(el) => el['name'] == 'selfprivacy-server',
orElse: null,
);
client.close();
return server == null;
}
2021-10-11 21:10:04 +00:00
Future<HetznerDataBase> createVolume() async {
2021-03-30 17:38:40 +00:00
var client = await getClient();
Response dbCreateResponse = await client.post(
'/volumes',
data: {
"size": 10,
2021-08-18 09:36:40 +00:00
"name": StringGenerators.dbStorageName(),
2021-03-30 17:38:40 +00:00
"labels": {"labelkey": "value"},
"location": "fsn1",
"automount": false,
"format": "ext4"
},
);
2021-10-11 21:10:04 +00:00
var dbId = dbCreateResponse.data['volume']['id'];
return HetznerDataBase(
id: dbId,
name: dbCreateResponse.data['volume']['name'],
);
}
Future<HetznerServerDetails> createServer({
required String cloudFlareKey,
required User rootUser,
required String domainName,
required HetznerDataBase dataBase,
}) async {
var client = await getClient();
// Response dbCreateResponse = await client.post(
// '/volumes',
// data: {
// "size": 10,
// "name": StringGenerators.dbStorageName(),
// "labels": {"labelkey": "value"},
// "location": "fsn1",
// "automount": false,
// "format": "ext4"
// },
// );
2021-08-29 09:50:24 +00:00
2021-08-18 09:36:40 +00:00
var dbPassword = StringGenerators.dbPassword();
2021-10-11 21:10:04 +00:00
// var dbId = dbCreateResponse.data['volume']['id'];
var dbId = dataBase.id;
2021-04-20 11:44:33 +00:00
2021-11-18 19:10:40 +00:00
final apiToken = StringGenerators.apiToken();
// Replace all non-alphanumeric characters with an underscore
2022-02-01 01:56:05 +00:00
var hostname =
domainName.split('.')[0].replaceAll(RegExp(r'[^a-zA-Z0-9]'), '-');
2022-02-01 01:55:09 +00:00
// if hostname ends with -, remove it
if (hostname.endsWith('-')) {
hostname = hostname.substring(0, hostname.length - 1);
}
// if hostname starts with -, remove it
if (hostname.startsWith('-')) {
hostname = hostname.substring(1);
}
// if hostname is empty, use default
if (hostname.isEmpty) {
hostname = 'selfprivacy-server';
}
2021-11-18 19:10:40 +00:00
2022-02-02 12:53:21 +00:00
print("hostname: $hostname");
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-02 12:53:21 +00:00
///
final userdataString = "#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='${escapeQuotes(rootUser.login)}' PASSWORD='${escapeQuotes(rootUser.password)}' CF_TOKEN=$cloudFlareKey DB_PASSWORD=${escapeQuotes(dbPassword)} API_TOKEN=$apiToken HOSTNAME=${escapeQuotes(hostname)} bash 2>&1 | tee /tmp/infect.log";
print(userdataString);
final data = {
"name": hostname,
"server_type": "cx11",
"start_after_create": false,
"image": "ubuntu-20.04",
"volumes": [dbId],
"networks": [],
"user_data": userdataString,
"labels": {},
"automount": true,
"location": "fsn1"
};
print("Decoded data: $data");
2021-01-19 08:38:02 +00:00
2021-03-30 17:38:40 +00:00
Response serverCreateResponse = await client.post(
2021-03-25 23:30:34 +00:00
'/servers',
2021-01-06 17:35:57 +00:00
data: data,
);
2021-04-20 11:44:33 +00:00
2022-02-02 12:53:21 +00:00
print(serverCreateResponse.data);
2021-03-25 23:30:34 +00:00
client.close();
2021-01-06 17:35:57 +00:00
return HetznerServerDetails(
2021-03-30 17:38:40 +00:00
id: serverCreateResponse.data['server']['id'],
ip4: serverCreateResponse.data['server']['public_net']['ipv4']['ip'],
2021-01-19 12:05:40 +00:00
createTime: DateTime.now(),
2021-10-11 21:10:04 +00:00
dataBase: dataBase,
2021-11-18 19:10:40 +00:00
apiToken: apiToken,
2021-01-19 12:05:40 +00:00
);
}
2021-03-31 11:37:39 +00:00
Future<void> deleteSelfprivacyServerAndAllVolumes({
required String domainName,
}) async {
2021-03-25 23:30:34 +00:00
var client = await getClient();
2021-02-15 18:58:29 +00:00
2021-03-30 17:38:40 +00:00
Response serversReponse = await client.get('/servers');
List servers = serversReponse.data['servers'];
2021-10-11 21:10:04 +00:00
Map server = servers.firstWhere((el) => el['name'] == domainName);
List volumes = server['volumes'];
2021-03-30 17:38:40 +00:00
var laterFutures = <Future>[];
2021-10-11 21:10:04 +00:00
for (var volumeId in volumes) {
await client.post('/volumes/$volumeId/actions/detach');
2021-03-30 17:38:40 +00:00
}
2021-10-11 21:10:04 +00:00
await Future.delayed(Duration(seconds: 10));
2021-03-30 17:38:40 +00:00
2021-10-11 21:10:04 +00:00
for (var volumeId in volumes) {
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
}
2021-03-31 14:33:58 +00:00
Future<HetznerServerDetails> reset() async {
var server = getIt<ApiConfigModel>().hetznerServer!;
2021-03-25 23:30:34 +00:00
2021-03-31 14:33:58 +00:00
var client = await getClient();
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
2021-03-31 14:33:58 +00:00
Future<HetznerServerDetails> powerOn() async {
var server = getIt<ApiConfigModel>().hetznerServer!;
2021-03-25 23:30:34 +00:00
var client = await getClient();
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(
DateTime start, DateTime end, String type) async {
2021-03-25 23:30:34 +00:00
var hetznerServer = getIt<ApiConfigModel>().hetznerServer;
var client = await getClient();
2021-04-10 03:04:23 +00:00
Map<String, dynamic> queryParameters = {
"start": start.toUtc().toIso8601String(),
"end": end.toUtc().toIso8601String(),
"type": type
};
var res = await client.get(
'/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 {
2021-03-25 23:30:34 +00:00
var hetznerServer = getIt<ApiConfigModel>().hetznerServer;
var client = await getClient();
2021-03-26 13:38:39 +00:00
Response response = await client.get('/servers/${hetznerServer!.id}');
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<void> createReverseDns({
required String ip4,
2021-05-17 12:40:06 +00:00
required String domainName,
2021-05-17 12:38:38 +00:00
}) async {
var hetznerServer = getIt<ApiConfigModel>().hetznerServer;
var client = await getClient();
await client.post(
'/servers/${hetznerServer!.id}/actions/change_dns_ptr',
data: {
"ip": ip4,
2021-05-17 12:40:06 +00:00
"dns_ptr": domainName,
2021-05-17 12:38:38 +00:00
},
);
close(client);
}
2021-01-06 17:35:57 +00:00
}
2022-02-01 01:55:09 +00:00
2022-02-02 12:53:21 +00:00
String escapeQuotes(String str) {
2022-02-01 01:55:09 +00:00
// replace all single quotes with escaped single quotes for bash strong quotes (i.e. '\'' )
2022-02-02 12:53:21 +00:00
print("Escaping single quotes for bash: $str");
print("Escaping result: ${str.replaceAll(RegExp(r"'"), "'\\''")}");
// also escape all double quotes for json
2022-02-01 01:55:09 +00:00
return str.replaceAll(RegExp(r"'"), "'\\''");
}