How can I access AWS CloudWatch Custom Metrics via PHP SDK - php

I'm able to retrieve metrics information for included metrics however for custom metrics, for example CPUUtilization on a per/instance basis, I cannot get the info. I'm not sure if I'm using the correct NameSpace, or perhaps I need to include additional information in the Dimensions field. Anyone know how to do this?
Here is my code:
<?php
date_default_timezone_set('America/New_York');
require 'vendor/autoload.php';
use Aws\CloudWatch\CloudWatchClient;
$cloudWatchClient = CloudWatchClient::factory(array(
'profile' => 'my_profile',
'region' => 'us-east-1',
));
$dimensions = array(
array('Name' => 'InstanceId', 'Value' => 'i-0c0f546e4d1ef25e1'),
array('Name' => 'ImageId', 'Value' => 'ami-9cdee48b'),
array('Name' => 'AutoScalingGroupName', 'Value' => 'lc-wordpress-asg'),
);
$cpuResult = $cloudWatchClient->getMetricStatistics(array(
'Namespace' => 'AWS/EC2',
'MetricName' => 'CPUUtilization',
'Dimensions' => $dimensions,
'StartTime' => strtotime('-5 minutes'),
'EndTime' => strtotime('now'),
'Period' => 300,
'Statistics' => array('Average'),
));
var_dump($cpuResult);
$memoryResult = $cloudWatchClient->getMetricStatistics(array(
'Namespace' => 'Linux System',
'MetricName' => 'MemoryUtilization',
'Dimensions' => $dimensions,
'StartTime' => strtotime('-5 hours'),
'EndTime' => strtotime('now'),
'Period' => 60,
'Statistics' => array('Average'),
));
var_dump($memoryResult);
?>
Running this code produces the following output. As you can see CPUUtilization returns the desired results however MemoryUtilization returns an empty array.
[ec2-user#ip-10-0-52-163 php-sdk]$ php get-cloudwatch-metrics.php
object(Guzzle\Service\Resource\Model)#100 (2) {
["structure":protected]=>
NULL
["data":protected]=>
array(3) {
["Datapoints"]=>
array(0) {
}
["Label"]=>
string(14) "CPUUtilization"
["ResponseMetadata"]=>
array(1) {
["RequestId"]=>
string(36) "63dc311e-bdaf-11e6-8143-f96eefa160b8"
}
}
}
object(Guzzle\Service\Resource\Model)#102 (2) {
["structure":protected]=>
NULL
["data":protected]=>
array(3) {
["Datapoints"]=>
array(0) {
}
["Label"]=>
string(17) "MemoryUtilization"
["ResponseMetadata"]=>
array(1) {
["RequestId"]=>
string(36) "63dec890-bdaf-11e6-b04d-0707ed181fab"
}
}
}
Note, I'm using the typical AWS custom metric Perl scripts to send custom metrics to CloudWatch.
* * * * * ~/aws-scripts-mon/mon-put-instance-data.pl --mem-util --mem-used --mem-avail --disk-space-util --disk-path=/ --from-cron --aggregated --auto-scaling

