3 namespace CoreFramework\Stack\File;
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7 use CoreFramework\Filesystem\File\BaseBinaryFile;
8 use CoreFramework\Generic\UnsupportedOperationException;
9 use CoreFramework\Iterator\Filesystem\SeekableWritableFileIterator;
12 * A general file-based stack class
14 * @author Roland Haeder <webmaster@ship-simu.org>
16 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
17 * @license GNU GPL 3.0 or any newer version
18 * @link http://www.ship-simu.org
20 * This program is free software: you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation, either version 3 of the License, or
23 * (at your option) any later version.
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
30 * You should have received a copy of the GNU General Public License
31 * along with this program. If not, see <http://www.gnu.org/licenses/>.
33 class BaseFileStack extends BaseStacker {
35 * Magic for this stack
37 const STACK_MAGIC = 'STACKv0.1';
40 * Name of array index for gap position
42 const ARRAY_INDEX_GAP_POSITION = 'gap';
45 * Name of array index for hash
47 const ARRAY_INDEX_HASH = 'hash';
50 * Name of array index for length of raw data
52 const ARRAY_INDEX_DATA_LENGTH = 'length';
55 * Protected constructor
57 * @param $className Name of the class
60 protected function __construct ($className) {
61 // Call parent constructor
62 parent::__construct($className);
66 * Reads the file header
69 * @todo To hard assertions here, better rewrite them to exceptions
71 public function readFileHeader () {
72 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
74 // First rewind to beginning as the header sits at the beginning ...
75 $this->getIteratorInstance()->rewind();
77 // Then read it (see constructor for calculation)
78 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
79 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
81 // Have all requested bytes been read?
82 assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
83 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
85 // Last character must be the separator
86 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
87 assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
88 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
90 // Okay, then remove it
91 $data = substr($data, 0, -1);
93 // And update seek position
94 $this->getIteratorInstance()->updateSeekPosition();
101 * 2 => current seek position
103 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
106 $this->getIteratorInstance()->setHeader($header);
108 // Check if the array has only 3 elements
109 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, true)));
110 assert(count($header) == 3);
111 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
114 assert($header[0] == self::STACK_MAGIC);
115 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
117 // Check length of count and seek position
118 assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
119 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
120 assert(strlen($header[2]) == BaseBinaryFile::LENGTH_POSITION);
121 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
123 // Decode count and seek position
124 $header[1] = hex2bin($header[1]);
125 $header[2] = hex2bin($header[2]);
127 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
131 * Flushes the file header
135 public function flushFileHeader () {
136 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
138 // Put all informations together
139 $header = sprintf('%s%s%s%s%s%s',
143 // Separator magic<->count
144 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
146 // Total entries (will be zero) and pad it to 20 chars
147 str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
149 // Separator count<->seek position
150 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
152 // Position (will be zero)
153 str_pad($this->dec2hex($this->getIteratorInstance()->getSeekPosition(), 2), BaseBinaryFile::LENGTH_POSITION, '0', STR_PAD_LEFT),
155 // Separator position<->entries
156 chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
159 // Write it to disk (header is always at seek position 0)
160 $this->getIteratorInstance()->writeData(0, $header, false);
162 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
166 * Initializes this file-based stack.
168 * @param $fileName File name of this stack
169 * @param $type Type of this stack (e.g. url_source for URL sources)
171 * @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.
173 protected function initFileStack ($fileName, $type) {
174 // Get a stack file instance
175 $fileInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileName, $this));
177 // Get iterator instance
178 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
180 // Is the instance implementing the right interface?
181 assert($iteratorInstance instanceof SeekableWritableFileIterator);
184 $this->setIteratorInstance($iteratorInstance);
186 // Calculate header size
187 $this->getIteratorInstance()->setHeaderSize(
188 strlen(self::STACK_MAGIC) +
189 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
190 BaseBinaryFile::LENGTH_COUNT +
191 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
192 BaseBinaryFile::LENGTH_POSITION +
193 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
196 // Init counters and gaps array
197 $this->getIteratorInstance()->initCountersGapsArray();
199 // Is the file's header initialized?
200 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
201 // No, then create it (which may pre-allocate the stack)
202 $this->getIteratorInstance()->createFileHeader();
204 // And pre-allocate a bit
205 $this->getIteratorInstance()->preAllocateFile('file_stack');
208 // Load the file header
209 $this->readFileHeader();
211 // Count all entries in file
212 $this->getIteratorInstance()->analyzeFile();
215 * Get stack index instance. This can be used for faster
216 * "defragmentation" and startup.
218 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileName, $type);
221 $this->setIndexInstance($indexInstance);
225 * Adds a value to given stack
227 * @param $stackerName Name of the stack
228 * @param $value Value to add to this stacker
230 * @throws FullStackerException If the stack is full
232 protected function addValue ($stackerName, $value) {
234 if ($this->isStackFull($stackerName)) {
236 throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
240 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName . ',value[' . gettype($value) . ']=' . print_r($value, true));
242 // No objects/resources are allowed as their serialization takes to long
243 assert(!is_object($value));
244 assert(!is_resource($value));
247 * Now add the value to the file stack which returns gap position, a
248 * hash and length of the raw data.
250 $data = $this->getIteratorInstance()->writeValueToFile($stackerName, $value);
252 // Add the hash and gap position to the index
253 $this->getIndexInstance()->addHashToIndex($stackerName, $data);
257 * Get last value from named stacker
259 * @param $stackerName Name of the stack
260 * @return $value Value of last added value
261 * @throws EmptyStackerException If the stack is empty
263 protected function getLastValue ($stackerName) {
264 // Is the stack not yet initialized or full?
265 if ($this->isStackEmpty($stackerName)) {
266 // Throw an exception
267 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
270 // Now get the last value
271 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
279 * Get first value from named stacker
281 * @param $stackerName Name of the stack
282 * @return $value Value of last added value
283 * @throws EmptyStackerException If the stack is empty
285 protected function getFirstValue ($stackerName) {
286 // Is the stack not yet initialized or full?
287 if ($this->isStackEmpty($stackerName)) {
288 // Throw an exception
289 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
292 // Now get the first value
293 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
301 * "Pops" last entry from stack
303 * @param $stackerName Name of the stack
304 * @return $value Value "poped" from array
305 * @throws EmptyStackerException If the stack is empty
307 protected function popLast ($stackerName) {
308 // Is the stack not yet initialized or full?
309 if ($this->isStackEmpty($stackerName)) {
310 // Throw an exception
311 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
314 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
315 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
320 * "Pops" first entry from stack
322 * @param $stackerName Name of the stack
323 * @return $value Value "shifted" from array
324 * @throws EmptyStackerException If the named stacker is empty
326 protected function popFirst ($stackerName) {
327 // Is the stack not yet initialized or full?
328 if ($this->isStackEmpty($stackerName)) {
329 // Throw an exception
330 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
333 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
334 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
339 * Checks whether the given stack is full
341 * @param $stackerName Name of the stack
342 * @return $isFull Whether the stack is full
344 protected function isStackFull ($stackerName) {
345 // File-based stacks will only run full if the disk space is low.
346 // @TODO Please implement this, returning false
354 * Checks whether the given stack is empty
356 * @param $stackerName Name of the stack
357 * @return $isEmpty Whether the stack is empty
358 * @throws NoStackerException If given stack is missing
360 public function isStackEmpty ($stackerName) {
361 // So, is the stack empty?
362 $isEmpty = (($this->getStackCount($stackerName)) == 0);
369 * Initializes given stacker
371 * @param $stackerName Name of the stack
372 * @param $forceReInit Force re-initialization
374 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
376 public function initStack ($stackerName, $forceReInit = false) {
377 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
381 * Initializes all stacks
384 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
386 public function initStacks (array $stacks, $forceReInit = false) {
387 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
391 * Checks whether the given stack is initialized (set in array $stackers)
393 * @param $stackerName Name of the stack
394 * @return $isInitialized Whether the stack is initialized
395 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
397 public function isStackInitialized ($stackerName) {
398 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
402 * Determines whether the EOF has been reached
404 * @return $isEndOfFileReached Whether the EOF has been reached
405 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
407 public function isEndOfFileReached () {
408 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
412 * Getter for file name
414 * @return $fileName The current file name
415 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
417 public function getFileName () {
418 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
422 * Getter for size of given stack (array count)
424 * @param $stackerName Name of the stack
425 * @return $count Size of stack (array count)
427 public function getStackCount ($stackerName) {
428 // Now, simply return the found count value, this must be up-to-date then!
429 return $this->getIteratorInstance()->getCounter();
433 * Calculates minimum length for one entry/block
435 * @return $length Minimum length for one entry/block
437 public function calculateMinimumBlockLength () {
440 // Length of entry group
441 BaseBinaryFile::LENGTH_GROUP + strlen(chr(BaseBinaryFile::SEPARATOR_GROUP_HASH)) +
443 self::getHashLength() + strlen(chr(BaseBinaryFile::SEPARATOR_HASH_VALUE)) + 1 +
445 strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
452 * Initializes counter for valid entries, arrays for damaged entries and
453 * an array for gap seek positions. If you call this method on your own,
454 * please re-analyze the file structure. So you are better to call
455 * analyzeFile() instead of this method.
458 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
460 public function initCountersGapsArray () {
461 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
465 * Getter for header size
467 * @return $totalEntries Size of file header
468 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
470 public final function getHeaderSize () {
471 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
475 * Setter for header size
477 * @param $headerSize Size of file header
479 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
481 public final function setHeaderSize ($headerSize) {
482 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
486 * Getter for header array
488 * @return $totalEntries Size of file header
489 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
491 public final function getHeader () {
492 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
498 * @param $header Array for a file header
500 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
502 public final function setHeader (array $header) {
503 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
507 * Updates seekPosition attribute from file to avoid to much access on file.
510 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
512 public function updateSeekPosition () {
513 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
517 * Getter for total entries
519 * @return $totalEntries Total entries in this file
520 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
522 public final function getCounter () {
523 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
527 * Writes data at given position
529 * @param $seekPosition Seek position
530 * @param $data Data to be written
531 * @param $flushHeader Whether to flush the header (default: flush)
533 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
535 public function writeData ($seekPosition, $data, $flushHeader = true) {
536 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
537 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
541 * Writes given value to the file and returns a hash and gap position for it
543 * @param $groupId Group identifier
544 * @param $value Value to be added to the stack
545 * @return $data Hash and gap position
546 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
548 public function writeValueToFile ($groupId, $value) {
549 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,value[%s]=%s', __METHOD__, __LINE__, $groupId, gettype($value), print_r($value, true)));
550 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
554 * Searches for next suitable gap the given length of data can fit in
555 * including padding bytes.
557 * @param $length Length of raw data
558 * @return $seekPosition Found next gap's seek position
559 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
561 public function searchNextGap ($length) {
562 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] length=%s', __METHOD__, __LINE__, $length));
563 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
567 * "Getter" for file size
569 * @return $fileSize Size of currently loaded file
571 public function getFileSize () {
572 // Call iterator's method
573 return $this->getIteratorInstance()->getFileSize();
577 * Writes given raw data to the file and returns a gap position and length
579 * @param $groupId Group identifier
580 * @param $hash Hash from encoded value
581 * @param $encoded Encoded value to be written to the file
582 * @return $data Gap position and length of the raw data
584 public function writeDataToFreeGap ($groupId, $hash, $encoded) {
586 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,encoded()=%d - CALLED!', __METHOD__, __LINE__, $groupId, $hash, strlen($encoded)));
588 // Raw data been written to the file
589 $rawData = sprintf('%s%s%s%s%s',
591 BaseBinaryFile::SEPARATOR_GROUP_HASH,
593 BaseBinaryFile::SEPARATOR_HASH_VALUE,
598 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
600 // Search for next free gap
601 $gapPosition = $this->getIteratorInstance()->searchNextGap(strlen($rawData));
603 // Gap position cannot be smaller than header length + 1
604 assert($gapPosition > $this->getIteratorInstance()->getHeaderSize());
607 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,gapPosition=%s', __METHOD__, __LINE__, $groupId, $hash, $gapPosition));
609 // Then write the data at that gap
610 $this->getIteratorInstance()->writeData($gapPosition, $rawData);
613 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d - EXIT!', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
615 // Return gap position, hash and length of raw data
617 self::ARRAY_INDEX_GAP_POSITION => $gapPosition,
618 self::ARRAY_INDEX_HASH => $hash,
619 self::ARRAY_INDEX_DATA_LENGTH => strlen($rawData)