getting weird issue with redis on laravel - php

i am trying to make larvel use redis in unix socket mode , but when i run php artisan cache:clear
i get the following error msg, what am i doing wrong here, i followed the .env correctly
Exception
When setting a value in the cache, you must pass an array of key / value pairs.
at vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:246
242| return app('cache')->get(...$arguments);
243| }
244|
245| if (! is_array($arguments[0])) {
> 246| throw new Exception(
247| 'When setting a value in the cache, you must pass an array of key / value pairs.'
248| );
249| }
250|
+28 vendor frames
29 artisan:37
Illuminate\Foundation\Console\Kernel::handle()
i also noticed
RedisException
php_network_getaddresses: getaddrinfo failed: Name or service not known
at vendor/laravel/framework/src/Illuminate/Redis/Connectors/PhpRedisConnector.php:137
133| $parameters[] = $context;
134| }
135| }
136|
> 137| $client->{($persistent ? 'pconnect' : 'connect')}(...$parameters);
138| }
139|
140| /**
141| * Create a new redis cluster instance.
+25 vendor frames
26 artisan:37
Illuminate\Foundation\Console\Kernel::handle()

Related

Laravel spatie Got error: 2004: "Can't create TCP/IP socket (10106)" when trying to connect

I have installed sepatie/backup package on my project and configure to create mysql backup. This work when i run php artisan backup:run. But what i am trying to do is to let user freedom to create backup by clickin on a button. So i have done something like this
Route::get('backup-run', function() {
Artisan::call('backup:run');
return response()->json(['success' => 'Backup for database created']);
});
and a button with vue js method
createDBBackup() {
axios.get('/backup-run')
.then(response => {
on database.php i have add this config i found on documentation
'dump' => [
'dump_binary_path' => 'C:\xampp\mysql\bin', // only the path, so without `mysqldump` or `pg_dump`
'use_single_transaction',
'timeout' => 60 * 5, // 5 minute timeout
],
as response i get some error like this on clockwork
Spatie\Backup\Events\BackupHasFailed exception: Spatie\DbDumper\Exceptions\DumpFailedbackupDestination: null
exception: Spatie\DbDumper\Exceptions\DumpFailed
*message: "The dump process failed with exitcode 2 : Misuse of shell builtins : mysqldump: Got error: 2004: "Can't create TCP/IP socket (10106)" when trying to connect
"
~string: ""
*code: 0
*file: "C:\...\vendor\spatie\db-dumper\src\Exceptions\DumpFailed.php"
*line: 17
~trace: Array(79)
~previous: null
backupDestination: null

Laravel ACL Errors in Console Call to undefined method Illuminate\Foundation\Application::where()

I'm currently new to Laravel and trying to learn it. I worked now many hours with it and tried to install and use now the Laravel ACL from https://github.com/mateusjunges/laravel-acl
But I keep getting errors with it.
My Steps:
Installed
tried php artisan migrate -> not worked -> Nothing to migrate.
tried it manually -> copying the migration files from vendor>mateusjunges>laravel-acl>database>migrations> into ..database>migrations
Again php artisan migrate -> worked
tried php artisan permission:create testperm testperm "test"-> error
Error:
Call to undefined method Illuminate\Foundation\Application::where()
at testproject\vendor\mateusjunges\laravel-acl\src\Console\Commands\CreatePermission.php:43
39▕ public function handle()
40▕ {
41▕ $permissionModel = app(config('acl.models.permission'));
42▕
➜ 43▕ $permission = $permissionModel->where('slug', $this->argument('slug'))
44▕ ->orWhere('name', $this->argument('name'))
45▕ ->first();
46▕
47▕ if (! is_null($permission)) {
1 testproject\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:36
Junges\ACL\Console\Commands\CreatePermission::handle()
2 testproject\vendor\laravel\framework\src\Illuminate\Container\Util.php:40
Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
tried php artisan user:permissions 1 -> next error
Error:
Call to undefined method Illuminate\Foundation\Application::find()
at testproject\vendor\mateusjunges\laravel-acl\src\Console\Commands\UserPermissions.php:44
40▕ $userParameter = $this->argument('user');
41▕ $userModel = app(config('acl.models.user'));
42▕
43▕ if (is_numeric($userParameter)) {
➜ 44▕ $user = $userModel->find((int) $userParameter);
45▕ } elseif (is_string($userParameter)) {
46▕ $table = config('acl.tables.users');
47▕ $columns = $this->verifyColumns($table);
48▕
1 testproject\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:36
Junges\ACL\Console\Commands\UserPermissions::handle()
2 testproject\vendor\laravel\framework\src\Illuminate\Container\Util.php:40
Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
I dont know what I did wrong, the installation was successful...
You have to see the documentation of the package, it is going always to be hard if you try by your own...
This is the documentation, and it clearly says: To install run php artisan acl:install, and then you have one more that will add all the needed files you are missing (that's why the error) php artisan vendor:publish --provider="Junges\ACL\Providers\ACLServiceProvider" --tag="acl-migrations"...
Read the documentation please...

Doctrine Exception: Deadlock found when trying to get lock

I have a Symfony app which exposes a collection of JSON web services used by a mobile app.
On the last few days we are having many concurrent users using the app (~5000 accesses per day) and a Doctrine error started to "randomly" appear in my logs. It appears about 2-3 times per day and this is the error:
Uncaught PHP Exception Doctrine\DBAL\Exception\DriverException: "An exception occurred while executing 'UPDATE fos_user_user SET current_crystals = ?, max_crystals = ?, updated_at = ? WHERE id = ?' with params [31, 34, "2017-12-19 09:31:18", 807]:
SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction" at /var/www/html/rollinz_cms/releases/98/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php line 115
It seems it cannot get the lock while updating the users table. The controller code is the following:
/**
* #Rest\Post("/api/badges/{id}/achieve", name="api_achieve_badge")
*/
public function achieveAction(Badge $badge = null)
{
if (!$badge) {
throw new NotFoundHttpException('Badge not found.');
}
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
$userBadge = $em->getRepository('AppBundle:UserBadge')->findBy(array(
'user' => $user,
'badge' => $badge,
));
if ($userBadge) {
throw new BadRequestHttpException('Badge already achieved.');
}
$userBadge = new UserBadge();
$userBadge
->setUser($user)
->setBadge($badge)
->setAchievedAt(new \DateTime())
;
$em->persist($userBadge);
// sets the rewards
$user->addCrystals($badge->getCrystals());
$em->flush();
return new ApiResponse(ApiResponse::STATUS_SUCCESS, array(
'current_crystals' => $user->getCurrentCrystals(),
'max_crystals' => $user->getMaxCrystals(),
));
}
I looked into MySQL and Doctrine documentation but I couldn't find a reliable solution. Doctrine suggests retrying the transaction but it doesn't show an actual example:
https://dev.mysql.com/doc/refman/5.7/en/innodb-deadlock-example.html
try {
// process stuff
} catch (\Doctrine\DBAL\Exception\RetryableException $e) {
// retry the processing
}
This posts suggests retrying the transaction. How can I do it?
Could it be a server problem (too many accesses) and I must boost the server or the code is wrong and I must explicitly handle the deadlock in my code?
This is a MySQL issue. Multiple simultaneous transactions blocking the same resources.
Check if you have cronjobs that may block the records for long times.
Otherwise is just concurrent requests updating the same data, you may have better knowledge where this data gets updated.
Dirty attempt for a retry in php:
$retry=0;
while (true) {
try {
// some more code
$em->flush();
return new ApiResponse(ApiResponse::STATUS_SUCCESS, array(
'current_crystals' => $user->getCurrentCrystals(),
'max_crystals' => $user->getMaxCrystals(),
));
} catch (DriverException $e) {
$retry++;
if($retry>3) { throw $e; }
sleep(1); //optional
}
}
Albert's solution is the right one but you also must recreate a new EntityManager in the catch clause using resetManager() of your ManagerRegistry. You'll get exceptions if you continue to use the old EntityManager and its behavior will be unpredictable. Beware of the references to the old EntityManager too.
This issue will be hopefully corrected in Doctrine 3: See issue
Until then, here is my suggestion to handle the problem nicely: Custom EntityManager

