PHP Memcached CAS (check and set) issue - php

Hey all, here are the version of my current setup
Memcached (1.2.2)
Pecl Memcached Client 1.0.2 (using libmemcached 0.43)
Issue: I cant get a cas token returned during a get request
Here is the code in question!
27 public function action_test() {
28 //phpinfo();
29 $m = Model_Mem::getSingleton();
30 $found = $m->get('navigation');
31 echo (int)count($found).'<br />'; // Returns an array of navigation objects
32
33 $cas = 0;
34 $found = $m->get('navigation', null, &$cas);
35 echo (int)count($found); // Returns nothing!
36
37 exit;
38 }
The output from the first echo is 7, and the second echo is 1. Also, the $cas variable as well as the $found variable from the second group of code are both empty. Im not 100% sure if I am doing this right but the cas token just doesnt seem to be working for me at all. Ive went through the php Memcached documentation with no mention on any kind of CAS enable flag that i could easily spot. Ive also tried to look at the memcached.org site for some info but im lost!
Ive never had any problems with it, its just everytime i try and use the cas functionality on a get request i do something wrong. Thanks for anyone helping me out!
*EDIT
Here is what the Model_Mem::getSingleton() function returns
static function getSingleton() {
if (self::$m)
return self::$m;
self::$m = new Memcached();
$servers = array(
array('127.0.0.1', 11211, 25),
array('127.0.0.1', 11212, 25),
array('127.0.0.1', 11213, 25),
array('127.0.0.1', 11214, 25)
);
// Sets up some options for the memcache server
self::$m->setOption(Memcached::OPT_DISTRIBUTION,Memcached::DISTRIBUTION_CONSISTENT);
self::$m->setOption(Memcached::OPT_PREFIX_KEY, Kohana::config('globals.prefix'));
self::$m->addServers($servers);
return self::$m;
}

Arg, debian's latest [secure] memcached release didn't have this feature yet. Upgraded to the latest by installing the memcached server's source and all is well.

Just FYI, CAS means "compare-and-swap": https://en.wikipedia.org/wiki/Compare-and-swap

Related

can't login into my codeigniter app after long time of usage

it's been a while since i've purchased freelancer office on codecanyon. i'm using it since 2015. I've never had an issue till last week. If I type in a wrong password it gives me an error (which is normal :D) however when i type the correct one it just reloads the page :/ i've set the ENVIRONMENT to production but no error messages.. except for deprecated each() call in mx/modules.php file.
Codeigniter version: v3.1.0
php version : 7.1
app url:
http://app.wolftech.eu
i've the same error with another 'app' that ive bought on codecanyon for a friend of mine. after 1 year of succesfull usage it just reloads the page when attempting to login.
Based on the error output that you've provided, I assume that the error comes from codeigniter modular extension hmvc, that show up because it uses each() function that is deprecated.
If you look at one of the official repository pull request, and from this codeigniter forum thread, you could change the third_party/MX/Modules.php files line 83 :
(is_array($module)) ? list($module, $params) = each($module) : $params = NULL;
and replace it to :
if(!is_array($module))
{
$params = NULL;
}
else
{
$keys = array_keys($module);
$params = $module[$keys[0]];
$module = $keys[0];
}

Memcached - Why data is not stored?

