-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcdn.cpp
More file actions
622 lines (453 loc) · 16.4 KB
/
Copy pathcdn.cpp
File metadata and controls
622 lines (453 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
#include "cdn.h"
#include <QNetworkProxy>
#include <QThread>
#include <QMessageAuthenticationCode>
#include <QJsonDocument>
#include <QJsonArray>
// Constructor
CDN::CDN() :
_manager(new QNetworkAccessManager(this)),
_thread(new QThread),
_jobQueue(new JobQueue<Job>),
_workQueue(new WorkerQueue<Job>(6))
{
_registerMetaType();
_manager->setProxy(QNetworkProxy::NoProxy);
connect(_manager, &QNetworkAccessManager::finished, this, &CDN::_requestFinished);
connect(_thread, &QThread::finished, this, &QObject::deleteLater);
this->moveToThread(_thread);
_thread->start();
}
// Destructor
CDN::~CDN()
{
qDebug() << "Execute CDN::~CDN()";
_manager->disconnect();
_manager->deleteLater();
_manager = nullptr;
_thread->quit();
_thread->requestInterruption();
_thread = nullptr;
_workQueue->clear();
delete _workQueue;
_workQueue = nullptr;
_jobQueue->clear();
delete _jobQueue;
_jobQueue = nullptr;
}
// Public Methods
void CDN::setAccount(const Account &account)
{
qDebug() << "enter CDN::setAccount";
_account = account;
qDebug() << "_account.accessKey:" << _account.accessKey;
qDebug() << "_account.accessSecret:" << _account.accessSecret;
}
void CDN::resetAccount()
{
_account.reset();
}
// Public Slots
void CDN::listDomain(const ListDomainParams ¶ms)
{
qDebug() << "Invoke listDomain";
QByteArray body;
QStringHash resources = {
{ "sortField", params.sortField },
{ "orderType", params.orderType },
{ "serviceType", params.serviceType },
{ "status", params.status },
{ "workStatus", params.workStatus },
{ "pageNum", QString::number(params.pageNum) },
{ "pageSize", QString::number(params.pageSize) }
};
// qDebug() << "listDomain resources:" << resources;
_sendRequest(METHOD_GET, body, resources, listDomainOperation);
}
void CDN::purge(const PurgeParams ¶ms)
{
if (params.domain.isEmpty())
{
emit errorResponse("创建缓存刷新请求: 缓存地址不得为空");
return;
}
if (params.files.isEmpty() && params.dirs.isEmpty())
{
emit errorResponse("创建缓存刷新请求: 文件或文件夹必须存在一个");
return;
}
Job job(purgeOperation, QVariant::fromValue<PurgeParams>(params));
_jobQueue->push(job);
_work();
}
void CDN::getPurgeStatus(const GetPurgeStatusParams ¶ms)
{
qDebug() << "Invoke getPurgeStatus";
if (params.domain.isEmpty())
{
emit errorResponse("创建缓存刷新请求: 缓存地址不得为空");
return;
}
QByteArray body;
QStringHash resources = {
{ "domain", params.domain },
{ "id", params.id }
};
// qDebug() << "getPurgeStatus resources:" << resources;
_sendRequest(METHOD_GET, body, resources, getPurgeStatusOperation);
}
void CDN::listPurge(const ListPurgeParams ¶ms)
{
qDebug() << "Invoke listPurge";
if (params.domain.isEmpty())
{
emit errorResponse("创建缓存刷新请求: 缓存地址不得为空");
return;
}
QByteArray body;
QStringHash resources = {
{ "domain", params.domain },
{ "pageNum", QString::number(params.pageNum) },
{ "pageSize", QString::number(params.pageSize) }
};
// qDebug() << "listPurge resources:" << resources;
_sendRequest(METHOD_GET, body, resources, listPurgeOperation);
}
// Private Methods
void CDN::_registerMetaType() const
{
qRegisterMetaType<ListDomainParams>("ListDomainParams");
qRegisterMetaType<PurgeParams>("PurgeParams");
qRegisterMetaType<GetPurgeStatusParams>("GetPurgeStatusParams");
qRegisterMetaType<ListPurgeParams>("ListPurgeParams");
qRegisterMetaType<Domain>("Domain");
qRegisterMetaType<QVector<Domain>>("QVector<Domain>");
qRegisterMetaType<Purge>("Purge");
qRegisterMetaType<QVector<Purge>>("QVector<Purge>");
qRegisterMetaType<PurgeStatus>("PurgeStatus");
qRegisterMetaType<QVector<PurgeStatus>>("QVector<PurgeStatus>");
qRegisterMetaType<Operation>("Operation");
}
void CDN::_work()
{
if (_workQueue->isFull()) return;
if (_jobQueue->isEmpty()) return;
Job job = _jobQueue->pop();
_workQueue->push(job);
switch (job.operation)
{
case purgeOperation: _purge(job); break;
#if 0
case preheatOperation: _preheat(job); break;
#endif
default: qDebug() << "Unknown operation";
}
}
QNetworkReply* CDN::_sendRequest(const QString &method,
const QByteArray &body,
const QStringHash &resources,
const Operation &operation)
{
QNetworkRequest request;
request.setUrl(QUrl("http://ncdn-eastchina1.126.net"));
QDateTime dateTime = QDateTime::currentDateTimeUtc();
QLocale locale = QLocale::English;
QString format = "ddd, dd MMM yyyy HH:mm:ss";
QString date = locale.toString(dateTime, format) + " GMT";
request.setRawHeader(HEADER_DATE, date.toUtf8());
request.setRawHeader(HEADER_ACCEPT, "application/json");
if (body.size() > 0)
{
// qDebug() << "body.size():" << body.size();
request.setHeader(QNetworkRequest::ContentLengthHeader, body.size());
// 文档里说需要提供,但实际上不提供也可以正常使用
// QByteArray bodyHash = QCryptographicHash::hash(body, QCryptographicHash::Md5);
// request.setRawHeader(HEADER_CONTENT_MD5, bodyHash.toHex());
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json;charset=UTF-8");
}
_signRequest(method, request, operation, resources);
qDebug() << "Build requeset success";
QNetworkReply *reply;
if (method == METHOD_GET) reply = _manager->get(request);
if (method == METHOD_POST) reply = _manager->post(request, body);
if (method == METHOD_PUT) reply = _manager->put(request, body);
_operationHash.insert(reply, operation);
qDebug() << "Sended requeset";
return reply;
}
void CDN::_signRequest(const QString &method,
QNetworkRequest &request,
const Operation &operation,
const QStringHash &resources)
{
QStringList sign = {
method,
request.rawHeader(HEADER_CONTENT_MD5),
request.header(QNetworkRequest::ContentTypeHeader).toString(),
request.rawHeader(HEADER_DATE)
};
QString url = request.url().toString();
QString resource = "/domain/";
switch (operation) {
case purgeOperation: case listPurgeOperation: resource += resources["domain"] + "/purge"; break;
case getPurgeStatusOperation: resource += resources["domain"] + "/purge/" + resources["id"]; break;
default:;
}
url += resource;
QStringHash::const_iterator rci;
QStringMap params;
for (rci = resources.cbegin(); rci != resources.cend(); ++rci)
{
QString key = rci.key();
if (key != "domain" && key != "id") params.insert(key, rci.value());
}
if (params.size() > 0)
{
QStringList subResourceList = {
"enable", "disable", "pageSize", "pageNum", "dateFrom", "dateTo", "type", "orderType", "sortField", "serviceType",
"status", "isEnabled"
};
QStringList subResources;
QStringList query;
QStringMap::const_iterator pci;
for (pci = params.cbegin(); pci != params.cend(); ++pci)
{
QString subQuery = pci.key();
if (!pci.value().isEmpty()) subQuery += "=" + pci.value();
query.append(subQuery);
if (subResourceList.contains(pci.key())) subResources.append(subQuery);
}
if (subResources.size() > 0) resource += "?" + subResources.join("&");
url += "?" + query.join("&");
}
request.setUrl(QUrl(url));
// qDebug() << "request url:" << request.url();
sign.append(resource);
QString signString = sign.join("\n");
// qDebug() << "sign:" << signString;
QString signature = QMessageAuthenticationCode::hash(signString.toUtf8(),
_account.accessSecret.toUtf8(),
QCryptographicHash::Sha256).toBase64();
// qDebug() << "signature:" << signature;
request.setRawHeader(HEADER_AUTHORIZATION, ("NCDN " + _account.accessKey + ":" + signature).toUtf8());
}
// _purge
void CDN::_purge(const Job &job)
{
PurgeParams params = job.params.value<PurgeParams>();
QJsonObject root;
QJsonArray fileUrls;
QJsonArray dirUrls;
foreach (auto file, params.files)
{
fileUrls.append(file);
}
foreach (auto dir, params.dirs)
{
dirUrls.append(dir);
}
root.insert("file-url", fileUrls);
root.insert("dir-url", dirUrls);
QJsonDocument jsonDoc(root);
QByteArray body = jsonDoc.toJson(QJsonDocument::Compact);
qDebug() << "body:" << body;
QStringHash resources = {{ "domain", params.domain }};
_sendRequest(METHOD_POST, body, resources, purgeOperation);
}
// listDomain
void CDN::_listDomainHandler(QNetworkReply *reply)
{
bool isTruncated = false;
int quantity = 0;
QVector<Domain> domains;
if (reply->error() != QNetworkReply::NoError)
{
emit listDomainResponse(reply->error(), isTruncated, quantity, domains);
return;
}
QByteArray data = reply->readAll();
// qDebug() << "_listDomainHandler data:" << data;
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);
if (jsonError.error != QJsonParseError::NoError)
{
emit listDomainResponse(QNetworkReply::InternalServerError, isTruncated, quantity, domains);
return;
}
QJsonObject root = jsonDoc.object();
isTruncated = root["is-truncated"].toBool();
quantity = root["quantity"].toInt();
foreach (const QJsonValue &value, root["domain-summary"].toArray())
{
auto obj = value.toObject();
Domain domain = {
.productID = obj["product-id"].toString(),
.id = obj["domain-id"].toString(),
.name = obj["domain-name"].toString(),
.serviceType = obj["service-type"].toString(),
.serviceAreas = obj["service-areas"].toString(),
.originType = obj["origin-type"].toString(),
.originIPs = {},
.defaultOriginHostHeader = obj["default-origin-host-header"].toString(),
.comment = obj["comment"].toString(),
.workStatus = obj["work-status"].toString(),
.status = obj["status"].toString(),
.cname = obj["cname"].toString()
};
domain.createTime = obj["create-time"].toDouble();
domain.updateTime = obj["update-time"].toDouble();
foreach (const QJsonValue &ip, obj["origin-ips"].toArray())
{
domain.originIPs.append(ip.toString());
}
domains.append(domain);
}
// qDebug() << "_listPurgeHandler domains:" << domains;
emit listDomainResponse(reply->error(), isTruncated, quantity, domains);
}
// purge
void CDN::_purgeHandler(QNetworkReply *reply)
{
QString id;
if (reply->error() != QNetworkReply::NoError)
{
emit purgeResponse(reply->error(), id);
return;
}
QByteArray data = reply->readAll();
// qDebug() << "_purgeHandler data:" << data;
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);
if (jsonError.error != QJsonParseError::NoError)
{
emit purgeResponse(QNetworkReply::InternalServerError, id);
return;
}
QJsonObject root = jsonDoc.object();
id = root["purge-id"].toString();
emit purgeResponse(reply->error(), id);
}
// getPurgeStatus
void CDN::_getPurgeStatusHandler(QNetworkReply *reply)
{
QVector<PurgeStatus> purgeStatuses;
if (reply->error() != QNetworkReply::NoError)
{
emit getPurgeStatusResponse(reply->error(), purgeStatuses);
return;
}
QByteArray data = reply->readAll();
// qDebug() << "_getPurgeStatusHandler data:" << data;
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);
if (jsonError.error != QJsonParseError::NoError)
{
emit getPurgeStatusResponse(QNetworkReply::InternalServerError, purgeStatuses);
return;
}
QJsonObject root = jsonDoc.object();
foreach (const QJsonValue &value, root["item"].toArray())
{
auto obj = value.toObject();
PurgeStatus purgeStatus = {
.path = obj["path"].toString(),
.status = obj["status"].toString(),
.rate = obj["rate"].toInt()
};
purgeStatuses.append(purgeStatus);
}
// qDebug() << "_getPurgeStatusHandler purgeStatuses:" << purgeStatuses;
emit getPurgeStatusResponse(reply->error(), purgeStatuses);
}
// listPurge
void CDN::_listPurgeHandler(QNetworkReply *reply)
{
bool isTruncated = false;
int quantity = 0;
QVector<Purge> purges;
if (reply->error() != QNetworkReply::NoError)
{
emit listPurgeResponse(reply->error(), isTruncated, quantity, purges);
return;
}
QByteArray data = reply->readAll();
// qDebug() << "_listPurgeHandler data:" << data;
QJsonParseError jsonError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);
if (jsonError.error != QJsonParseError::NoError)
{
emit listPurgeResponse(QNetworkReply::InternalServerError, isTruncated, quantity, purges);
return;
}
QJsonObject root = jsonDoc.object();
isTruncated = root["is-truncated"].toBool();
quantity = root["quantity"].toInt();
foreach (const QJsonValue &value, root["items"].toArray())
{
auto obj = value.toObject();
Purge purge = {
.id = obj["purge-id"].toString(),
.urls = {},
.status = obj["status"].toString()
};
purge.createTime = obj["create-time"].toDouble();
foreach (const QJsonValue &url, obj["purge-urls"].toArray())
{
purge.urls.append(url.toString());
}
purges.append(purge);
}
// qDebug() << "_listPurgeHandler purges:" << purges;
emit listPurgeResponse(reply->error(), isTruncated, quantity, purges);
}
// Private Slots
void CDN::_requestFinished(QNetworkReply *reply)
{
// qDebug() << "enter _requestFinished Thread:" << this->thread();
QNetworkReply::NetworkError error = reply->error();
Operation operation = _operationHash.value(reply);
if (error != QNetworkReply::NoError) {
QString message;
switch (error)
{
case QNetworkReply::ConnectionRefusedError:
message = "远程服务器拒绝连接";
qDebug() << "远程服务器拒绝连接 operation:" << operation;
break;
case QNetworkReply::HostNotFoundError:
message = "远程主机名未找到(无效主机名)";
qDebug() << "远程主机名未找到(无效主机名) operation:" << operation;
break;
case QNetworkReply::TooManyRedirectsError:
message = "请求超过了设定的最大重定向次数";
qDebug() << "请求超过了设定的最大重定向次数 operation:" << operation;
break;
case QNetworkReply::ContentNotFoundError:
message = "内容不存在";
qDebug() << "请求查询的对象不存在 operation:" << operation;
break;
default:
message = "未知错误: " + reply->errorString();
qDebug() << "未知错误:" << error << " " << reply->errorString() << "operation:" << operation;
}
emit errorResponse(message);
}
switch (operation)
{
case listDomainOperation: _listDomainHandler(reply); break;
case purgeOperation: _workQueue->pop(); _purgeHandler(reply); break;
case getPurgeStatusOperation: _getPurgeStatusHandler(reply); break;
case listPurgeOperation: _listPurgeHandler(reply); break;
#if 0
case preheatOperation: _workQueue->pop(); _preheatHandler(reply); break;
case listPreheatOperation: _listPreheatHandler(reply); break;
case getPreheatQuotaOperation: _getPreheatQuotaHandler(reply); break;
#endif
default: qDebug() << "Connect to host success!";
}
_operationHash.remove(reply);
reply->disconnect();
reply->deleteLater();
reply = nullptr;
_work();
}