PHP: Error in creating Server Instance in Google Cloud Compute - php

While using Google Cloud Compute's API in PHP, I am able to start, stop, delete instances as well as create and delete disks.
However, when trying to create an Instance, I keep getting this error
Invalid value for field 'resource.disks'
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/compute/v1/projects/project/zones/zone/instances: (400) Invalid value for field 'resource.disks': ''. Boot disk must be specified.' in /var/www/html/google/google-api-php-client/src/Google/Http/REST
Here is the request I am making
self::connectClient();
$computeService = new Google_Service_Compute($this->client);
if ($this->client->getAccessToken())
{
$googleNetworkInterfaceObj = new Google_Service_Compute_NetworkInterface();
$network = self::DEFAULT_NETWORK;
$googleNetworkInterfaceObj->setNetwork($network);
$diskObj = self::getDisk($instance_name);
$new_instance = new Google_Service_Compute_Instance();
$new_instance->setName($instance_name);
$new_instance->setMachineType(self::DEFAULT_MACHINE_TYPE);
$new_instance->setNetworkInterfaces(array($googleNetworkInterfaceObj));
$new_instance->setDisks(array(
"source"=>$diskObj->selfLink,
"boot"=>true,
"type"=>"PERSISTENT",
"deviceName"=>$diskObj->name,
));
$insertInstance = $computeService->instances->insert(self::DEFAULT_PROJECT,self::DEFAULT_ZONE_NAME, $new_instance);
Any help will be highly appreciated, thank you.

Ok the solution was really simple (and silly)
Instead of
$new_instance->setDisks(array(
"source"=>$diskObj->selfLink,
"boot"=>true,
"type"=>"PERSISTENT",
"deviceName"=>$diskObj->name,
));
It's supposed to be
$new_instance->setDisks(array(
array(
'source'=>self::getDisk($instance_name)->selfLink,
'boot'=>true,
'type' => "PERSISTENT",
'deviceName'=>self::getDisk($instance_name)->name,
)
));

Related

Amazon SP_API POST createReport() responded return Invalid Input

I am trying to create a report so I can import products in bulk. The issue i am facing right now is that whatever I have done always got Invalid input error. It seems very very ambiguous error message I have checked issue here and similar once but unfortunately no solution worked.
So if you check below received error from sp-api
{
"notifications": [],
"text": "{\"message\":\"[400] [{\\\"code\\\":\\\"InvalidInput\\\",\\\"message\\\":\\\"Could not match input arguments\\\"}]\",\"success\":false}"
}
you will notice that it seems there is a mistake with my code regarding datatype(as I understood from error) But I have made sure many times of datatype, even I have wrote data as string[] but honestly it took too much time. Please find my code
$config = new Configuration([
"lwaClientId" => $account_data['lwa_client_id'],
"lwaClientSecret" => $account_data['lwa_client_secret'],
"lwaRefreshToken" => $account_data['lwa_refresh_token'],
"awsAccessKeyId" => $account_data['aws_access_key'],
"awsSecretAccessKey" => $account_data['aws_secret_key'],
"endpoint" => SellingPartnerApi\Endpoint::NA ,
]);
$apiInstance = new SellingPartnerApi\Api\ReportsApi($config);
$body = new SellingPartnerApi\Model\Reports\CreateReportSpecification([
'marketplace_ids' => [$merchant_data['marketplace_ids']],
'report_type' => ReportType::GET_MERCHANT_LISTINGS_ALL_DATA['name'],
]);
try{
$report_id = $apiInstance->createReport($body);
}catch(Exception $e){
return array("message"=>$e->getMessage(),'success'=>false);
}
Btw, I am using this lib https://github.com/jlevers/selling-partner-api
Please note that 3 of CreateReportSpecification parameter are optional (report_options, data_start_time, data_end_time) I didn't passed it at constructor.
Could you please advise what's went wrong with my code? Why I am receiving Invalid Input ??
Thanks in advance
Check that AWS_ENV=PRODUCTION (not SANDBOX)

AMQPException Library error: table too large for buffer

I am using the messenger component in a Symfony application to process messages from rabbitmq.
When I send a 2-3mb message and an error occurs in my handler, the middleware that tries to send the message back to rabbit raises an exception of type:
AMQPException Library error: table too large for buffer
I found similar error in this links :
https://github.com/vyuldashev/laravel-queue-rabbitmq/issues/10
https://github.com/alanxz/rabbitmq-c/issues/224
https://github.com/php-amqp/php-amqp/issues/131
But I don't see any solution or workaround provided!
I found a workaround: when the message is being redirected back to queue (to retry later) one huge stamp is being added
In my serializer, in method 'encode' I filter stamps:
$allStamps = [];
foreach ($envelope->all() as $stampKey => $stamps) {
if ($stampKey === 'Symfony\Component\Messenger\Stamp\ErrorDetailsStamp') {
// this header could be huge and drasticaly increase a size of a message
continue;
}
$allStamps = array_merge($allStamps, $stamps);
}
return [
'body' => serialize($messageBody),
'headers' => [
// store stamps as a header - to be read in decode()
'stamps' => serialize($allStamps),
],
];

Parse error using 'use' in Google Cloud

I am trying to post some form data to Google Datastore, using this documentation here and here. I am struggling with knowing how to post the form data to the datastore, but I thought I had cracked it when I got the following error.
Parse error: syntax error, unexpected 'use' (T_USE) in record-usage.php on line 23
So my question is in two parts:
how do I post data to the Datastore from my form? (the examples in the documentation seem to offer two different ways of posting to the store)
how do I fix this syntax error?
Here is my code (it's actually line 7 in the sample below):
if(isset($_POST['submit'])) {
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\Datastore\DatastoreClient;
# Your Google Cloud Platform project ID
$projectId = 'room-usage';
# Instantiates a client
$datastore = new DatastoreClient([
'projectId' => $projectId
]);
# The kind for the new entity
$kind = 'RoomUsage';
# The name/ID for the new entity
$name = $roomname + $_POST('timestamp');
# The Cloud Datastore key for the new entity
$taskKey = $datastore->key($kind, $name);
if($_POST('countinput') == '') {
$formdata->Headcount = $_POST('countslider');
} else {
$formdata->Headcount = $_POST('countinput');
}
$formdata->Timestamp = $_POST('timestamp');
$formdata->EnteredBy = $_POST('userid');
$formdata->RoomID = $_POST('roomid');
$formdata->Activity = $_POST('activity');
$formdata->Estimate = $_POST('estimate');
$formdata->NotAudited = $_POST('notaudited');
$formdata->Reason = $_POST('reason');
function save_room_usage(DatastoreClient $datastore, $formdata) {
$RoomUsage = $datastore->RoomUsage();
$transaction->updateBatch([$formdata]);
$transaction->commit();
}
# Prepares the new entity
$task = $datastore->entity($taskKey,
['Timestamp' => $_POST('timestamp'),
'Headcount' => $formdata->Headcount,
'EnteredBy' => $_POST('userid'),
'RoomID' => $_POST('roomid'),
'Activity' => $_POST('activity'),
'Estimate' => $_POST('estimate'),
'NotAudited' => $_POST('notaudited'),
'Reason' => $_POST('reason')]);
# Saves the entity
$datastore->upsert($task);
$status = 'Saved ' . $task->key() . ': ' . $task['description'];
}
Use
You can't have use inside a function. Think of it like an import.
Instead, move it outside of the method but inside your namespace. Simplest way to get going is just move it to the top of your file.
Writing data
Looking at this code:
$transaction->updateBatch([$formdata]);
$transaction->commit();
I think you've misinterpreted the transaction documentation. In the code example it presents, it first reads entities from Datastore via a Batch Lookup, then writes them back as a batch with:
$transaction->updateBatch([$fromAccount, $toAccount]);
In that example $fromAccount and $toAccount are proper entities with keys.
In your example, you are trying to batch write just a bunch of random data. Since you are only writing one record, you should delete that code.
The second part of your code where you create an entity and then upsert it should work. If you did end up needing to write more than one entity in a transaction, it is $task that you would use in the updateBatch method rather than the raw data.

SOAP Logic help retrieving and updating data

So have been playing with this for a while now.
Pretty new with SOAP to be honest.
Issue is this:
I have documentation which i have been following and i can retrieve one persons profile using the unique ID.
Now i want to receive all users in a certain pool/group/target etc.
here is what i am using:
$client = new SoapClient($pr, array('login' => $username, 'password' => $password, 'trace'=>true));
and the code is like so:
$job_info = $client->getByTargetGroup(16520);
also tried this
$job_info = $client->getByTargetGroup(16520, array('NAME','EMAIL','FIRSTNAME') );
In the documentation of the soap i get this info:
parameters type getByTargetGroup
targetgroup_id type int
pool_attribute_list - nillable; type ArrayOfString
**item** - optional, unbounded; type string
But when executed i get this error
Fatal error: Uncaught SoapFault exception: [Receiver] Maximum number of 20 active jobs exceeded for this customer
Am i using SOAP correctly? or reading the documentation incorrectly?
I am just doing this to view feedback
echo "<pre>";
print_r( $job_info);
echo "</pre>";
Image link to the documentation:
Image

php salesforce novice INVALID_FIELD: No such column 'fields' on entity 'Contact'

I am having a tough time and have spent like 4 hrs trying to debug this. I am new to PHP, but did not expect this to be so hard.
This is the code, i am trying to update a contact table. i tried upsert and update nothign seems to work
this is the update" version of the code.
$id = '003A000000XRVFxIAP';
$updateFields = array (
'Id' => $id,
'MailingCity' => 'New York',
'MailingState' => 'NY'
);
$sObject1 = new SObject();
//$sObject1->fields = $updateFields;
//$sObject1->MailingCity= 'New York';
$sObject1->type = 'Contact';
try{
$updateResponse = $client->update(array($sObject1),'Contact');
$myID = $updateResponse->id;
}
Strict Standards: Creating default object from empty value in C:\xampp\htdocs\Proj1\ForceToolkit\soapclient\SforceEnterpriseClient.php on line 89 INVALID_FIELD: No such column 'fields' on entity 'Contact'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names. Error Info SoapFault exception: [sf:INVALID_FIELD] INVALID_FIELD: No such column 'fields' on entity 'Contact'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names. in C:\xampp\htdocs\Proj1\ForceToolkit\soapclient\SforceBaseClient.php:508 Stack trace: #0 C:\xampp\htdocs\Proj1\ForceToolkit\soapclient\SforceBaseClient.php(508): SoapClient->__call('update', Array) #1 C:\xampp\htdocs\Proj1\ForceToolkit\soapclient\SforceBaseClient.php(508): SoapClient->update(Object(stdClass))
#2 C:\xampp\htdocs\Proj1\ForceToolkit\soapclient\SforceEnterpriseClient.php(90): SforceBaseClient->_update(Object(stdClass))
#3 C:\xampp\htdocs\Proj1\createAccount.php(95): SforceEnterpriseClient->update(Array, 'Contact') #4 {main}
Looking at your trace you appear to be using the enterprise client and I can assume enterprise WSDL. This is strongly typed and you should be using the WSDL specific to your Salesforce org. If you are not using the WSDL downloaded from your org it will not have the correct objects and fields defined within it.
I would recommend using the partner client and partner WSDL. This is loosely typed and far more flexible. It would be easier to work with particularly if you aren't familiar with the PHP or the webservices.
The following should do your update...
$sObject1 = new stdClass();
$sObject1->type = 'Contact';
$sObject1->Id = $id;
$sObject1->fields['MailingCity'] = 'New York';
$sObject1->fields['MailingState'] = 'NY';
try
{
$updateResponse = $client->update( array( $sObject1 ) );
}
catch( Exception $exception )
{
// Do something
}
Note that the Id is a property of $sObject and not a value in the fields array. Also there is no need to specify the 'Contact' in your update call as you have it set in the type property of $sObject.
When using the Enterprise WSDL, don't create a new SObject, just create a new stdClass. See the examples in the PHP Getting Started Guide; SObjects are only for use with the partner WSDL.
I have encountered the same issue updating while using the Enterprise client. I experienced the same issue while updating a custom field on an Account object.
The issue that I had with the SObject was that it tried to update a parameter called 'fields' during the update. With the Enterprise WSDL not including that field, I used unset() to remove the 'fields' attribute from the SObject.
I appreciate this is a bit of a hacky solution, but it could come in useful for others that encounter this issue.
$sUpdateObject = new SObject();
$sUpdateObject->id = $record->Id;
$sUpdateObject->MyCustomField__c = 0;
unset($sUpdateObject->fields);
$updateResponse = $mySforceConnection->update(array($sUpdateObject), 'Account');
print_r($upsertResponse);

Categories