How to stop assetic watch in Symfony2? - symfony

I followed the Symfony2 guide to automatically dump assetic files in dev mode:
I changed the use_controller parameter to false in my dev config file.
And I started the --watch routine.
$ php app/console assetic:dump --watch
How can I stop watching?

Command looking for file changes only while it working itself. So then you stop command - no more automatic regenerating assets.
On linux its typical ctrl+c or ctrl+x
P.S. some code from DumpCommand
while (true) {
try {
foreach ($this->am->getNames() as $name) {
if ($this->checkAsset($name, $previously)) {
$this->dumpAsset($name, $output);
}
}
// reset the asset manager
$prop->setValue($this->am, array());
$this->am->load();
file_put_contents($cache, serialize($previously));
$error = '';
} catch (\Exception $e) {
if ($error != $msg = $e->getMessage()) {
$output->writeln('<error>[error]</error> '.$msg);
$error = $msg;
}
}
sleep($input->getOption('period'));
}

Like #forgottenbas points out the code runs in an infinite loop so it's not really a background worker but simply a worker that occupies your shell until an outside force intervenes.
Generally the developer can kill the process or the shell session it's occupying.
On OSX ctrl + c sends SIGKILL, for instance.
In Windows it seems to work a bit differently in Window shells: http://en.wikipedia.org/wiki/Kill_(command)#Microsoft_Windows
It's definitely OS, or more accurately, shell dependent.

If you have spawned a linux background process, e.g.:
$ php app/console assetic:dump --watch &
you have to kill the php process that is running

Related

Unittesting a Symfony 4.2 process runs infinite loop (than times out), wihout unittest it works fine

Lets say I have the following Symfony 4 command:
class Command1 extends Command {
protected static $defaultName = 'app:command1';
protected function execute(InputInterface $input, OutputInterface $output){
$process = new Process('bin/console list', getcwd());
$process->start(); // or even $process->run() does not matter if its async or not
// ... where we handle if its finished, etc...
}
}
If I simply call bin/console app:command1 it will return the expected command list. Basically works as I expect.
But if I have a phpunit test which uses the Symfony\Component\Console\Application::run() to start this command, I end up in an "infinite loop" (well, actually not, it times out after 60 sec) in the Symfony\Component\Process::wait() in the
do {
$this->checkTimeout();
$running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
$this->readPipes($running, '\\' !== \DIRECTORY_SEPARATOR || !$running);
} while ($running);
where the $this->processPipes->areOpen() will be always open.
It seems to me, if I use any Symfony console command in a Process through phpunit, there will be always two pipes open like these:
1 = {resource} resource id='x' type='stream'
2 = {resource} resource id='z' type='stream'
but I don't know what are these actually. I also saw in htop, that the start()'s proc_open actually starts up a new process, but it just hangs (does absolutely nothing, cant even debug it), until times out. Nothing in error logs (other than the timeout).

Limit number of instances of Symfony Command

I have a command in my Symfony app launched by Cron. I want to be able to limit the number of instances executed at the same time on my server, let's say 4 instances. I don't have any clue on how to do this. I found how to lock the command to launch the command only one time and wait for it to finish, but I don't know how to launch more than one and limit the number of instances anyway.
Do you have an idea ?
What you are looking for is a semaphore.
There is a LockComponent currently scheduled for 3.4 (was pulled from 3.3). It is a major improvement over the LockHandler in the FilesystemComponent.
In a pinch, you can probably pool a fixed number of locks from the LockHandler. I don't recommend it, because it uses flock on the filesystem. This limits the lock to a single server. Additionally, flock may be limited to the process scope on some systems.
<?php
use Symfony\Component\Filesystem\LockHandler;
define('LOCK_ID', 'some-identifier');
define('LOCK_MAX', 5);
$lockPool = [];
for ($i = 0; $i <= LOCK_MAX;) {
$lockHandle = sprintf('%s-%s.lock', LOCK_ID, ++$i);
$lockPool[$i] = new LockHandler($lockHandle);
}
$activeLock = null;
$lockTimeout = 60 * 1000;
$lockWaitStart = microtime(true);
while(!$activeLock) {
foreach ($lockPool as $lockHandler) {
if ($lockHandler->lock()) {
$activeLock = $lockHandler;
break 2;
}
}
if ($lockTimeout && ($lockTimeout > microtime(true) - $lockWaitStart)) {
break;
}
// Randomly wait between 0.1ms and 10ms
usleep(mt_rand(100, 10000));
}
A much better and efficient solution would be to use the semaphore extension and work some magic with ftok, shm_* and sem_*.
i suggest you to use a process control system as supervisor. it's pretty simple to use and you can choose how many instance of your script you start.
http://supervisord.org/
You could use a shared counter file which holds a counter that gets increased when the Command starts running and decreases it before it's finished.
Another solution would be checking the process list with something like this:
$processCount = exec('ps aux | grep "some part of the console command you run" | grep -v "grep" | wc -l' );
if(!empty($processCount) && $processCount >= X) {
return false;
}
You can create a "launcher command" executed by your cron or supervisor.
This Symfony commad can launch your instances with the process component on your server. You can also check whatever you want to check and do everything you want to do like the exec php function.

Download Multiple Files from http using Powershell with proper names

