summaryrefslogtreecommitdiff
path: root/cpp/src/IcePatch2/ClientUtil.cpp
blob: 754f77588740e4c958efbab6ce132b9c288be077 (plain)
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
// **********************************************************************
//
// Copyright (c) 2004 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

#include <IcePatch2/ClientUtil.h>
#include <IcePatch2/Util.h>
#include <IcePatch2/FileServerI.h>
#include <list>

#ifdef _WIN32
#   include <direct.h>
#endif

using namespace std;
using namespace Ice;
using namespace IcePatch2;

namespace IcePatch2
{

class Decompressor : public IceUtil::Thread, IceUtil::Monitor<IceUtil::Mutex>
{
public:

    Decompressor(const string& dataDir) :
	_dataDir(dataDir),
	_destroy(false)
    {
    }

    virtual ~Decompressor()
    {
	assert(_destroy);
    }

    void
    destroy()
    {
	IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
	_destroy = true;
	notify();
    }

    void
    add(const FileInfo info)
    {
	IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
	if(!_exception.empty())
	{
	    throw _exception;
	}
	_files.push_back(info);
	notify();
    }

    void
    exception() const
    {
	IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
	if(!_exception.empty())
	{
	    throw _exception;
	}
    }

    void
    log(ofstream& os)
    {
	IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);

	for(FileInfoSeq::const_iterator p = _filesDone.begin(); p != _filesDone.end(); ++p)
	{
	    os << '+' << *p << endl;
	}

	_filesDone.clear();
    }

    virtual void
    run()
    {
	FileInfo info;
	
	while(true)
	{
	    {
		IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
	    
		if(!info.path.empty())
		{
		    _filesDone.push_back(info);
		}
	    
		while(!_destroy && _files.empty())
		{
		    wait();
		}
	    
		if(!_files.empty())
		{
		    info = _files.front();
		    _files.pop_front();
		}
		else
		{
		    return;
		}
	    }
	
	    try
	    {
		decompressFile(_dataDir + '/' + info.path);
		remove(_dataDir + '/' + info.path + ".bz2");
	    }
	    catch(const string& ex)
	    {
		IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this);
		_destroy = true;
		_exception = ex;
		return;
	    }
	}
    }

private:

    const string _dataDir;

    string _exception;
    list<FileInfo> _files;
    FileInfoSeq _filesDone;

    bool _destroy;
};

}

IcePatch2::Patcher::Patcher(const CommunicatorPtr& communicator, const PatcherFeedbackPtr& feedback) :
    _feedback(feedback),
    _dataDir(normalize(communicator->getProperties()->getProperty("IcePatch2.Directory"))),
    _thorough(communicator->getProperties()->getPropertyAsInt("IcePatch2.Thorough") > 0),
    _chunkSize(communicator->getProperties()->getPropertyAsIntWithDefault("IcePatch2.ChunkSize", 100000))
{
    if(_dataDir.empty())
    {
	throw string("no data directory specified");
    }

    if(_chunkSize < 1)
    {
	const_cast<Int&>(_chunkSize) = 1;
    }

#ifdef _WIN32
    char cwd[_MAX_PATH];
    if(_getcwd(cwd, _MAX_PATH) == NULL)
#else
    char cwd[PATH_MAX];
    if(getcwd(cwd, PATH_MAX) == NULL)
#endif
    {
	throw "cannot get the current directory: " + lastError();
    }
    
    const_cast<string&>(_dataDir) = normalize(string(cwd) + '/' + _dataDir);
    
    PropertiesPtr properties = communicator->getProperties();

    const char* endpointsProperty = "IcePatch2.Endpoints";
    const string endpoints = properties->getProperty(endpointsProperty);
    if(endpoints.empty())
    {
	throw string("property `") + endpointsProperty + "' is not set";
    }
    
    const char* idProperty = "IcePatch2.Identity";
    const Identity id = stringToIdentity(properties->getPropertyWithDefault(idProperty, "IcePatch2/server"));
    
    ObjectPrx serverBase = communicator->stringToProxy(identityToString(id) + ':' + endpoints);
    const_cast<FileServerPrx&>(_serverCompress) = FileServerPrx::checkedCast(serverBase->ice_compress(true));
    if(!_serverCompress)
    {
	throw "proxy `" + identityToString(id) + ':' + endpoints + "' is not a file server.";
    }
    const_cast<FileServerPrx&>(_serverNoCompress) = FileServerPrx::checkedCast(_serverCompress->ice_compress(false));
}