I figured it out. A quick check of my custom metric instance scripts that put metrics to CloudWatch show a namespace of "System/Linux", however in the CloudWatch Console it displays "Linux System". Switching the code to System/Linux produces the expected results!
$dimensions = array(
array('Name' => 'InstanceId', 'Value' => 'i-0c0f546e4d1ef25e1'),
);
$memoryResult = $cloudWatchClient->getMetricStatistics(array(
'Namespace' => 'System/Linux',
'MetricName' => 'MemoryUtilization',
'Dimensions' => $dimensions,
'StartTime' => strtotime('-5 minutes'),
'EndTime' => strtotime('now'),
'Period' => 60,
'Statistics' => array('Average'),
));
var_dump($memoryResult);
Output below:
[ec2-user#ip-10-0-52-163 php-sdk]$ php get-cloudwatch-metrics.php
object(Guzzle\Service\Resource\Model)#100 (2) {
["structure":protected]=>
NULL
["data":protected]=>
array(3) {
["Datapoints"]=>
array(5) {
[0]=>
array(3) {
["Average"]=>
string(16) "50.1385233069785"
["Unit"]=>
string(7) "Percent"
["Timestamp"]=>
string(20) "2016-12-10T23:07:00Z"
}
[1]=>
array(3) {
["Average"]=>
string(16) "38.5987663771093"
["Unit"]=>
string(7) "Percent"
["Timestamp"]=>
string(20) "2016-12-10T23:08:00Z"
}
[2]=>
array(3) {
["Average"]=>
string(16) "41.5588687016341"
["Unit"]=>
string(7) "Percent"
["Timestamp"]=>
string(20) "2016-12-10T23:09:00Z"
}
[3]=>
array(3) {
["Average"]=>
string(16) "45.4270517993215"
["Unit"]=>
string(7) "Percent"
["Timestamp"]=>
string(20) "2016-12-10T23:10:00Z"
}
[4]=>
array(3) {
["Average"]=>
string(16) "46.4784461685095"
["Unit"]=>
string(7) "Percent"
["Timestamp"]=>
string(20) "2016-12-10T23:06:00Z"
}
}
["Label"]=>
string(17) "MemoryUtilization"
["ResponseMetadata"]=>
array(1) {
["RequestId"]=>
string(36) "07c17abc-bf2e-11e6-a0ce-0f6cd308d7b2"
}
}
}

I used to have same problem,
Problem was in dimensions (I should use ClusterName)
$dimensions = array(array('Name' => 'ClusterName', 'Value' => env('AWS_CLUSTER_NAME')));
$metrics = $cloudWatch->GetMetricStatistics(['Namespace' => 'AWS/ECS',
'MetricName' => "MemoryUtilization",
'Period' => 60,
'Dimensions' => $dimensions,
'StartTime' => strtotime('-24 hours'),
'EndTime' => strtotime('now'),
'Statistics' => array('Maximum', 'Minimum', 'Average')]);

Related

need to change number of rows of an array