I'm actually trying to understand why memcached is not storing data for a give Id.
I'm using Magento EE 1.11.2.0 that is based on Zend Framework 1.11.1.
The interface used to deal with memcached is Zend_Cache_Backend_Memcached
Now there is not such big custom code here, this is my custom container that save the cache:
public function saveCache($blockContent)
{
$lifeTime = 86400 * 30 * 6;
$tags = array(
My_Module_Model_PageCache_Container_Category_Blabla::CACHE_TAG
);
$cacheId = $this->_getCacheId();
if ($cacheId !== false) {
$this->_saveCache($blockContent, $cacheId, $tags, $lifeTime);
}
return $this;
}
I'm just forcing magento to use my custom cache tag and a fixed lifetime ( memcache doens't support custom tag so I guess this is not the problem ) also my lifetime is not used in memcached because I can see that the default one is used.
At the beginning I thought the issue was caused by a to long cache ID but now after reducing it ( <31 char ) this didn't help me:
I can see that the load() method Zend_Cache_Backend_Memcached return always false for my cache ids.
While the save() method return true like if it was cached.
This is my local.xml configuration:
<cache>
<slow_backend_store_data>1</slow_backend_store_data>
<auto_refresh_fast_cache>0</auto_refresh_fast_cache>
<backend>memcached</backend>
<slow_backend>database</slow_backend>
<memcached>
<servers>
<!--<server>-->
<!--<host><![CDATA[127.0.0.1]]></host>-->
<!--<port><![CDATA[11213]]></port>-->
<!--<persistent><![CDATA[1]]></persistent>-->
<!--</server>-->
<server>
<host><![CDATA[unix:///tmp/memcached.sock]]></host>
<port><![CDATA[0]]></port>
<persistent><![CDATA[0]]></persistent>
<weight><![CDATA[2]]></weight>
<timeout><![CDATA[5]]></timeout>
</server>
</servers>
<compression><![CDATA[0]]></compression>
<hashed_directory_level><![CDATA[]]></hashed_directory_level>
<hashed_directory_umask><![CDATA[]]></hashed_directory_umask>
<file_name_prefix><![CDATA[]]></file_name_prefix>
</memcached>
</cache>
<full_page_cache>
<backend>memcached</backend>
<slow_backend>database</slow_backend>
<slow_backend_store_data><![CDATA[1]]></slow_backend_store_data>
<memcached>
<servers>
<server>
<host><![CDATA[unix:///tmp/memcached.sock]]></host>
<port><![CDATA[0]]></port>
<persistent><![CDATA[0]]></persistent>
<weight><![CDATA[2]]></weight>
<timeout><![CDATA[10]]></timeout>
<retry_interval><![CDATA[10]]></retry_interval>
<status><![CDATA[1]]></status>
<stats_update_factor><![CDATA[1]]></stats_update_factor>
</server>
</servers>
</memcached>
</full_page_cache>
I also tried to check the entry of memcached to see if my id was stored or not with this command:
echo 'stats cachedump 35 35' | sudo nc -U /tmp/memcached.sock
Any idea about the reason of this ?
How can I debug it ? ( I cannot go under Zend_Cache_Backend_Memcached with xdebug)
You can restart memcached with -vv and look at the interactions.
BTW, the default port for memcache is 11211. FYI
here the issue is $lifetime and a relative bug in Zend_Cache_Backend_Memcached.
Memcached has a max lifetime of 30 days (2592000) so the limit I was using it was too big and that is why the data was not stored.
Sadly:
Zend_Cache_Backend_Memcached::save()
doesn't check if the limit is correct < 2592000
the set() method on the memcached object return true even if it doesn't store the data
$result = #$this->_memcache->set($id, array($data, time(), $lifetime), $flag, $lifetime);

Session variable loses index after refresh in Yii

I'm having a problem with the session variables in my web app.
The thing is that I set it with the following code and check if it exists and only if not then I update it.
The idea is to know if the user is enterprise or not for his session.
I use the following code:
$logo_class = "logo";
if(!Yii::app()->user->isGuest) {
define("ENT_LIM_PROD_COUNT", 10000);
$user_id = Stores::model()->findByPk(Products::model()->getStoreID())->user_id;
if(array_key_exists('is_enterprise', Yii::app()->session)) {
if(Yii::app()->session['is_enterprise'] === true)
$logo_class = "logo_ent";
} else {
$total_prod = LicenseMngr::getFeatureAllocTotal($user_id, LicenseMngr::FEATURE_PRODUCTS);
Yii::app()->session['is_enterprise'] = ($total_prod > ENT_LIM_PROD_COUNT ? true : false);
if(Yii::app()->session['is_enterprise'] === true)
$logo_class = "logo_ent";
}
}
I have tried using different types of sessions in my config file and now it's:
'session'=>array(
'autoStart' => true,
'sessionName' => 'session',
'timeout' => 30758400
),
Now, the problem is that every time I refresh the page the index "is_enterprise" is not in the session array as if it was never set.
I have tried changing the session save directory to /var/tmp.
I'm running:
Darwin niflheim 12.3.0 Darwin Kernel Version 12.3.0: Sun Jan 6 22:37:10 PST 2013; root:xnu-2050.22.13~1/RELEASE_X86_64 x86_64
PHP Version 5.4.15 (web)
The following line does a rest call to a server to get information we need (It's probably the only thing that isn't related to YII here):
$total_prod = LicenseMngr::getFeatureAllocTotal($user_id, LicenseMngr::FEATURE_PRODUCTS);
P.S: This is not the only custom variable that it happens with, I hope that helps.
OK So after a while we were able to solve the problem... Apparently the session variable in YII is not an array but an object and you can access it as an array so array_key_exists didn't work.
Changing it to isset solved the problem.

PHP 5.2.13 MongoCursorException 'duplicate key error index'

I'm getting duplicate _ids when inserting documents into our mongo database. This is an intermittent problem that only happens under some load (is reproducable with some test scripts).
Here's some test code so you don't think I'm trying to double-insert the same object (I know that the PHP mongo driver adds the _id field):
// Insert a job
$job = array(
'type' => 'cleanup',
'meta' => 'cleaning the data',
'user_id' => new MongoId($user_id),
'created' => time(),
'status' => 'pending'
);
$this->db->job->insert($job, array('safe' => true)); // <-- failz here
I went on a frenzy and installed the latest stable (1.1.4) mongo driver to no avail. This isn't under heavy load. We're doing maybe 5 req/s on one server, so the 16M rec/s limit for the inc value probably isn't the issue.
Any ideas would be greatly appreciated. I'm hoping someone somewhere has used mongo with PHP and inserted more than 5 docs/s and had this issue ;).
-EDIT-
On CentOS 5.4 x86_64, linux 2.6.18-164.el5xen, Apache worker 2.2.15, PHP 5.2.13, MongoDB 1.8.1
-EDIT2-
As noted in the comments, I'm using the latest version of the PECL driver as of now (1.2.0) and the problem is still happening.
-EDIT3-
Forgot to post exact error:
Uncaught exception 'MongoCursorException' with message 'E11000 duplicate key error index: hannibal.job.$_id_ dup key
There is a different solution for this (the preform/worker MPM didn't help in my case, we were running as prefork which is default anyway).
The issue is that the insert array is passed by reference, and modified by the PHP MongoDB library to include the ID. You need to clear the ID.
So imagine the following code:
$aToInsert = array('field'=>$val1);
$collection->insert($aToInsert); << This will have '_id' added
$aToInsert['field'] = $val2
$collection->insert($aToInsert); << This will fail with the above error
Why? What happens with the library is:
$aToInsert = array('field'=>$val1);
$collection->insert($aToInsert);
// $aToInsert has '_id' added by PHP MongoDB library
// Therefore $aToInsert = array('field'=>$val1, '_id'=>MongoID() );
$aToInsert['field'] = $val2
// Therefore $aToInsert = array('field'=>$val2, '_id'=>MongoID() );
$collection->insert($aToInsert);
// This will not add '_id' as it already exists. But will now fail.
Solution is to reinitialise the array
$aToInsert = array('field'=>$val1);
$collection->insert($aToInsert);
$aToInsert = array('field'=>$val2);
$collection->insert($aToInsert);
or to unset the id
$aToInsert = array('field'=>$val1);
$collection->insert($aToInsert);
unset($aToInsert['_id']);
$aToInsert['field'] = $val2
$collection->insert($aToInsert); << This will now work
Looks like it had to do with the Apache version installed (worker). After installing apache prefork, we've seen no more duplicate _id errors on the server.
My guess is this has something to do with the global counter the Mongo driver uses. I'm thinking the lack of communication between the threads may be the cause...maybe one pool has instance counters per-thread, but since the PID is the same, you get conflicts.
I don't know the internals, but this seems to be the most likely explanation. Don't use Apache Worker MPM with the PHP MongoDB driver. Please comment and correct me if this is not the case, or if you know of a fix.

PHP AMI Connection - saving incoming and outgoing calls to a database is not working

Using the AMI (API connection with an Asteriskserver so I can use a PHP Socket connection) I'm trying to catch the recieving data using PHP in a way that I can record outgoing and incomming calls for the CRM system (webbased) used at the company I work for.
But I'm not getting the result I am hoping for...
The full code can be found on PasteBin http://pastebin.com/AwRNBW2G
I catch the outgoing calls this way, and that works:
if($givenkey = array_search("Context: from-internal", $content)){
$calleridKey = $givenkey + 1;
$idSIP = $givenkey - 1;
$dialNumber = str_replace("Extension: 0","31",$content[$calleridKey]);
$dialNumber = str_replace("Extension: ", "", $dialNumber);
$fromSIP = str_replace("Channel: SIP/", "", $content[$idSIP]);
$fromSIP = substr($fromSIP, 0, 2);
$dialTime = date('r');
$uitgaand = array(
"Phonenumber" => $dialNumber,
"Type" => "Uitgaand",
"datetime" => $dialTime,
"SIP" => $fromSIP
);
The incomming calls are being catched this way, but that's not working properly:
if($givenkey = array_search("AppData: Using CallerID ", $content)){
if(array_search("Channel: SIP/31000000000", $content)+5 == $InCallKey = array_search("AppData: Using CallerID", $content)){
$calleridNum = explode('"',str_replace('AppData: Using CallerID "',"",$content[$InCallKey]));
$pickupSource = array_search("Source: SIP/31000000000", $content);
if($pickupSource+1 == $pickupKey = array_search("Destination: SIP/", $content)){
$pickupBy = str_replace("Destination: SIP/","",$content[$pickupkey]);
$pickupBy = substr($pickupBy, 0, 2);
$dialTime = date('r');
$inkomend = array(
"Phonenumber" => $calleridNum[0],
"Type" => "Binnenkomend",
"datetime" => $dialTime,
"SIP" => $pickupBy
);
I have the array that I make not available right now but, if necessary, I can save the array and post it here with personal data filtered.
I know that the code I'm using right now is not neat, but I wrote it with the goal: quick result. If I have a working code I will optimize it and clean it up. Tips about this are also very welcome. It's too bad that I cannot find any good documentation about this so I have to start from the beginning and could only find the working class that I'm using right now, however it's not very complete.
I had to write this part without any knowledge about VOIP or AMI or Asterisk.
To be short, here are my questions:
- How can I record incoming and outgoing calls to eventually save them in a database by using the AMI?
- How can I keep alive the connection with the server the best way? The method I'm using now is not optimal as the connection fails atleast once within 48 hours.
- Do you have tips or suggestions about optimizing the code and neater code-writing? And do you maybe know any functions that I could use instead of a function that I am using?
With regards,
Dempsey
Since recently I get this error which
I cannot solve properly. This error
creates itself after about 15 minutes
running. It would run atleast 24 hours
before:
PHP Notice: fwrite(): send of 16 bytes failed with errno=32 Broken pipe in /var/www/html/phpami/AMILoader.php on line 147
Net_AsteriskManagerException: Authorisation failed in /var/www/html/phpami/AMILoader.php on line 173
#0 /var/www/html/phpami/AMILoader.php(173): Net_AsteriskManager-login('GEBRUIKERSNAAM','WACHTWOORD')
#1 /var/www/html/phpami/AMILoader.php(306): Net_AsteriskManager-_sendCommand('Action: Ping???...')
#2 /var/www/html/phpami/AMILoader.php(543): Net_AsteriskManager->ping()
#3 {main}
Can anyone help me with this too? The
authorisation data is correct (it is
using the same data in the whole
script and it does get a connection).
Also I don't get the response 'Action:
Ping???...' which it says is being
send by the script as command, but
where do the three questionmarks and
periods come from?
this framework should be handy:
https://github.com/marcelog/PAMI
otherwise you can check vTiger sources and how it handles ami integration:
http://www.vtiger.com/index.php?Itemid=57&id=30&option=com_content&task=view
If your using php, one of the easiest way to connect to the AMI is using the php-astmanager class. It supports callback on certain "events" so that you can catch the data you need. The best (only?) maintained copy is part of FreePBX and can be pulled right out of the latest version (2.9 as of this writing).

Categories