3 namespace CoreFramework\Stack\File;
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
9 * A general file-based stack class
11 * @author Roland Haeder <webmaster@ship-simu.org>
13 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
14 * @license GNU GPL 3.0 or any newer version
15 * @link http://www.ship-simu.org
17 * This program is free software: you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation, either version 3 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program. If not, see <http://www.gnu.org/licenses/>.
30 class BaseFileStack extends BaseStacker {
32 * Magic for this stack
34 const STACK_MAGIC = 'STACKv0.1';
37 * Name of array index for gap position
39 const ARRAY_INDEX_GAP_POSITION = 'gap';
42 * Name of array index for hash
44 const ARRAY_INDEX_HASH = 'hash';
47 * Name of array index for length of raw data
49 const ARRAY_INDEX_DATA_LENGTH = 'length';
52 * Protected constructor
54 * @param $className Name of the class
57 protected function __construct ($className) {
58 // Call parent constructor
59 parent::__construct($className);
63 * Reads the file header
66 * @todo To hard assertions here, better rewrite them to exceptions
68 public function readFileHeader () {
69 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
71 // First rewind to beginning as the header sits at the beginning ...
72 $this->getIteratorInstance()->rewind();
74 // Then read it (see constructor for calculation)
75 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
76 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
78 // Have all requested bytes been read?
79 assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
80 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
82 // Last character must be the separator
83 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
84 assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
85 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
87 // Okay, then remove it
88 $data = substr($data, 0, -1);
90 // And update seek position
91 $this->getIteratorInstance()->updateSeekPosition();
98 * 2 => current seek position
100 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
103 $this->getIteratorInstance()->setHeader($header);
105 // Check if the array has only 3 elements
106 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, TRUE)));
107 assert(count($header) == 3);
108 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
111 assert($header[0] == self::STACK_MAGIC);
112 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
114 // Check length of count and seek position
115 assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
116 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
117 assert(strlen($header[2]) == BaseBinaryFile::LENGTH_POSITION);
118 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
120 // Decode count and seek position
121 $header[1] = hex2bin($header[1]);
122 $header[2] = hex2bin($header[2]);
124 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
128 * Flushes the file header
132 public function flushFileHeader () {
133 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
135 // Put all informations together
136 $header = sprintf('%s%s%s%s%s%s',
140 // Separator magic<->count
141 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
143 // Total entries (will be zero) and pad it to 20 chars
144 str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
146 // Separator count<->seek position
147 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
149 // Position (will be zero)
150 str_pad($this->dec2hex($this->getIteratorInstance()->getSeekPosition(), 2), BaseBinaryFile::LENGTH_POSITION, '0', STR_PAD_LEFT),
152 // Separator position<->entries
153 chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
156 // Write it to disk (header is always at seek position 0)
157 $this->getIteratorInstance()->writeData(0, $header, FALSE);
159 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
163 * Initializes this file-based stack.
165 * @param $fileName File name of this stack
166 * @param $type Type of this stack (e.g. url_source for URL sources)
168 * @todo Currently the stack file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole stack file.
170 protected function initFileStack ($fileName, $type) {
171 // Get a stack file instance
172 $fileInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileName, $this));
174 // Get iterator instance
175 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
177 // Is the instance implementing the right interface?
178 assert($iteratorInstance instanceof SeekableWritableFileIterator);
181 $this->setIteratorInstance($iteratorInstance);
183 // Calculate header size
184 $this->getIteratorInstance()->setHeaderSize(
185 strlen(self::STACK_MAGIC) +
186 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
187 BaseBinaryFile::LENGTH_COUNT +
188 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
189 BaseBinaryFile::LENGTH_POSITION +
190 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
193 // Init counters and gaps array
194 $this->getIteratorInstance()->initCountersGapsArray();
196 // Is the file's header initialized?
197 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
198 // No, then create it (which may pre-allocate the stack)
199 $this->getIteratorInstance()->createFileHeader();
201 // And pre-allocate a bit
202 $this->getIteratorInstance()->preAllocateFile('file_stack');
205 // Load the file header
206 $this->readFileHeader();
208 // Count all entries in file
209 $this->getIteratorInstance()->analyzeFile();
212 * Get stack index instance. This can be used for faster
213 * "defragmentation" and startup.
215 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileName, $type);
218 $this->setIndexInstance($indexInstance);
222 * Adds a value to given stack
224 * @param $stackerName Name of the stack
225 * @param $value Value to add to this stacker
227 * @throws FullStackerException If the stack is full
229 protected function addValue ($stackerName, $value) {
231 if ($this->isStackFull($stackerName)) {
233 throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
237 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
239 // No objects/resources are allowed as their serialization takes to long
240 assert(!is_object($value));
241 assert(!is_resource($value));
244 * Now add the value to the file stack which returns gap position, a
245 * hash and length of the raw data.
247 $data = $this->getIteratorInstance()->writeValueToFile($stackerName, $value);
249 // Add the hash and gap position to the index
250 $this->getIndexInstance()->addHashToIndex($stackerName, $data);
254 * Get last value from named stacker
256 * @param $stackerName Name of the stack
257 * @return $value Value of last added value
258 * @throws EmptyStackerException If the stack is empty
260 protected function getLastValue ($stackerName) {
261 // Is the stack not yet initialized or full?
262 if ($this->isStackEmpty($stackerName)) {
263 // Throw an exception
264 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
267 // Now get the last value
268 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
276 * Get first value from named stacker
278 * @param $stackerName Name of the stack
279 * @return $value Value of last added value
280 * @throws EmptyStackerException If the stack is empty
282 protected function getFirstValue ($stackerName) {
283 // Is the stack not yet initialized or full?
284 if ($this->isStackEmpty($stackerName)) {
285 // Throw an exception
286 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
289 // Now get the first value
290 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
298 * "Pops" last entry from stack
300 * @param $stackerName Name of the stack
301 * @return $value Value "poped" from array
302 * @throws EmptyStackerException If the stack is empty
304 protected function popLast ($stackerName) {
305 // Is the stack not yet initialized or full?
306 if ($this->isStackEmpty($stackerName)) {
307 // Throw an exception
308 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
311 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
312 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
317 * "Pops" first entry from stack
319 * @param $stackerName Name of the stack
320 * @return $value Value "shifted" from array
321 * @throws EmptyStackerException If the named stacker is empty
323 protected function popFirst ($stackerName) {
324 // Is the stack not yet initialized or full?
325 if ($this->isStackEmpty($stackerName)) {
326 // Throw an exception
327 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
330 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
331 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
336 * Checks whether the given stack is full
338 * @param $stackerName Name of the stack
339 * @return $isFull Whether the stack is full
341 protected function isStackFull ($stackerName) {
342 // File-based stacks will only run full if the disk space is low.
343 // @TODO Please implement this, returning FALSE
351 * Checks whether the given stack is empty
353 * @param $stackerName Name of the stack
354 * @return $isEmpty Whether the stack is empty
355 * @throws NoStackerException If given stack is missing
357 public function isStackEmpty ($stackerName) {
358 // So, is the stack empty?
359 $isEmpty = (($this->getStackCount($stackerName)) == 0);
366 * Initializes given stacker
368 * @param $stackerName Name of the stack
369 * @param $forceReInit Force re-initialization
371 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
373 public function initStack ($stackerName, $forceReInit = FALSE) {
374 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
378 * Initializes all stacks
381 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
383 public function initStacks (array $stacks, $forceReInit = FALSE) {
384 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
388 * Checks whether the given stack is initialized (set in array $stackers)
390 * @param $stackerName Name of the stack
391 * @return $isInitialized Whether the stack is initialized
392 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
394 public function isStackInitialized ($stackerName) {
395 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
399 * Determines whether the EOF has been reached
401 * @return $isEndOfFileReached Whether the EOF has been reached
402 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
404 public function isEndOfFileReached () {
405 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
409 * Getter for file name
411 * @return $fileName The current file name
412 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
414 public function getFileName () {
415 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
419 * Getter for size of given stack (array count)
421 * @param $stackerName Name of the stack
422 * @return $count Size of stack (array count)
424 public function getStackCount ($stackerName) {
425 // Now, simply return the found count value, this must be up-to-date then!
426 return $this->getIteratorInstance()->getCounter();
430 * Calculates minimum length for one entry/block
432 * @return $length Minimum length for one entry/block
434 public function calculateMinimumBlockLength () {
437 // Length of entry group
438 BaseBinaryFile::LENGTH_GROUP + strlen(chr(BaseBinaryFile::SEPARATOR_GROUP_HASH)) +
440 self::getHashLength() + strlen(chr(BaseBinaryFile::SEPARATOR_HASH_VALUE)) + 1 +
442 strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
449 * Initializes counter for valid entries, arrays for damaged entries and
450 * an array for gap seek positions. If you call this method on your own,
451 * please re-analyze the file structure. So you are better to call
452 * analyzeFile() instead of this method.
455 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
457 public function initCountersGapsArray () {
458 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
462 * Getter for header size
464 * @return $totalEntries Size of file header
465 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
467 public final function getHeaderSize () {
468 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
472 * Setter for header size
474 * @param $headerSize Size of file header
476 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
478 public final function setHeaderSize ($headerSize) {
479 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
483 * Getter for header array
485 * @return $totalEntries Size of file header
486 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
488 public final function getHeader () {
489 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
495 * @param $header Array for a file header
497 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
499 public final function setHeader (array $header) {
500 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
504 * Updates seekPosition attribute from file to avoid to much access on file.
507 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
509 public function updateSeekPosition () {
510 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
514 * Getter for total entries
516 * @return $totalEntries Total entries in this file
517 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
519 public final function getCounter () {
520 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
524 * Writes data at given position
526 * @param $seekPosition Seek position
527 * @param $data Data to be written
528 * @param $flushHeader Whether to flush the header (default: flush)
530 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
532 public function writeData ($seekPosition, $data, $flushHeader = TRUE) {
533 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
534 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
538 * Writes given value to the file and returns a hash and gap position for it
540 * @param $groupId Group identifier
541 * @param $value Value to be added to the stack
542 * @return $data Hash and gap position
543 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
545 public function writeValueToFile ($groupId, $value) {
546 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,value[%s]=%s', __METHOD__, __LINE__, $groupId, gettype($value), print_r($value, TRUE)));
547 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
551 * Searches for next suitable gap the given length of data can fit in
552 * including padding bytes.
554 * @param $length Length of raw data
555 * @return $seekPosition Found next gap's seek position
556 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
558 public function searchNextGap ($length) {
559 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] length=%s', __METHOD__, __LINE__, $length));
560 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
564 * "Getter" for file size
566 * @return $fileSize Size of currently loaded file
568 public function getFileSize () {
569 // Call iterator's method
570 return $this->getIteratorInstance()->getFileSize();
574 * Writes given raw data to the file and returns a gap position and length
576 * @param $groupId Group identifier
577 * @param $hash Hash from encoded value
578 * @param $encoded Encoded value to be written to the file
579 * @return $data Gap position and length of the raw data
581 public function writeDataToFreeGap ($groupId, $hash, $encoded) {
583 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,encoded()=%d - CALLED!', __METHOD__, __LINE__, $groupId, $hash, strlen($encoded)));
585 // Raw data been written to the file
586 $rawData = sprintf('%s%s%s%s%s',
588 BaseBinaryFile::SEPARATOR_GROUP_HASH,
590 BaseBinaryFile::SEPARATOR_HASH_VALUE,
595 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
597 // Search for next free gap
598 $gapPosition = $this->getIteratorInstance()->searchNextGap(strlen($rawData));
600 // Gap position cannot be smaller than header length + 1
601 assert($gapPosition > $this->getIteratorInstance()->getHeaderSize());
604 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,gapPosition=%s', __METHOD__, __LINE__, $groupId, $hash, $gapPosition));
606 // Then write the data at that gap
607 $this->getIteratorInstance()->writeData($gapPosition, $rawData);
610 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d - EXIT!', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
612 // Return gap position, hash and length of raw data
614 self::ARRAY_INDEX_GAP_POSITION => $gapPosition,
615 self::ARRAY_INDEX_HASH => $hash,
616 self::ARRAY_INDEX_DATA_LENGTH => strlen($rawData)