Rollback in laravel has no effect

I am creating a backup system but I got an issue with the import step. Impossible to rollback if there is any error.
I'm using this code on the CLI mode (via artisan myowncommand)
I have a file, with all my instructions:
<?php
// #generated 2016-12-11 01:05:25
use Illuminate\Support\Facades\DB;
use App\Category;
// ...
DB::beginTransaction();
Category::truncate();
// ...
// LOAD MODEL `Category` (CLASS `App\Category`)
Category::unguard();
Category::create(array (
'id' => 1,
'name' => 'Holidays',
'descr' => 'Holidays & sick & off',
'color' => 'default',
'created_at' => '2016-12-11 01:05:21',
'updated_at' => '2016-12-11 01:05:21',
));
// ...
Category::reguard();
// ...
DB::rollback();
?>
If I execute this code, it's like if no rollback happened :( If I clean my table and execute the script ... data are inserted.
According the laravel documentation, rollback instruction should be compatible:
Using the DB facade's transaction methods also controls transactions
for the query builder and Eloquent ORM (https://laravel.com/docs/5.3/database).
I also tried to use the DB::transaction() (with manual error (changed id by ida) to trigger rollback). No difference.
Do you have any explanation ? Or any way to execute correctly the rollback instruction ?
Thanks :)
Solutions I tested
Test 1
try {
DB::beginTransaction();
include $file;
/*** File is:
* use Illuminate\Support\Facades\DB;
* use App\Category;
*
* Category::truncate();
* Category::unguard();
* Category::create(array ('id' => 1, 'name' => 'Holidays'));
* // create error by changing 'id' by 'ida'
* Category::reguard();
***/
DB::commit();
echo sprintf('> Load Backup file `%s` COMPLETED', $file);
}
catch( \Exception $e ) {
DB::rollback();
echo sprintf('> Load file `%s` failled - ROLLBACK', $file);
throw $e;
}
Test 2
DB::transaction(function() {
include $file;
/*** File is:
* use Illuminate\Support\Facades\DB;
* use App\Category;
*
* Category::truncate();
* Category::unguard();
* Category::create(array ('id' => 1, 'name' => 'Holidays'));
* // create error by changing 'id' by 'ida'
* Category::reguard();
***/
});
Test 3 & 4
Same as test 1, include $file and all DB::transaction, DB::beginTransaction & DB::commit & DB:rollback directly in this $file file
Test 5
I tried to:
move the DB::beginTransaction outside the try/catch
move the DB::commit outside the try/catch
Test case
php artian migrate:refresh --seed Clear tables & populate with some masterdata
On phpmyadmin, clean (truncable) table (here: category).
There is no result on the table
Execute the code. "Load Backup failled - ROLLBACK" is executed
On phpmyadmin, check data: there are records. Model:truncable from my code executed, but not rollback
I think it should be
DB::beginTransaction();
try
{
//code for processing multiple related transactions
include $file;
}
catch(\Exception $e)
{
DB::rollBack();
//echo error message
}
DB::commit();
//echo success message
DB::beginransaction and DB::commit should be outside the try-catch block. It works for me.
And your $file should have only the instructions which you want within the try block - no DB::beginTransaction(), DB::commit() or DB::rollBack() statements.
UPDATE
The general logical steps to follow would be
Begin transaction - DB::beginTransaction()
Run database queries - crud operations - try{//run queries}
If there's an error/exception - Rollback the transaction - catch(Exception $e){ DB::rollBack()
Send/display the error/exception message - //display/send error/exception message }
If the queries run smoothly - Commit the transaction - DB::commit()
Hope this helps.
I was with the same problem, I start reading the documentation carefully and it was mysql version, must be 5.7+.
some reason a rollback often requires you to run composer dump-autoload. if your migration work.

Symfony + Doctrine Oracle DateTime format issue

I have a problem with Oracle DateTime type in Symfony 2.7 + Doctrine.
I have a table with a DateTime column which is mapped in Symfony through Doctrine.
When I try to persiste the relative Entity I got the following error:
Could not convert database value "31-MAY-16 03.56.49.000000 PM" to Doctrine Type datetime. Expected format: Y-m-d H:i:s File: .../vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/ConversionException.php Line: 63
I cannot change the default format in the Oracle Database.
I previously fixed the problem by modifing the method getDateTimeFormatString() in the vendor/doctrine/dbal/lib/Doctrine/DBAL/Platforms/OraclePlatform.php and it worked.
However, since I have to use Git and "composer install ..." in order to deploy my application in production environment, all vendors are installed from the Symfony repository; in that way I lose the changes I made in OraclePlatform.php
To solve the problem without touching the verdors libraries, i tried to set the following Oracle ENV variables on httpd init start script but it doesn't work
export NLS_TIME_FORMAT="HH24:MI:SS"
export NLS_DATE_FORMAT="YYYY-MM-DD HH24:MI:SS"
export NLS_TIMESTAMP_FORMAT="YYYY-MM-DD HH24:MI:SS"
export NLS_TIMESTAMP_TZ_FORMAT="YYYY-MM-DD HH24:MI:SS TZH:TZM"
I found a possible solution in the Known Vendor Issues in the Doctrine documentation about PostgreSQL where they suggest to use the VarDateTimeType by overriding the type like this:
use Doctrine\DBAL\Types\Type;
Type::overrideType('datetime', 'Doctrine\DBAL\Types\VarDateTimeType');
Type::overrideType('datetimetz', 'Doctrine\DBAL\Types\VarDateTimeType');
Type::overrideType('time', 'Doctrine\DBAL\Types\VarDateTimeType');
This seams to be the solution, however I have no idea on how to override the type with the code above but mostly where to put the above code.
Do someone have any idea?
Thanks
P.S. I'm using DateTime without timezone
Create a custom DBAL Type extending the DateTimeType and override the convertToPHPValue function (I copied the VarDateTimeType class, which couldn't successfully convert the Date type my Oracle installation was using):
<?php
namespace YourCompany\SomeBundle\Doctrine\DBAL\Types;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateTimeType;
class SillyDateTimeType extends DateTimeType
{
/**
* {#inheritdoc}
* #throws \Doctrine\DBAL\Types\ConversionException
*/
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if ($value === null || $value instanceof \DateTime) {
return $value;
}
$val = \DateTime::createFromFormat('d-M-y H.i.s.u A', $value);
if ( ! $val instanceof \DateTime) {
throw ConversionException::conversionFailed($value, $this->getName());
}
return $val;
}
}
Replace $val = \DateTime::createFromFormat('d-M-y H.i.s.u A', $value); with whatever format your installation is returning for those columns.
Then just register it under dbal in config.yml:
# app/config/config.yml
doctrine:
dbal:
types:
sillydatetime: YourCompany\SomeBundle\Doctrine\DBAL\Types\SillyDateTimeType
Now you can use sillydatetime (or whatever you call it) anywhere in your column type specifications.
I fixed the problem following the proposal of this comment in Github. In app/config/config.yml (Symfony 2.3.1) I added the following block:
services:
oracle.listener:
class: Doctrine\DBAL\Event\Listeners\OracleSessionInit
tags:
- { name: doctrine.event_listener, event: postConnect }
I don't know about Symfony/Doctrine, but this is simple to fix with the regular OCI functions:
$conn = oci_connect('username', 'password', 'connection_string');
// get the sysdate...
$select = oci_parse($conn, 'select sysdate from dual');
oci_execute($select);
print_r(oci_fetch_row($select));
// alter the session date format...
$alter = oci_parse($conn, 'alter session set NLS_DATE_FORMAT=\'YYYY-MM-DD HH24:MI:SS\'');
oci_execute($alter);
// get the sysdate again...
oci_execute($select);
print_r(oci_fetch_row($select));
This gives the output:
Array
(
[0] => 10-JUN-16
)
Array
(
[0] => 2016-06-10 13:39:34
)

Categories