I have the following queue config:
'queue' => [
'class' => \yii\queue\db\Queue::class,
'db' => 'db',
'tableName' => '{{%queue}}',
'channel' => 'default',
'mutex' => \yii\mutex\MysqlMutex::class,
'ttr' => 14400,
],
I wrote simple job that outputs current time in the console.
use yii\queue\JobInterface;
use yii\queue\Queue;
class DummyTimer implements JobInterface
{
public function run()
{
$strtime = time();
while($strtime + (4*60*60) > time())
echo date('H:i:s') . "\r\n";
}
public function execute($queue)
{
$this->run();
}
}
It runs only 300 seconds, and then gets killed with the next output in terminal:
2020-05-27 23:29:51 [8] app\modules\queue\DummyTimer (attempt: 1, pid:
7637) - Error
Symfony\Component\Process\Exception\ProcessTimedOutException: The process "'/usr/bin/php7.2' 'yii' 'queue/exec' '8' '300' '1' '7637'
'--color=1' '--verbose=1'" exceeded the timeout of 300 seconds.
So how to increase maximum lifetime of a job?
The original solution should be working just fine:
'queue' => [
'class' => \yii\queue\db\Queue::class,
'db' => 'db',
'tableName' => '{{%queue}}',
'channel' => 'default',
'mutex' => \yii\mutex\MysqlMutex::class,
'ttr' => 14400,
],
Stumbled upon the same issue and seemed that ttr in queue config did not work. But What I forgot to do was to re-start the queue process after changing the config. Works just fine with the configuration change if the queue is properly re-loaded with the new configuration.
Related
Have done Master Slave configuration as per official Yii2 documentation. Below is actual configuration look like,
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=1.1.1.1;dbname=master_db',
'username' => 'user',
'password' => 'password',
'charset' => 'utf8',
'enableSchemaCache' => true,
'schemaCacheDuration' => 10,
'schemaCache' => 'cache',
'slaveConfig' => [
'username' => 'slave_user',
'password' => 'slave_password',
'charset' => 'utf8',
'attributes' => [
// use a smaller connection timeout
PDO::ATTR_TIMEOUT => 10,
],
'enableSchemaCache' => true,
'schemaCacheDuration' => 10,
'schemaCache' => 'cache',
],
'slaves' => [
['dsn' => 'mysql:host=2.2.2.2;dbname=slave_db']
],
],
It always connect master database even if slave server is up and reachable.
Surprisingly replacing current master config with slave one works, moreover if try to connect slave database from command line it get connected in a moment but unable to achieve same with above configuration.
Wondering if there is any parameters missing in configuration or any other way to get things working like ideal read write splitting?
issue was resolved by adding connection class in the slaveConfig,
'class' => 'yii\db\Connection'
I use a Yii2 console application to run migrations. It's a very basic app, that goes like this (yii.php in the / folder of the project):
<?php
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';
$config = require __DIR__ . '/config/console.php';
(new yii\console\Application($config))->run();
?>
So when i run
php yii.php
Everything's fine, but when i run
php yii.php migrate/create create_user_table
I am getting an error message:
Error: Failed to instantiate component or class "db".
My Yii is v2.0.15.1
UPD 19:32 30/12/2018
When I add a db config to a config/console.php like this:
return [
'id' => 'school-console',
'basePath' => dirname(__DIR__),
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=school',
'username' => 'root',
'password' => 'Taras1love',
'charset' => 'utf8',
]
];
I get this:
Error: Setting read-only property: yii\console\Application::db
You are missing the database component configurations for the console application you need to add the following inside the config/console.php file. As you are usign the basic-app for Yii2 you must have a db.php file with the database configurations, you need to include it like below
//this goes on the top of your `console.php` file
$db = require __DIR__ . '/db.php',
return [
'id' => 'myapp-console',
'basePath' => dirname(__DIR__)
//add the db component
'components' => [
'db' => $db,
]
];
Your db.php should be like below inside the config folder, change the values for the username, password and dbname.
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=YOUR_DB_NAME',
'username' => 'DB_USER',
'password' => 'DB_PASS',
'charset' => 'utf8',
];
or you can assign it inside the config/console.php if you dont want to create a separate file
return [
'id' => 'myapp-console',
'basePath' => dirname(__DIR__)
//add the db component
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=YOUR_DB_NAME',
'username' => 'DB_USER',
'password' => 'DB_PASS',
'charset' => 'utf8',
]
]
];
I found that I got this problem if I ran yii directly from vendor/bin.
If I went to the console directory and ran it from there using ./yii, I did not get this error and was able to create the migration.
In other words:
cd <project-root>/vendor/bin
yii migrate/create xxx
did not work
But:
cd <project-root>/console
./yii migrate/create xxx
did work
this happened to me because I accidentally renamed my migration and it was not matching the file name
I am trying to use the yii2-queue
https://github.com/yiisoft/yii2-queue/blob/master/docs/guide/usage.md
It says:
In order to use the extension you have to configure it like the
following:
return [
'bootstrap' => [
'queue', // The component registers its own console commands
],
'components' => [
'queue' => [
'class' => \yii\queue\<driver>\Queue::class,
'as log' => \yii\queue\LogBehavior::class,
// Other driver options
],
],
];
My question is simple: In which PHP file, in which directory, should I put this code?
Note: I am using the Basic template.
For Yii2 Basic Template config/console.php
For Yii2 Advanced Template console/config/main.php
return [
'bootstrap' => [
'log',
'queue',
],
'components' => [
'queue' => [
'class' => \yii\queue\db\Queue::class,
'db' => 'db', // DB connection component or its config
'tableName' => '{{%queue}}', // Table name
'channel' => 'default', // Queue channel key
'mutex' => \yii\mutex\MysqlMutex::class, // Mutex that used to sync queries
'as log' => \yii\queue\LogBehavior::class,
// 'deleteReleased' => YII_ENV_PROD,
],
]
];
Refer Yii2 Queue extension guide
Add to the main.php file in backend or frond end you are using like this
'bootstrap' => ['log', 'queue'],
Add this to under component array
'queue' => [
'class' => Queue::class,
'db' => 'db', // DB connection component or its config
'tableName' => '{{%db_queue}}', // Table name
'channel' => 'default', // Queue channel key
'mutex' => MysqlMutex::class, // Mutex used to sync queries
]
To make it workfull you need to do same in console /config/main.php
file and run the command listen form documentaiton
It is very simple to configure it on yii2 basic, add the following configuration on config/web.php file, and for yii2 advanced if you are using frontend then add in frontend/config/main.php, if you are using backend then add to to backend/config.main.php.
Just like this
'components' => [
'request' => [
'cookieValidationKey' => 'htXdOInCiP6ut4gNbDO2',
'csrfParam' => '_frontendCSRF',
],
'queue' => [
'class' => \yii\queue\<driver>\Queue::class,
'as log' => \yii\queue\LogBehavior::class,
// Other driver options
],
]
My Yii 2 application was progressing well until I received an unusual error bout a bad HTTP request.
HTTP 400 Unable to verify your data Submission.
I have looked it up and much of the literature indicates the cause being due to a CSRF issue. However, the CSRF components are all in place within the HTML head section and the hidden field is submitting the correct token.
Additional Info
Yii version = 2.0.12 App Basic
PHP version = 5.6
OS = Ubuntu
I have disabled all the security firmware of the host but I still get the error. Please help the site is in Prod already and I can not find how to solve this many thanks in advance.
web/config/main.php
$config = [
'components' => [
'session' => ['class' => 'yii\web\DbSession'],
'request' => [
'cookieValidationKey' => 'AAOSL2no3kbkJwRA4CNwDuB5g5T5_58t',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => ['errorAction' => 'site/error'],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
//'allowedIPs' => ['127.0.0.1', '::1'],
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
//'allowedIPs' => ['127.0.0.1', '::1'],
];
}
return $config;
As per Change Logs, BugFix and Enhancement related to CSRF cookie.
2.0.13 November 03, 2017 updates include
Bug #14542: Ensured only ASCII characters are in CSRF cookie value since binary data causes issues with ModSecurity and some browsers (samdark)
Enh #14087: Added yii\web\View::registerCsrfMetaTags() method that registers CSRF tags dynamically ensuring that caching doesn't interfere (RobinKamps).
2.0.14 February 18, 2018 updates include
Bug #15317: Regenerate CSRF token if an empty value is given
Enh #15496: (CVE-2018-6009): CSRF token is now regenerated on changing identity (samdark, rhertogh)(sammousa)
So update your framework to the latest version 2.0.14 use composer update via terminal inside your project root, once updated make sure you have the
<?= Html::csrfMetaTags () ?>
inside the <head> tag of the layout file you are using either main.php or any other custom name.
If still persist you can disable it for the specific action inside the beforeAction
public function beforeAction($action)
{
if ($action->id == 'action-name') {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
or for a specific controller by adding
public $enableCsrfValidation = false;
Add <?= Html::csrfMetaTags() ?> in your view, or add in layout(main.php)
I have been fighting with this problem for hours and cannot get through. I want to run API tests with Yii2 and (of course) Codeception. Here is my api.suite.yml
class_name: ApiTester
modules:
enabled:
- REST:
url: /mobile
depends: Yii2
part: Json
- \Helper\Api
config:
Yii2:
entryUrl: http://localhost:8080/index-test.php
and my test file UserLoginCept.php
<?php
$I = new ApiTester($scenario);
$I->wantTo('Test User Login');
$I->sendPOST('mobile/login', ['username' => 'uname', 'password' => '123456']);
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
$I->seeResponseContainsJson(['success'=>true]);
Results are logged below. The problem is the Test is calling site/index which is in the root project not mobile module. I can sense that it is picking wrong URL somewhere as I cannot see any trace of the module being called. If I try URL on Browser it works fine
http://localhost:8080/index.php/mobile/api/login
{
"success": false,
"token": ""
}
can someone help me spot what am doing wrong? I have read as much as I could could not find the issue.
Codeception Results
$~ codecept --debug run api
Codeception PHP Testing Framework v2.2.10
Powered by PHPUnit 4.8.35 by Sebastian Bergmann and contributors.
Rebuilding ApiTester...
Api Tests (1) -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
Modules: REST, Yii2, \Helper\Api
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
UserLoginCept: Test User Login
Signature: UserLoginCept
Test: tests/api/UserLoginCept.php
Scenario --
I send post "/mobile/api/login",{"username":"uname","password":"123456"}
[Request] POST /mobile/mobile/api/login {"username":"uname","password":"123456"}
[Request Headers] []
[yii\db\Connection::open] 'Opening DB connection: mysql:host=localhost;dbname=database_name'
ERROR
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1) UserLoginCept: Test user login
Test tests/api/UserLoginCept.php
[Error] Call to a member function isAdmin() on null
Scenario Steps:
1. $I->sendPOST("/mobile/api/login",{"username":"uname","password":"123456"}) at tests/api/UserLoginCept.php:4
#1 /Users/hosanna/Projects/Volcano/WebApp/vendor/yiisoft/yii2/base/View.php:328
#2 /Users/hosanna/Projects/Volcano/WebApp/vendor/yiisoft/yii2/base/View.php:250
#3 /Users/hosanna/Projects/Volcano/WebApp/vendor/yiisoft/yii2/base/Controller.php:396
#4 /Users/hosanna/Projects/Volcano/WebApp/vendor/yiisoft/yii2/base/Controller.php:382
#5 /Users/hosanna/Projects/Volcano/WebApp/controllers/SiteController.php:74
#6 app\controllers\SiteController->actionIndex
#7 /Users/hosanna/Projects/Volcano/WebApp/vendor/yiisoft/yii2/base/InlineAction.php:57
#8 /Users/hosanna/Projects/Volcano/WebApp/vendor/yiisoft/yii2/base/Controller.php:156
#9 /Users/hosanna/Projects/Volcano/WebApp/vendor/yiisoft/yii2/base/Module.php:523
#10 /Users/hosanna/Projects/Volcano/WebApp/vendor/yiisoft/yii2/web/Application.php:102
<!DOCTYPE html>
<html lang="en-US">
..... rest of HTML.....
So here is how I solved it:
changed suite.api.yaml to use test-index.php
class_name: ApiTester
modules:
enabled:
- Yii2
- REST:
url: http://localhost:8080/index-test.php/mobile/
depends: Yii2
part: Json
configFile: 'config/test.php'
- \Helper\Api
config:
Yii2:
I then changed the config file referred by text-index (config/test.php) to include pretty URLs:
<?php
$params = require(__DIR__ . '/params.php');
$dbParams = require(__DIR__ . '/test_db.php');
/**
* Application configuration shared by all test types
*/
return [
'id' => 'basic-tests',
'basePath' => dirname(__DIR__),
'language' => 'en-US',
'modules' => [
'mobile' => [
'class' => 'app\modules\mobile\Module',
],
],
'components' => [
'db' => $dbParams,
'mailer' => [
'useFileTransport' => true,
],
'assetManager' => [
'basePath' => __DIR__ . '/../web/assets',
],
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'showScriptName' => true,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'mobile/api'],
],
],
'user' => [
'identityClass' => 'app\modules\mobile\models\User',
],
'request' => [
'cookieValidationKey' => 'test',
'enableCsrfValidation' => false,
// but if you absolutely need it set cookie domain to localhost
/*
'csrfCookie' => [
'domain' => 'localhost',
],
*/
],
],
'params' => $params,
];
After that tests were running fine!