IcePatch2::Patcher::~Patcher()
{
}

bool
IcePatch2::Patcher::prepare()
{
    _localFiles.clear();

    bool thorough = _thorough;

    if(!thorough)
    {
	try
	{
	    loadFileInfoSeq(_dataDir, _localFiles);
	}
	catch(const string& ex)
	{
	    thorough = _feedback->noFileSummary(ex);
	    if(!thorough)
	    {
		return false;
	    }
	}
    }
    
    if(thorough)
    {
	getFileInfoSeq(_dataDir, _localFiles, false, false, false);
	saveFileInfoSeq(_dataDir, _localFiles);
    }

    FileTree0 tree0;
    getFileTree0(_localFiles, tree0);

    if(tree0.checksum != _serverCompress->getChecksum())
    {
	if(!_feedback->fileListStart())
	{
	    return false;
	}
	
	ByteSeqSeq checksum0Seq = _serverCompress->getChecksum0Seq();
	if(checksum0Seq.size() != 256)
	{
	    throw string("server returned illegal value");
	}
	
	for(int node0 = 0; node0 < 256; ++node0)
	{
	    if(tree0.nodes[node0].checksum != checksum0Seq[node0])
	    {
		FileInfoSeq files = _serverCompress->getFileInfo1Seq(node0);
		
		sort(files.begin(), files.end(), FileInfoLess());
		files.erase(unique(files.begin(), files.end(), FileInfoEqual()), files.end());
		
		set_difference(tree0.nodes[node0].files.begin(),
			       tree0.nodes[node0].files.end(),
			       files.begin(),
			       files.end(),
			       back_inserter(_removeFiles),
			       FileInfoLess());
		
		set_difference(files.begin(),
			       files.end(),
			       tree0.nodes[node0].files.begin(),
			       tree0.nodes[node0].files.end(),
			       back_inserter(_updateFiles),
			       FileInfoLess());
	    }

	    if(!_feedback->fileListProgress((node0 + 1) * 100 / 256))
	    {
		return false;
	    }
	}

	if(!_feedback->fileListEnd())
	{
	    return false;
	}
    }
    
    sort(_removeFiles.begin(), _removeFiles.end(), FileInfoLess());
    sort(_updateFiles.begin(), _updateFiles.end(), FileInfoLess());

    string pathLog = _dataDir + ".log";
    _log.open(pathLog.c_str());
    if(!_log)
    {
	throw "cannot open `" + pathLog + "' for writing: " + lastError();
    }

    return true;
}

bool
IcePatch2::Patcher::patch(const string& d)
{
    string dir = normalize(d);

    if(dir.empty() || dir == ".")
    {
	if(!_removeFiles.empty())
	{
	    if(!removeFiles(_removeFiles))
	    {
		return false;
	    }
	}
	
	if(!_updateFiles.empty())
	{
	    if(!updateFiles(_updateFiles))
	    {
		return false;
	    }
	}
	
	return true;
    }
    else
    {
	string dirWithSlash = dir + '/';

	FileInfoSeq::const_iterator p;

	FileInfoSeq remove;
	for(p = _removeFiles.begin(); p != _removeFiles.end(); ++p)
	{
	    if(p->size < 0) // Directory?
	    {
		if(p->path.compare(0, dir.size(), dir) == 0)
		{
		    remove.push_back(*p);
		}
	    }
	    else
	    {
		if(p->path.compare(0, dirWithSlash.size(), dirWithSlash) == 0)
		{
		    remove.push_back(*p);
		}
	    }
	}

	FileInfoSeq update;
	for(p = _updateFiles.begin(); p != _updateFiles.end(); ++p)
	{
	    if(p->size < 0) // Directory?
	    {
		if(p->path.compare(0, dir.size(), dir) == 0)
		{
		    update.push_back(*p);
		}
	    }
	    else
	    {
		if(p->path.compare(0, dirWithSlash.size(), dirWithSlash) == 0)
		{
		    update.push_back(*p);
		}
	    }
	}

	if(!remove.empty())
	{
	    if(!removeFiles(remove))
	    {
		return false;
	    }
	}
	
	if(!update.empty())
	{
	    if(!updateFiles(update))
	    {
		return false;
	    }
	}
	
	return true;
    }
}

void
IcePatch2::Patcher::finish()
{
    _log.close();

    saveFileInfoSeq(_dataDir, _localFiles);
}

