3 namespace CoreFramework\Stack\File;
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7 use CoreFramework\Filesystem\File\BaseBinaryFile;
8 use CoreFramework\Iterator\Filesystem\SeekableWritableFileIterator;
11 * A general file-based stack class
13 * @author Roland Haeder <webmaster@ship-simu.org>
15 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
16 * @license GNU GPL 3.0 or any newer version
17 * @link http://www.ship-simu.org
19 * This program is free software: you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation, either version 3 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
29 * You should have received a copy of the GNU General Public License
30 * along with this program. If not, see <http://www.gnu.org/licenses/>.
32 class BaseFileStack extends BaseStacker {
34 * Magic for this stack
36 const STACK_MAGIC = 'STACKv0.1';
39 * Name of array index for gap position
41 const ARRAY_INDEX_GAP_POSITION = 'gap';
44 * Name of array index for hash
46 const ARRAY_INDEX_HASH = 'hash';
49 * Name of array index for length of raw data
51 const ARRAY_INDEX_DATA_LENGTH = 'length';
54 * Protected constructor
56 * @param $className Name of the class
59 protected function __construct ($className) {
60 // Call parent constructor
61 parent::__construct($className);
65 * Reads the file header
68 * @todo To hard assertions here, better rewrite them to exceptions
70 public function readFileHeader () {
71 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
73 // First rewind to beginning as the header sits at the beginning ...
74 $this->getIteratorInstance()->rewind();
76 // Then read it (see constructor for calculation)
77 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
78 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
80 // Have all requested bytes been read?
81 assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
82 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
84 // Last character must be the separator
85 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
86 assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
87 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
89 // Okay, then remove it
90 $data = substr($data, 0, -1);
92 // And update seek position
93 $this->getIteratorInstance()->updateSeekPosition();
100 * 2 => current seek position
102 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
105 $this->getIteratorInstance()->setHeader($header);
107 // Check if the array has only 3 elements
108 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, TRUE)));
109 assert(count($header) == 3);
110 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
113 assert($header[0] == self::STACK_MAGIC);
114 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
116 // Check length of count and seek position
117 assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
118 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
119 assert(strlen($header[2]) == BaseBinaryFile::LENGTH_POSITION);
120 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
122 // Decode count and seek position
123 $header[1] = hex2bin($header[1]);
124 $header[2] = hex2bin($header[2]);
126 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
130 * Flushes the file header
134 public function flushFileHeader () {
135 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
137 // Put all informations together
138 $header = sprintf('%s%s%s%s%s%s',
142 // Separator magic<->count
143 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
145 // Total entries (will be zero) and pad it to 20 chars
146 str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
148 // Separator count<->seek position
149 chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
151 // Position (will be zero)
152 str_pad($this->dec2hex($this->getIteratorInstance()->getSeekPosition(), 2), BaseBinaryFile::LENGTH_POSITION, '0', STR_PAD_LEFT),
154 // Separator position<->entries
155 chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
158 // Write it to disk (header is always at seek position 0)
159 $this->getIteratorInstance()->writeData(0, $header, FALSE);
161 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
165 * Initializes this file-based stack.
167 * @param $fileName File name of this stack
168 * @param $type Type of this stack (e.g. url_source for URL sources)
170 * @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.
172 protected function initFileStack ($fileName, $type) {
173 // Get a stack file instance
174 $fileInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileName, $this));
176 // Get iterator instance
177 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
179 // Is the instance implementing the right interface?
180 assert($iteratorInstance instanceof SeekableWritableFileIterator);
183 $this->setIteratorInstance($iteratorInstance);
185 // Calculate header size
186 $this->getIteratorInstance()->setHeaderSize(
187 strlen(self::STACK_MAGIC) +
188 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
189 BaseBinaryFile::LENGTH_COUNT +
190 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
191 BaseBinaryFile::LENGTH_POSITION +
192 strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
195 // Init counters and gaps array
196 $this->getIteratorInstance()->initCountersGapsArray();
198 // Is the file's header initialized?
199 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
200 // No, then create it (which may pre-allocate the stack)
201 $this->getIteratorInstance()->createFileHeader();
203 // And pre-allocate a bit
204 $this->getIteratorInstance()->preAllocateFile('file_stack');
207 // Load the file header
208 $this->readFileHeader();
210 // Count all entries in file
211 $this->getIteratorInstance()->analyzeFile();
214 * Get stack index instance. This can be used for faster
215 * "defragmentation" and startup.
217 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileName, $type);
220 $this->setIndexInstance($indexInstance);
224 * Adds a value to given stack
226 * @param $stackerName Name of the stack
227 * @param $value Value to add to this stacker
229 * @throws FullStackerException If the stack is full
231 protected function addValue ($stackerName, $value) {
233 if ($this->isStackFull($stackerName)) {
235 throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
239 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
241 // No objects/resources are allowed as their serialization takes to long
242 assert(!is_object($value));
243 assert(!is_resource($value));
246 * Now add the value to the file stack which returns gap position, a
247 * hash and length of the raw data.
249 $data = $this->getIteratorInstance()->writeValueToFile($stackerName, $value);
251 // Add the hash and gap position to the index
252 $this->getIndexInstance()->addHashToIndex($stackerName, $data);
256 * Get last value from named stacker
258 * @param $stackerName Name of the stack
259 * @return $value Value of last added value
260 * @throws EmptyStackerException If the stack is empty
262 protected function getLastValue ($stackerName) {
263 // Is the stack not yet initialized or full?
264 if ($this->isStackEmpty($stackerName)) {
265 // Throw an exception
266 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
269 // Now get the last value
270 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
278 * Get first value from named stacker
280 * @param $stackerName Name of the stack
281 * @return $value Value of last added value
282 * @throws EmptyStackerException If the stack is empty
284 protected function getFirstValue ($stackerName) {
285 // Is the stack not yet initialized or full?
286 if ($this->isStackEmpty($stackerName)) {
287 // Throw an exception
288 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
291 // Now get the first value
292 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
300 * "Pops" last entry from stack
302 * @param $stackerName Name of the stack
303 * @return $value Value "poped" from array
304 * @throws EmptyStackerException If the stack is empty
306 protected function popLast ($stackerName) {
307 // Is the stack not yet initialized or full?
308 if ($this->isStackEmpty($stackerName)) {
309 // Throw an exception
310 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
313 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
314 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
319 * "Pops" first entry from stack
321 * @param $stackerName Name of the stack
322 * @return $value Value "shifted" from array
323 * @throws EmptyStackerException If the named stacker is empty
325 protected function popFirst ($stackerName) {
326 // Is the stack not yet initialized or full?
327 if ($this->isStackEmpty($stackerName)) {
328 // Throw an exception
329 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
332 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
333 /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
338 * Checks whether the given stack is full
340 * @param $stackerName Name of the stack
341 * @return $isFull Whether the stack is full
343 protected function isStackFull ($stackerName) {
344 // File-based stacks will only run full if the disk space is low.
345 // @TODO Please implement this, returning FALSE
353 * Checks whether the given stack is empty
355 * @param $stackerName Name of the stack
356 * @return $isEmpty Whether the stack is empty
357 * @throws NoStackerException If given stack is missing
359 public function isStackEmpty ($stackerName) {
360 // So, is the stack empty?
361 $isEmpty = (($this->getStackCount($stackerName)) == 0);
368 * Initializes given stacker
370 * @param $stackerName Name of the stack
371 * @param $forceReInit Force re-initialization
373 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
375 public function initStack ($stackerName, $forceReInit = FALSE) {
376 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
380 * Initializes all stacks
383 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
385 public function initStacks (array $stacks, $forceReInit = FALSE) {
386 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
390 * Checks whether the given stack is initialized (set in array $stackers)
392 * @param $stackerName Name of the stack
393 * @return $isInitialized Whether the stack is initialized
394 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
396 public function isStackInitialized ($stackerName) {
397 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
401 * Determines whether the EOF has been reached
403 * @return $isEndOfFileReached Whether the EOF has been reached
404 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
406 public function isEndOfFileReached () {
407 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
411 * Getter for file name
413 * @return $fileName The current file name
414 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
416 public function getFileName () {
417 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
421 * Getter for size of given stack (array count)
423 * @param $stackerName Name of the stack
424 * @return $count Size of stack (array count)
426 public function getStackCount ($stackerName) {
427 // Now, simply return the found count value, this must be up-to-date then!
428 return $this->getIteratorInstance()->getCounter();
432 * Calculates minimum length for one entry/block
434 * @return $length Minimum length for one entry/block
436 public function calculateMinimumBlockLength () {
439 // Length of entry group
440 BaseBinaryFile::LENGTH_GROUP + strlen(chr(BaseBinaryFile::SEPARATOR_GROUP_HASH)) +
442 self::getHashLength() + strlen(chr(BaseBinaryFile::SEPARATOR_HASH_VALUE)) + 1 +
444 strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
451 * Initializes counter for valid entries, arrays for damaged entries and
452 * an array for gap seek positions. If you call this method on your own,
453 * please re-analyze the file structure. So you are better to call
454 * analyzeFile() instead of this method.
457 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
459 public function initCountersGapsArray () {
460 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
464 * Getter for header size
466 * @return $totalEntries Size of file header
467 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
469 public final function getHeaderSize () {
470 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
474 * Setter for header size
476 * @param $headerSize Size of file header
478 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
480 public final function setHeaderSize ($headerSize) {
481 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
485 * Getter for header array
487 * @return $totalEntries Size of file header
488 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
490 public final function getHeader () {
491 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
497 * @param $header Array for a file header
499 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
501 public final function setHeader (array $header) {
502 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
506 * Updates seekPosition attribute from file to avoid to much access on file.
509 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
511 public function updateSeekPosition () {
512 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
516 * Getter for total entries
518 * @return $totalEntries Total entries in this file
519 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
521 public final function getCounter () {
522 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
526 * Writes data at given position
528 * @param $seekPosition Seek position
529 * @param $data Data to be written
530 * @param $flushHeader Whether to flush the header (default: flush)
532 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
534 public function writeData ($seekPosition, $data, $flushHeader = TRUE) {
535 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
536 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
540 * Writes given value to the file and returns a hash and gap position for it
542 * @param $groupId Group identifier
543 * @param $value Value to be added to the stack
544 * @return $data Hash and gap position
545 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
547 public function writeValueToFile ($groupId, $value) {
548 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,value[%s]=%s', __METHOD__, __LINE__, $groupId, gettype($value), print_r($value, TRUE)));
549 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
553 * Searches for next suitable gap the given length of data can fit in
554 * including padding bytes.
556 * @param $length Length of raw data
557 * @return $seekPosition Found next gap's seek position
558 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
560 public function searchNextGap ($length) {
561 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] length=%s', __METHOD__, __LINE__, $length));
562 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
566 * "Getter" for file size
568 * @return $fileSize Size of currently loaded file
570 public function getFileSize () {
571 // Call iterator's method
572 return $this->getIteratorInstance()->getFileSize();
576 * Writes given raw data to the file and returns a gap position and length
578 * @param $groupId Group identifier
579 * @param $hash Hash from encoded value
580 * @param $encoded Encoded value to be written to the file
581 * @return $data Gap position and length of the raw data
583 public function writeDataToFreeGap ($groupId, $hash, $encoded) {
585 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,encoded()=%d - CALLED!', __METHOD__, __LINE__, $groupId, $hash, strlen($encoded)));
587 // Raw data been written to the file
588 $rawData = sprintf('%s%s%s%s%s',
590 BaseBinaryFile::SEPARATOR_GROUP_HASH,
592 BaseBinaryFile::SEPARATOR_HASH_VALUE,
597 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
599 // Search for next free gap
600 $gapPosition = $this->getIteratorInstance()->searchNextGap(strlen($rawData));
602 // Gap position cannot be smaller than header length + 1
603 assert($gapPosition > $this->getIteratorInstance()->getHeaderSize());
606 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,gapPosition=%s', __METHOD__, __LINE__, $groupId, $hash, $gapPosition));
608 // Then write the data at that gap
609 $this->getIteratorInstance()->writeData($gapPosition, $rawData);
612 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d - EXIT!', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
614 // Return gap position, hash and length of raw data
616 self::ARRAY_INDEX_GAP_POSITION => $gapPosition,
617 self::ARRAY_INDEX_HASH => $hash,
618 self::ARRAY_INDEX_DATA_LENGTH => strlen($rawData)