/** * @param InputInterface $input * @param OutputInterface $output * @param int|null $exitCode */ public function postRun(InputInterface $input, OutputInterface $output, $exitCode) { // Release lock if set if (!is_null($this->lockHandler)) { $this->lockHandler->release(); } }
/** * {@inheritdoc} */ protected final function execute(InputInterface $input, OutputInterface $output) { $lock = new LockHandler($this->getName()); if (!$lock->lock()) { $output->writeln('The command is already running in another process.'); return 1; } if (($errorCode = $this->executeLocked($input, $output)) > 0) { $lock->release(); return $errorCode; } $lock->release(); return 0; }
protected function execute(InputInterface $input, OutputInterface $output) { $lockHandler = new LockHandler('sendDeferredWelcome.lock'); if ($lockHandler->lock()) { $this->getContainer()->get('nyrodev')->increasePhpLimits(); $this->getContainer()->enterScope('request'); $this->getContainer()->set('request', new Request(), 'request'); $context = $this->getContainer()->get('router')->getContext(); $context->setScheme($this->getContainer()->getParameter('nyroCms.email.router_scheme')); $context->setHost($this->getContainer()->getParameter('nyroCms.email.router_host')); $context->setBaseUrl($this->getContainer()->getParameter('nyroCms.email.router_base_url')); $users = $this->getContainer()->get('nyrocms_db')->getUserRepository()->getForWelcomeEmails(); $nbUsers = count($users); $output->writeln($nbUsers . ' are activated or has as password key which ends today.'); if ($nbUsers > 0) { foreach ($users as $user) { $this->getContainer()->get('nyrocms_user')->sendWelcomeEmail($user); } } $output->writeln('End of welcome email sending.'); $lockHandler->release(); } else { $output->writeln('sendDeferredWelcome command is locked.'); } }
protected function execute(InputInterface $input, OutputInterface $output) { $lock = new LockHandler($this->getName()); if (!$lock->lock()) { $output->writeln('The command is already running in another process.'); return 0; } $repositoryName = $input->getArgument('repository'); if ($repositoryName) { $repository = $this->repositoryStorage->get($repositoryName); if ($repository === null) { throw new \InvalidArgumentException('Unknown repository ' . $repositoryName); } $repositories = [$repository]; } else { $repositories = $this->getRepositoriesToUpdate(); } foreach ($repositories as $repository) { $output->writeln(sprintf('Updating <info>%s</info>', $repository->getName())); $timer = microtime(true); $this->update($repository, $output); $output->writeln(sprintf('Took %ds', microtime(true) - $timer)); } $lock->release(); return 0; }
protected function execute(InputInterface $input, OutputInterface $output) { $lockHandler = new LockHandler('lock:test:run.lock', CACHE_PATH); var_dump($lockHandler->lock()); sleep(10); $lockHandler->release(); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $force = (bool) $input->getOption('force'); $verbose = (bool) $input->getOption('verbose'); $deployLock = $this->getContainer()->getParameter('kernel.cache_dir') . '/deploy.globallock'; if (file_exists($deployLock)) { if ($verbose) { $output->writeln('Aborting, ' . $deployLock . ' file present'); } return; } $doctrine = $this->getContainer()->get('doctrine'); if ($force) { $packages = $doctrine->getManager()->getConnection()->fetchAll('SELECT id FROM package ORDER BY id ASC'); } else { $packages = $doctrine->getRepository('PackagistWebBundle:Package')->getStalePackagesForDumping(); } $ids = array(); foreach ($packages as $package) { $ids[] = $package['id']; } $lock = new LockHandler('packagist_package_dumper'); ini_set('memory_limit', -1); gc_enable(); // another dumper is still active if (!$lock->lock()) { if ($verbose) { $output->writeln('Aborting, another dumper is still active'); } return; } $result = $this->getContainer()->get('packagist.package_dumper')->dump($ids, $force, $verbose); $lock->release(); return $result ? 0 : 1; }
protected function postRun(InputInterface $input, OutputInterface $output, $exitCode) { $this->getLoggingEnhancement()->postRun($input, $output, $exitCode); // Release lock if set if (!is_null($this->lockHandler)) { $this->lockHandler->release(); } }
protected function execute(InputInterface $input, OutputInterface $output) { $lock = new LockHandler('app:sendcoupons'); if (!$lock->lock()) { $output->writeln('The command is already running in another process.'); return 0; } $em = $this->getContainer()->get('doctrine')->getManager(); $repo = $em->getRepository('AppBundle\\Entity\\Customer'); $customers = $repo->findBy(['isActivated' => true, 'couponsHaveBeenSent' => false], ['datetimeActivation' => 'ASC'], 100); foreach ($customers as $customer) { $mapped = $this->getContainer()->get('couponmapper')->mapNToCustomer(6, $customer); if (!$mapped) { $output->writeln('Could not map coupon codes to customer ' . $customer->getId()); $lock->release(); return 1; } $couponcodesData = []; foreach ($customer->getCouponcodes() as $couponcode) { ob_start(); @QRcode::png($couponcode->getCode()); $imageData = ob_get_contents(); ob_end_clean(); $couponcodesData[] = base64_encode($imageData); } $useRemoteFont = true; if ($this->getContainer()->get('kernel')->getEnvironment() === 'test') { $useRemoteFont = false; // This decouples test runs from Internet connectivity } $pdfData = $this->getContainer()->get('knp_snappy.pdf')->getOutputFromHtml($this->getContainer()->get('templating')->render('AppBundle:coupons:index.html.twig', array('customer' => $customer, 'couponcodesData' => $couponcodesData, 'useRemoteFont' => $useRemoteFont))); if ($this->getContainer()->get('kernel')->getEnvironment() === 'dev') { file_put_contents('/var/tmp/coupon.pdf', $pdfData); } $fileLocator = $this->getContainer()->get('file_locator'); $brandsPdfPath = $fileLocator->locate('@AppBundle/Resources/other/Marken_Selbst_Vertragspartner_2015_09_24.pdf'); $message = \Swift_Message::newInstance()->setSubject('Ihre Rabattcodes für die Good Buy METRO Sonderaktion')->setFrom('*****@*****.**')->setTo($customer->getEmail())->setBody($this->getContainer()->get('templating')->render('Emails/couponCodes.html.twig', ['customer' => $customer]), 'text/html')->attach(\Swift_Attachment::newInstance($pdfData, 'Goodbye-Metro-Rabattcodes.pdf', 'application/pdf'))->attach(\Swift_Attachment::fromPath($brandsPdfPath, 'application/pdf')); $this->getContainer()->get('mailer')->send($message); $customer->setCouponsHaveBeenSent(true); $em->flush(); $output->writeln($customer->getEmail()); } $lock->release(); }
public function testLockReturnsFalseIfAlreadyLockedByAnotherCommand() { $command = new \FooLockCommand(); $lock = new LockHandler($command->getName()); $lock->lock(); $tester = new CommandTester($command); $this->assertSame(1, $tester->execute(array())); $lock->release(); $this->assertSame(2, $tester->execute(array())); }
/** * Tests the lock. */ public function testLock() { $lock = new LockHandler('contao:install'); $lock->lock(); $command = new InstallCommand('contao:install'); $tester = new CommandTester($command); $code = $tester->execute([]); $this->assertEquals(1, $code); $this->assertContains('The command is already running in another process.', $tester->getDisplay()); $lock->release(); }
public function testLockIsReleased() { $name = 'symfony-test-filesystem.lock'; $l1 = new LockHandler($name); $l2 = new LockHandler($name); $this->assertTrue($l1->lock()); $this->assertFalse($l2->lock()); $l1 = null; $this->assertTrue($l2->lock()); $l2->release(); }
/** * Tests the lock. */ public function testLock() { $lock = new LockHandler('contao:filesync'); $lock->lock(); $command = new FilesyncCommand('contao:filesync'); $command->setFramework($this->mockContaoFramework()); $tester = new CommandTester($command); $code = $tester->execute([]); $this->assertEquals(1, $code); $this->assertContains('The command is already running in another process.', $tester->getDisplay()); $lock->release(); }
protected function execute(InputInterface $input, OutputInterface $output) { // Create the lock: $lock = new LockHandler('go'); if (!$lock->lock()) { return 0xff; } $message = __METHOD__; $file = realpath(__DIR__ . '/../Resources/data/Siciarek_Jacek.vcf'); $vcard = new Vcard($file); $data = $vcard->getData(); $json = json_encode($data, JSON_PRETTY_PRINT); $output->writeln($json); // Release the lock: $lock->release(); }
/** * Tests the lock. */ public function testLock() { $lock = new LockHandler('contao:automator'); $lock->lock(); $command = new AutomatorCommand('contao:automator'); $command->setApplication($this->getApplication()); $command->setFramework($this->mockContaoFramework()); $tester = new CommandTester($command); /** @var QuestionHelper $helper */ $helper = $command->getHelper('question'); $helper->setInputStream($this->getStreamFromInput("\n")); $code = $tester->execute(['command' => $command->getName()]); $this->assertEquals(1, $code); $this->assertEquals("The command is already running in another process.\n", $tester->getDisplay()); $lock->release(); }
/** * (non-PHPdoc) * @see Symfony\Component\Console\Command.Command::execute() */ protected function execute(InputInterface $input, OutputInterface $output) { // create the lock $lock = new LockHandler($this->getName()); if (!$lock->lock()) { $output->writeln('The command is already running in another process.'); return 0; } $failedAddresses = array(); $sentMails = $this->getContainer()->get('azine_email_notifier_service')->sendNotifications($failedAddresses); $output->writeln(date(\DateTime::RFC2822) . " : " . str_pad($sentMails, 4, " ", STR_PAD_LEFT) . " emails have been processed."); if (sizeof($failedAddresses) > 0) { $output->writeln(date(\DateTime::RFC2822) . " : " . "The following email-addresses failed:"); foreach ($failedAddresses as $address) { $output->writeln(" " . $address); } } // (optional) release the lock (otherwise, PHP will do it for you automatically) $lock->release(); }
/** * Release the lock. * * @return void */ private function releaseLock() { $this->logger->info('Release lock file.'); $this->lock->release(); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $verbose = $input->getOption('verbose'); $force = $input->getOption('force'); $indexAll = $input->getOption('all'); $package = $input->getArgument('package'); $deployLock = $this->getContainer()->getParameter('kernel.cache_dir') . '/deploy.globallock'; if (file_exists($deployLock)) { if ($verbose) { $output->writeln('Aborting, ' . $deployLock . ' file present'); } return; } $doctrine = $this->getContainer()->get('doctrine'); $solarium = $this->getContainer()->get('solarium.client'); $redis = $this->getContainer()->get('snc_redis.default'); $downloadManager = $this->getContainer()->get('packagist.download_manager'); $favoriteManager = $this->getContainer()->get('packagist.favorite_manager'); $lock = new LockHandler('packagist_package_indexer'); // another dumper is still active if (!$lock->lock()) { if ($verbose) { $output->writeln('Aborting, another indexer is still active'); } return; } if ($package) { $packages = array(array('id' => $doctrine->getRepository('PackagistWebBundle:Package')->findOneByName($package)->getId())); } elseif ($force || $indexAll) { $packages = $doctrine->getManager()->getConnection()->fetchAll('SELECT id FROM package ORDER BY id ASC'); $doctrine->getManager()->getConnection()->executeQuery('UPDATE package SET indexedAt = NULL'); } else { $packages = $doctrine->getRepository('PackagistWebBundle:Package')->getStalePackagesForIndexing(); } $ids = array(); foreach ($packages as $row) { $ids[] = $row['id']; } // clear index before a full-update if ($force && !$package) { if ($verbose) { $output->writeln('Deleting existing index'); } $update = $solarium->createUpdate(); $update->addDeleteQuery('*:*'); $update->addCommit(); $solarium->update($update); } $total = count($ids); $current = 0; // update package index while ($ids) { $indexTime = new \DateTime(); $idsSlice = array_splice($ids, 0, 50); $packages = $doctrine->getRepository('PackagistWebBundle:Package')->findById($idsSlice); $update = $solarium->createUpdate(); $indexTimeUpdates = []; foreach ($packages as $package) { $current++; if ($verbose) { $output->writeln('[' . sprintf('%' . strlen($total) . 'd', $current) . '/' . $total . '] Indexing ' . $package->getName()); } try { $document = $update->createDocument(); $tags = $doctrine->getManager()->getConnection()->fetchAll('SELECT t.name FROM package p JOIN package_version pv ON p.id = pv.package_id JOIN version_tag vt ON vt.version_id = pv.id JOIN tag t ON t.id = vt.tag_id WHERE p.id = :id GROUP BY t.id, t.name', ['id' => $package->getId()]); foreach ($tags as $idx => $tag) { $tags[$idx] = $tag['name']; } $this->updateDocumentFromPackage($document, $package, $tags, $redis, $downloadManager, $favoriteManager); $update->addDocument($document); $indexTimeUpdates[$indexTime->format('Y-m-d H:i:s')][] = $package->getId(); } catch (\Exception $e) { $output->writeln('<error>Exception: ' . $e->getMessage() . ', skipping package ' . $package->getName() . '.</error>'); } $providers = $doctrine->getManager()->getConnection()->fetchAll('SELECT lp.packageName FROM package p JOIN package_version pv ON p.id = pv.package_id JOIN link_provide lp ON lp.version_id = pv.id WHERE p.id = :id AND pv.development = true GROUP BY lp.packageName', ['id' => $package->getId()]); foreach ($providers as $provided) { $provided = $provided['packageName']; try { $document = $update->createDocument(); $document->setField('id', $provided); $document->setField('name', $provided); $document->setField('package_name', ''); $document->setField('description', ''); $document->setField('type', 'virtual-package'); $document->setField('trendiness', 100); $document->setField('repository', ''); $document->setField('abandoned', 0); $document->setField('replacementPackage', ''); $update->addDocument($document); } catch (\Exception $e) { $output->writeln('<error>' . get_class($e) . ': ' . $e->getMessage() . ', skipping package ' . $package->getName() . ':provide:' . $provided . '</error>'); } } } try { $update->addCommit(); $solarium->update($update); } catch (\Exception $e) { $output->writeln('<error>' . get_class($e) . ': ' . $e->getMessage() . ', occurred while processing packages: ' . implode(',', $idsSlice) . '</error>'); } $doctrine->getManager()->clear(); unset($packages); if ($verbose) { $output->writeln('Updating package index times'); } foreach ($indexTimeUpdates as $dt => $idsToUpdate) { $retries = 5; // retry loop in case of a lock timeout while ($retries--) { try { $doctrine->getManager()->getConnection()->executeQuery('UPDATE package SET indexedAt=:indexed WHERE id IN (:ids)', ['ids' => $idsToUpdate, 'indexed' => $dt], ['ids' => Connection::PARAM_INT_ARRAY]); } catch (\Exception $e) { if (!$retries) { throw $e; } sleep(2); } } } } $lock->release(); }
/** * During destruction an object it unlocks the file and then closes one. */ function __destruct() { fclose($this->fileHandler); $this->lockHandler->release(); }
/** * Creates cache file based on registered services * * If debug is false, it will only create the cache file if it doesn't already exist * * @return int Number of services cached */ public function createCache() { $lockHandler = new LockHandler(self::RETROFIT_LOCK_FILE); $lockHandler->lock(true); // loop through registered services and write to file foreach ($this->services as $service) { $classMetaDataProvider = new ClassMetaDataProvider($service); $generatedClassMetaDataProvider = new GeneratedClassMetaDataProvider($classMetaDataProvider); $generatedClass = $this->restClientGenerator->generate($classMetaDataProvider, $generatedClassMetaDataProvider); $this->cacheWriter->write($generatedClassMetaDataProvider, $generatedClass); } $lockHandler->release(); return count($this->services); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $verbose = $input->getOption('verbose'); $force = $input->getOption('force'); $indexAll = $input->getOption('all'); $package = $input->getArgument('package'); $deployLock = $this->getContainer()->getParameter('kernel.cache_dir') . '/deploy.globallock'; if (file_exists($deployLock)) { if ($verbose) { $output->writeln('Aborting, ' . $deployLock . ' file present'); } return; } $doctrine = $this->getContainer()->get('doctrine'); $solarium = $this->getContainer()->get('solarium.client'); $redis = $this->getContainer()->get('snc_redis.default'); $downloadManager = $this->getContainer()->get('packagist.download_manager'); $favoriteManager = $this->getContainer()->get('packagist.favorite_manager'); $lock = new LockHandler('packagist_package_indexer'); // another dumper is still active if (!$lock->lock()) { if ($verbose) { $output->writeln('Aborting, another indexer is still active'); } return; } if ($package) { $packages = array(array('id' => $doctrine->getRepository('PackagistWebBundle:Package')->findOneByName($package)->getId())); } elseif ($force || $indexAll) { $packages = $doctrine->getManager()->getConnection()->fetchAll('SELECT id FROM package ORDER BY id ASC'); $doctrine->getManager()->getConnection()->executeQuery('UPDATE package SET indexedAt = NULL'); } else { $packages = $doctrine->getRepository('PackagistWebBundle:Package')->getStalePackagesForIndexing(); } $ids = array(); foreach ($packages as $row) { $ids[] = $row['id']; } // clear index before a full-update if ($force && !$package) { if ($verbose) { $output->writeln('Deleting existing index'); } $update = $solarium->createUpdate(); $update->addDeleteQuery('*:*'); $update->addCommit(); $solarium->update($update); } $total = count($ids); $current = 0; // update package index while ($ids) { $packages = $doctrine->getRepository('PackagistWebBundle:Package')->getPackagesWithVersions(array_splice($ids, 0, 50)); $update = $solarium->createUpdate(); foreach ($packages as $package) { $current++; if ($verbose) { $output->writeln('[' . sprintf('%' . strlen($total) . 'd', $current) . '/' . $total . '] Indexing ' . $package->getName()); } try { $document = $update->createDocument(); $this->updateDocumentFromPackage($document, $package, $redis, $downloadManager, $favoriteManager); $update->addDocument($document); $package->setIndexedAt(new \DateTime()); } catch (\Exception $e) { $output->writeln('<error>Exception: ' . $e->getMessage() . ', skipping package ' . $package->getName() . '.</error>'); } foreach ($package->getVersions() as $version) { // abort when a non-dev version shows up since dev ones are ordered first if (!$version->isDevelopment()) { break; } if (count($provide = $version->getProvide())) { foreach ($version->getProvide() as $provide) { try { $document = $update->createDocument(); $document->setField('id', $provide->getPackageName()); $document->setField('name', $provide->getPackageName()); $document->setField('description', ''); $document->setField('type', 'virtual-package'); $document->setField('trendiness', 100); $document->setField('repository', ''); $document->setField('abandoned', 0); $document->setField('replacementPackage', ''); $update->addDocument($document); } catch (\Exception $e) { $output->writeln('<error>' . get_class($e) . ': ' . $e->getMessage() . ', skipping package ' . $package->getName() . ':provide:' . $provide->getPackageName() . '</error>'); } } } } } $update->addCommit(); $solarium->update($update); foreach ($packages as $package) { $doctrine->getManager()->flush($package); } $doctrine->getManager()->clear(); unset($packages); } $lock->release(); }