I have this array in indice.php, included into my page.php, is an array exported from the table "indice" of my db.
<?php
$indice = array(
array('id' => '1','def' => 'Admin'),
array('id' => '2','def' => 'Utente'),
array('id' => '31','def' => 'Aldwich Vertigos'),
array('id' => '32','def' => 'Celtic Newcastle'),
array('id' => '91','def' => 'Serie A'),
array('id' => '92','def' => 'Serie B'),
array('id' => '93','def' => 'Premier League'),
array('id' => '110','def' => 'Argentina'),
array('id' => '431','def' => 'Brisbane Road'),
array('id' => '432','def' => 'Kingstone Park'),
array('id' => '120','def' => 'Belgio') ); ?>
And my array is in this way:
array(416) {
[0]=>
array(2) {
["id"]=>
string(1) "1"
["def"]=>
string(5) "Admin"
}
[1]=>
array(2) {
["id"]=>
string(1) "2"
["def"]=>
string(6) "Utente"
}
[2]=>
array(2) {
["id"]=>
string(2) "31"
["def"]=>
string(16) "Aldwich Vertigos"
...etc...
then i print this:
<?php
include("functions.php");
include("auth.php");
include("db.php");
include("indice.php");
$indiceok = $indice['2']['def'];
echo $indiceok;
?>
'''
Well... My $indiceok stamps 'Aldwych Vertigos', but how could i obtain that $indiceok using the ID (2) stamps "Utente"?
I appreciate too a string which change my array in an array like this, using ID to identify my array selections:
array(416) {
[1]=>
array(2) {
["id"]=>
string(1) "1"
["def"]=>
string(5) "Admin"
}
[2]=>
array(2) {
["id"]=>
string(1) "2"
["def"]=>
string(6) "Utente"
}
**[31]**=>
array(2) {
["id"]=>
string(2) "31"
["def"]=>
string(16) "Aldwich Vertigos"
Many thanks and sorry for my question, i'm sure it's probably very easy to resolve, but i don't know how i can
You are looking for array_column.
By default it isolates a column in a multidimensional array but if you use the third argument you can make an array associative.
$yourarray = array_column($yourarray, Null, "id");
This will only work if id is unique.
If it's not unique, meaning you have two 31, the last subarray will be kept and the first will be truncated.
See result of your array here: https://3v4l.org/CJcJL
Alternatively, of your array is static you can just assign the keys manually in the code:
$indice = array(
"1" => array('id' => '1','def' => 'Admin'),
"2" => array('id' => '2','def' => 'Utente'),
"31" => array('id' => '31','def' => 'Aldwich Vertigos'),
"32" => array('id' => '32','def' => 'Celtic Newcastle'),
"91" => array('id' => '91','def' => 'Serie A'),
"92" => array('id' => '92','def' => 'Serie B'),
"93" => array('id' => '93','def' => 'Premier League'),
"110" => array('id' => '110','def' => 'Argentina'),
"431" => array('id' => '431','def' => 'Brisbane Road'),
"432" => array('id' => '432','def' => 'Kingstone Park'),
"120" => array('id' => '120','def' => 'Belgio') );

Sort Multidimensional Array By Searched Word

I need to sort a multidimensional array by a searched keyword.
My array is like below.
<?php
array(
array(
'name' => '11th-Physics',
'branch' => 'Plus One',
'college' => 'Plus One',
),
array(
'name' => 'JEE-IIT',
'branch' => 'Physics',
'college' => 'IIT College',
),
array(
'name' => 'Physics',
'branch' => 'Bsc Physics',
'college' => 'College of Chemistry',
),
array(
'name' => 'Chemical Engineering',
'branch' => 'Civil',
'college' => 'Physics Training Center',
),
array(
'name' => 'Physics Education',
'branch' => 'Mechanical',
'college' => 'TBR',
),
)
?>
I need to sort this array when search keyword is physics . And after Sorting i need the result like below.
NEEDED RESULT
<?php
array(
array(
'name' => 'Physics',
'branch' => 'Bsc Physics',
'college' => 'College of Chemistry',
),
array(
'name' => 'Physics Education',
'branch' => 'Mechanical',
'college' => 'TBR',
),
array(
'name' => '11th-Physics',
'branch' => 'Plus One',
'college' => 'Plus One',
),
array(
'name' => 'JEE-IIT',
'branch' => 'Physics',
'college' => 'IIT College',
),
array(
'name' => 'Chemical Engineering',
'branch' => 'Civil',
'college' => 'Physics Training Center',
),
)
?>
That is I need to sort the array first by the name which is exactly like the searched keyword. Then wildcard search in name. Then to the next key branch and same as above. Is there any php function to sort this array like my requirement. I have already checked asort, usort. But I didn't get result properly.
Just call this simple function I just created for your requirement, It works just fine :) change the priority order according to your need
function sortArray($array,$itemToSearch)
{
$sortedArray = array();
$priorityOrder = ['name','branch','college'];
foreach ($priorityOrder as $key)
{
foreach ($array as $i => $value)
{
if(strpos(strtolower($value[$key]), strtolower($itemToSearch)) === 0)
{
array_push($sortedArray, $value);
unset($array[$i]);
}
}
foreach ($array as $i => $value)
{
if(strpos(strtolower($value[$key]), strtolower($itemToSearch)) > 0)
{
array_push($sortedArray, $value);
unset($array[$i]);
}
}
}
return $sortedArray;
}
Here we go
So I started from the algorithm in this answer and modified it to fit your requirements. Since you have three different "priorities" to you sorting, we have to use some temporary variables to separate the elements we wish sorted.
// arrays used to separate each row based on the row where the word "Physics" is found
$searchName = array();
$searchBranch = array();
$searchCollege = array();
// arrays used later for array_multisort
$foundInName = array();
$foundInBranch = array();
$foundInCollege = array();
foreach ($var as $key => $row) {
if(strpos(strtolower($row['name']), 'physics') !== false) {
$searchName[$key] = $row['name'];
$foundInName[] = $row;
}
elseif(strpos(strtolower($row['branch']), 'physics') !== false) {
$searchBranch[$key] = $row['branch'];
$foundInBranch[] = $row;
}
elseif(strpos(strtolower($row['college']), 'physics') !== false) {
$searchCollege[$key] = $row['college'];
$foundInCollege[] = $row;
}
}
// Note: I use SORT_NATURAL here so that "11-XXXXX" comes after "2-XXXXX"
array_multisort($searchName, SORT_NATURAL, $foundInName); // sort the three arrays separately
array_multisort($searchBranch, SORT_NATURAL, $foundInBranch);
array_multisort($searchCollege, SORT_NATURAL, $foundInCollege);
$sortedArray = array_merge($foundInName, $foundInBranch, $foundInCollege);
Outputting $sortedArray using var_dump() gives something like:
array(5) {
[0]=> array(3) {
["name"]=> string(12) "11th-Physics"
["branch"]=> string(8) "Plus One"
["college"]=> string(8) "Plus One"
}
[1]=> array(3) {
["name"]=> string(7) "Physics"
["branch"]=> string(11) "Bsc Physics"
["college"]=> string(20) "College of Chemistry"
}
[2]=> array(3) {
["name"]=> string(17) "Physics Education"
["branch"]=> string(10) "Mechanical"
["college"]=> string(3) "TBR"
}
[3]=> array(3) {
["name"]=> string(7) "JEE-IIT"
["branch"]=> string(7) "Physics"
["college"]=> string(11) "IIT College"
}
[4]=> array(3) {
["name"]=> string(20) "Chemical Engineering"
["branch"]=> string(5) "Civil"
["college"]=> string(23) "Physics Training Center"
}
}
As you can see 11th-Physics comes out first. That is because the ASCII value of numbers is lower than that of letters. To fix this, modify the $search... arrays by prepending a high ASCII character before the string.
if(strpos(strtolower($row['name']), 'physics') !== false) {
// if the first character is a number, prepend an underscore
$searchName[$key] = is_numeric(substr($row['name'], 0, 1)) ? '_'.$row['name'] : $row['name'];
$foundInName[] = $row;
}
Which yields the following output:
array(5) {
[0]=> array(3) {
["name"]=> string(7) "Physics"
["branch"]=> string(11) "Bsc Physics"
["college"]=> string(20) "College of Chemistry"
}
[1]=> array(3) {
["name"]=> string(17) "Physics Education"
["branch"]=> string(10) "Mechanical"
["college"]=> string(3) "TBR"
}
[2]=> array(3) {
["name"]=> string(12) "11th-Physics"
["branch"]=> string(8) "Plus One"
["college"]=> string(8) "Plus One"
}
[3]=> array(3) {
["name"]=> string(7) "JEE-IIT"
["branch"]=> string(7) "Physics"
["college"]=> string(11) "IIT College"
}
[4]=> array(3) {
["name"]=> string(20) "Chemical Engineering"
["branch"]=> string(5) "Civil"
["college"]=> string(23) "Physics Training Center"
}
}
Try it here!

dynanmo db filterexpression with multiple condition php

I am unable to retrieve the item using filterExpression using logical and or or in Dyanamodb php using aws sdk. can any any one provide the code with the correct syntax to retrieve the item satisfying both the condition.
$scan_response = $dynamodb->scan(array(
'TableName' => $tableName,
'ExpressionAttributeValues' => [
':val1' => ['S' => '20'],
':val2' => ['S' => 'ajay'],
'FilterExpression' => 'age = :val1 AND name = :val2'
]));
i am getting error that
filterExpression must be a associative array
Thanks in advance
try this
$scan_response = $dynamodb->scan(array(
'TableName' => $tableName,
'ExpressionAttributeValues' => [
':val1' => ['S' => '20'],
':val2' => ['S' => 'ajay']],
'FilterExpression' => 'age = :val1 AND name = :val2'
));
badly placed closing ] creates
array(2) {
["TableName"]=>
string(3) "..."
["ExpressionAttributeValues"]=>
array(3) {
[":val1"]=>
array(1) {
["S"]=>
string(2) "20"
}
[":val2"]=>
array(1) {
["S"]=>
string(4) "ajay"
}
["FilterExpression"]=>
string(28) "age = :val1 AND name = :val2"
}
}
instead of required
array(3) {
["TableName"]=>
string(3) "..."
["ExpressionAttributeValues"]=>
array(2) {
[":val1"]=>
array(1) {
["S"]=>
string(2) "20"
}
[":val2"]=>
array(1) {
["S"]=>
string(4) "ajay"
}
}
["FilterExpression"]=>
string(28) "age = :val1 AND name = :val2"
}

PHP Multidimensional Array with multiple array with same keys?

I've been trying multiple things and for the life of me can not get this to work. I'm beginning to think it maybe isn't possible at this point.
So I have a SOAP API I'm sending this array too. Below is the code I currently have that works, but does not send the multiple values. It just uses the last one as it overwrite the previous.
Looking at this thread, what I'm doing should work?
$my_array['sn'] = "234234232";
$my_array['arrayparams'] = array(
'Param' => array( 'Name' => 'sending_key', 'Value' => 'blah',),
'Param' => array( 'Name' => 'sending_key2', 'Value' => '2',),
);
$my_array['push'] = true;
$my_array['endsession'] = false;
returns:
array(4) {
["sn"]=>
string(12) "234234232"
["arrayparams"]=>
array(1) {
["Param"]=>
array(2) {
["Name"]=>
string(61) "sending_key2"
["Value"]=>
string(1) "2"
}
}
["push"]=>
bool(true)
["endsession"]=>
bool(false)
}
I'm just having a time getting it to send this instead:
array(4) {
["sn"]=>
string(12) "234234232"
["arrayparams"]=>
array(2) {
["Param"]=>
array(2) {
["Name"]=>
string(61) "sending_key"
["Value"]=>
string(1) "blah"
}
["Param"]=>
array(2) {
["Name"]=>
string(61) "sending_key2"
["Value"]=>
string(1) "2"
}
}
["push"]=>
bool(true)
["endsession"]=>
bool(false)
}
The 'Param' array is very strict and has to have this value, I can not change to 'Param2' to get it to work. Thanks in advanced!
can you do this?
$my_array['arrayparams'] = array(
array('Param' => array( 'Name' => 'sending_key', 'Value' => 'blah',)),
array('Param' => array( 'Name' => 'sending_key2', 'Value' => '2',)),
);
The problem is you can't have the key 'Param' set in more than one key.
You would need to define 'Param' as an actual array, instead of as multiple keys within in array.
like so...
$my_array['Param'] = [
['Name' => 'sending_key', 'Value' => 'blah'],
['Name' => 'sending_key2', 'Value' => '2']
];

How to use struct formatting for PHP SOAP request

I am trying to make a SOAP request using PHP.
With the following parameters I am getting this error:
$soapURL = 'http://my.simpleviewcrm.com/webapi/listings/soap/listings.cfc?wsdl';
$client = new SoapClient($soapURL, array('trace' => true));
$listingRequest = array(
'username' => 'someuser',
'password' => 'somepass',
'pagenum' => 15,
'pagesize' => 10,
'filters' => array(
'FieldCategory' => 'Listing',
'FieldName' => 'Listingid',
'FilterType' => 'Equal To',
'FilterValue' => 13,
),
'displayamentities' => 1
);
$listingResponse = $client->__soapCall("getListings", $listingRequest);
//echo 'Request: ' . $client->__getLastRequest() .'';
echo "</br><h3>Listing Response</h3>";
print '<pre>';
var_dump($listingResponse);
print '</pre>';
OUTPUTS:
array(2) {
["DATA"]=>
array(0) {
}
["STATUS"]=>
array(3) {
["RESULTS"]=>
string(1) "0"
["ERRORS"]=>
array(1) {
[0]=>
array(3) {
["MESSAGE"]=>
string(44) "Element FILTERS is undefined in FILTERGROUP."
["DETAIL"]=>
string(0) ""
["TYPE"]=>
string(10) "Expression"
}
}
["HASERRORS"]=>
string(1) "1"
}
}
Any help as to why its not taking my filters?
Documentation here, https://www.dropbox.com/s/kbryi7syan7wt9a/Listings%20API%20Documentation.pdf
You are not forming your request message for getListings as per required by your operation.
As per your document (page 24), Filters is defined under FilterGroup. and each filter fields should be under items tag.So please form your request message like this in above code
<getListings>
<username>data</username>
<password>data</password>
<pagenum>data</pagenum>
<pagesize>data</pagesize>
<FILTERGROUP>
<FILTERS>
<ITEM>
<FILTERTYPE>data</FILTERTYPE>
<FIELDCATEGORY>data</FIELDCATEGORY>
<FILTERVALUE>data</FILTERVALUE>
<FIELDNAME>data</FIELDNAME>
</ITEM>
</FILTERS>
<FILTERGROUP>
</getListings>

Categories