I have searched for something similar and I keep running across the FTP download answers. This is helpful information, but ultimately proving to be difficult to translate. I have found a powershell script and it works, but I am wondering if it can be tweaked for my needs. I don't have much experience with powershell scripting, but I'm trying to learn.
The need is this. I need to download and install a series of files to a remote machine, unattended. The files are distributed via email via tinyurls. I currently throw those into a .txt file, then have a powershell script read the list and download each file.
Requirements of the project and why I have turned to powershell (and not other utilities), is that these are very specialized machines. The only tools available are ones that are baked into Windows 7 embedded.
The difficulties I run into are:
The files download one at the time. I would like to grab as many downloads at the same time that the web server will allow. (usually 6)
The current script creates file names based off the tinyurl. I need the actual file name from the webserver.
Thanks in advance for any suggestions.
Below is the script I’m currently using.
# Copyright (C) 2011 by David Wright (davidwright#digitalwindfire.com)
# All Rights Reserved.
# Redistribution and use in source and binary forms, with or without
# modification or permission, are permitted.
# Additional information available at http://www.digitalwindfire.com.
$folder = "d:\downloads\"
$userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"
$web = New-Object System.Net.WebClient
$web.Headers.Add("user-agent", $userAgent)
Get-Content "d:\downloads\files.txt" |
Foreach-Object {
"Downloading " + $_
try {
$target = join-path $folder ([io.path]::getfilename($_))
$web.DownloadFile($_, $target)
} catch {
$_.Exception.Message
}
}
If you do the web request before you decide on file name you should be able to get the expanded path (otherwise you would have to make two web requests, one to get the extended path and one to download the file).
When I tried this, I found that the BaseResponse property of the Microsoft.PowerShell.Commands.HtmlWebResponseObject returned by the Invoke-WebRequest cmdlet had a ResponseUri property which was the extended path we are looking for.
If you get the correct response, just save the file using the name from the extended path, something like the following (this sample code does not look at HTTP response codes or similar, but expects everything to go well):
function Save-TinyUrlFile
{
PARAM (
$TinyUrl,
$DestinationFolder
)
$response = Invoke-WebRequest -Uri $TinyUrl
$filename = [System.IO.Path]::GetFileName($response.BaseResponse.ResponseUri.OriginalString)
$filepath = [System.IO.Path]::Combine($DestinationFolder, $filename)
try
{
$filestream = [System.IO.File]::Create($filepath)
$response.RawContentStream.WriteTo($filestream)
$filestream.Close()
}
finally
{
if ($filestream)
{
$filestream.Dispose();
}
}
}
This method could be called using something like the following, given that the $HOME\Documents\Temp folder exists:
Save-TinyUrlFile -TinyUrl http://tinyurl.com/ojt3lgz -DestinationFolder $HOME\Documents\Temp
On my computer, that saves a file called robots.txt, taken from a github repository, to my computer.
If you want to download many files at the same time, you could let PowerShell make this happen for you. Either use PowerShell workflows parallel functionality or simply start a Job for each url. Here's a sample on how you could do it using PowerShell Jobs:
Get-Content files.txt | Foreach {
Start-Job {
function Save-TinyUrlFile
{
PARAM (
$TinyUrl,
$DestinationFolder
)
$response = Invoke-WebRequest -Uri $TinyUrl
$filename = [System.IO.Path]::GetFileName($response.BaseResponse.ResponseUri.OriginalString)
$filepath = [System.IO.Path]::Combine($DestinationFolder, $filename)
try
{
$filestream = [System.IO.File]::Create($filepath)
$response.RawContentStream.WriteTo($filestream)
$filestream.Close()
}
finally
{
if ($filestream)
{
$filestream.Dispose();
}
}
}
Save-TinyUrlFile -TinyUrl $args[0] -DestinationFolder $args[1]
} -ArgumentList $_, "$HOME\documents\temp"
}

PHPUnit Selenium2 - No Browser Instance

When I run even a sample test, either in Netbeans IDE of from the command line, e.g.:
class WebTest extends PHPUnit_Extensions_Selenium2TestCase
{
protected function setUp()
{
$this->setBrowser('firefox');
$this->setBrowserUrl('http://www.example.com/');
}
public function testTitle()
{
$this->url('http://www.example.com/');
$this->assertEquals('Example WWW Page', $this->title());
}
}
I get the PHPUnit response, but it doesn't seem to be communication with the Selenium server as no browser window was created.
PHPUnit 3.6.10 by Sebastian Bergmann.
Configuration read from /var/www/gcd/framework/yii/gadget/protected/tests/phpunit.xml
F
Time: 1 second, Memory: 10.50Mb
There was 1 failure:
1) WebTest::testTitle
Failed asserting that null matches expected 'Example WWW Page'.
Using PHPUnit 3.6.10 and selenium-server-standalone-2.21.0
Anyone any ideas?
Turns out, if you run PHPUnit with sudo, it works! Doh!

PHPUnit Performance / Test Timeout

I am building a testing script which is checking the performance of a set of commands. The test script needs to let it run for a specific amount of time before failing the test.
I found the PerformanceTestCase in the PHPUnit documentation website, but when I tried to use it I realised that it's old functionality which hasn't been included within the new version. (That doc is PHPUnit 3.0, and my version is 3.5).
Is there an equivalent for this functionality within PHPUnit 3.5, and how do I use it?
Well, you could simply do something like
public function testFoo() {
$tStart = microtime( true );
// your time critical commands
$tDiff = microtime( true ) - $tStart;
$this->assertLessThan( $maxTime, $tDiff, 'Took too long' );
}
Of course this means that your commands will not be interrupted before being finished.
And IMO unittests are not meant for testing performance.
I ran into a smiliar issue today - I needed to test an external HTTP call was occuring within the allocated time.
Rather than build another loop or take $start and $end time readings - I exposed the timed_out param, detailed here http://www.php.net/manual/en/function.stream-get-meta-data.php
while (!feof($fp)) {
$info = stream_get_meta_data($fp);
if ($info['timed_out']) {
$this->timed_out = true;
fclose($fp);
throw new Exception("Request timed out");
}
else {
$response .= fgets($fp, 128);
}
}
fclose($fp);

Resources