bool
IcePatch2::Patcher::removeFiles(const FileInfoSeq& files)
{
    for(FileInfoSeq::const_reverse_iterator p = files.rbegin(); p != files.rend(); ++p)
    {
	remove(_dataDir + '/' + p->path);
	_log << '-' << *p << endl;
    }
    
    FileInfoSeq newLocalFiles;
    newLocalFiles.reserve(_localFiles.size());
    
    set_difference(_localFiles.begin(),
		   _localFiles.end(),
		   files.begin(),
		   files.end(),
		   back_inserter(newLocalFiles),
		   FileInfoLess());
    
    _localFiles.swap(newLocalFiles);
    
    FileInfoSeq newRemoveFiles;
    
    set_difference(_removeFiles.begin(),
		   _removeFiles.end(),
		   files.begin(),
		   files.end(),
		   back_inserter(newRemoveFiles),
		   FileInfoLess());
    
    _removeFiles.swap(newRemoveFiles);

    return true;
}
    
bool
IcePatch2::Patcher::updateFiles(const FileInfoSeq& files)
{
    DecompressorPtr decompressor = new Decompressor(_dataDir);
    decompressor->start();

    bool result;

    try
    {
	result = updateFilesInternal(files, decompressor);
    }
    catch(...)
    {
	decompressor->destroy();
	decompressor->getThreadControl().join();
	decompressor->log(_log);
	throw;
    }
    
    decompressor->destroy();
    decompressor->getThreadControl().join();
    decompressor->log(_log);
    decompressor->exception();

    return result;
}

bool
IcePatch2::Patcher::updateFilesInternal(const FileInfoSeq& files, const DecompressorPtr& decompressor)
{
    FileInfoSeq::const_iterator p;
    
    Long total = 0;
    Long updated = 0;
    
    for(p = files.begin(); p != files.end(); ++p)
    {
	if(p->size > 0) // Regular, non-empty file?
	{
	    total += p->size;
	}
    }
    
    for(p = files.begin(); p != files.end(); ++p)
    {
	if(p->size < 0) // Directory?
	{
	    createDirectoryRecursive(_dataDir + '/' + p->path);
	    _log << '+' << *p << endl;
	}
	else // Regular file.
	{
	    if(!_feedback->patchStart(p->path, p->size, updated, total))
	    {
		return false;
	    }

	    string pathBZ2 = _dataDir + '/' + p->path + ".bz2";
	    ofstream fileBZ2;
	    
	    string dir = getDirname(pathBZ2);
	    if(!dir.empty())
	    {
		createDirectoryRecursive(dir);
	    }
		
	    try
	    {
		removeRecursive(pathBZ2);
	    }
	    catch(...)
	    {
	    }
		
	    fileBZ2.open(pathBZ2.c_str(), ios::binary);
	    if(!fileBZ2)
	    {
		throw "cannot open `" + pathBZ2 + "' for writing: " + lastError();
	    }
	    
	    Int pos = 0;
	    string progress;
	    
	    while(pos < p->size)
	    {
		ByteSeq bytes;
		
		try
		{
		    bytes = _serverNoCompress->getFileCompressed(p->path, pos, _chunkSize);
		}
		catch(const FileAccessException& ex)
		{
		    throw "server error for `" + p->path + "':" + ex.reason;
		}
		
		if(bytes.empty())
		{
		    throw "size mismatch for `" + p->path + "'";
		}
		
		fileBZ2.write(reinterpret_cast<char*>(&bytes[0]), bytes.size());
		
		if(!fileBZ2)
		{
		    throw ": cannot write `" + pathBZ2 + "': " + lastError();
		}
		
		pos += bytes.size();
		updated += bytes.size();
		
		if(!_feedback->patchProgress(pos, p->size, updated, total))
		{
		    return false;
		}
	    }
	    
	    fileBZ2.close();

	    decompressor->log(_log);
	    decompressor->add(*p);
	
	    if(!_feedback->patchEnd())
	    {
		return false;
	    }
	}
    }

    FileInfoSeq newLocalFiles;
    newLocalFiles.reserve(_localFiles.size());
	
    set_union(_localFiles.begin(),
	      _localFiles.end(),
	      files.begin(),
	      files.end(),
	      back_inserter(newLocalFiles),
	      FileInfoLess());
	
    _localFiles.swap(newLocalFiles);

    FileInfoSeq newUpdateFiles;

    set_difference(_updateFiles.begin(),
		   _updateFiles.end(),
		   files.begin(),
		   files.end(),
		   back_inserter(newUpdateFiles),
		   FileInfoLess());
	
    _updateFiles.swap(newUpdateFiles);

    return true;
}