AWS: how to get the instance status check state, not state - amazon-web-services

The aws console show two columns State and Status Checks, when an instance is launching. A state of Running is not a true reflection of state because the Status Checks could fail.
Anyone have any examples of .net C# code to check the Status Check state?
The closest I have is this:
var request = new DescribeInstanceStatusRequest();
request.InstanceId = insts.Select(i => i.InstanceId).ToList();
DescribeInstanceStatusResponse response = ec2Client.DescribeInstanceStatus(request);
InstanceStatus instanceStatus = response.DescribeInstanceStatusResult.InstanceStatus[0];
Console.WriteLine("Availability zone - " + instanceStatus.AvailabilityZone);
Console.WriteLine("Instance State Code - " + instanceStatus.InstanceState.Code);
Console.WriteLine("Instance State Name - " + instanceStatus.InstanceState.Name);
foreach (InstanceStatusEvent statusEvent in instanceStatus.InstanceStatusEvent)
{
Console.WriteLine("Event Code - " + statusEvent.Code);
Console.WriteLine("Event Description - " + statusEvent.Description);
Console.WriteLine("Earliest Scheduled Start Time - " + statusEvent.NotBefore);
Console.WriteLine("Latest Scheduled End Time - " + statusEvent.NotAfter);
}
But that just gives the State, not the Status Checks.

You need to look deeper into the InstanceStatus object. The status checks are in the InstanceStatusDetail and the SystemStatusDetail properties. Here is a snippet that gets that information for you:
var status = result.InstanceStatus[0];
Console.WriteLine("Instance Status = " + status.InstanceStatusDetail.Status);
Console.WriteLine("Instance Status Detail Name = " + status.InstanceStatusDetail.Detail[0].Name);
Console.WriteLine("Instance Status Detail Status = " + status.InstanceStatusDetail.Detail[0].Status);
Console.WriteLine("System Status = " + status.SystemStatusDetail.Status);
Console.WriteLine("System Status Detail Name = " + status.SystemStatusDetail.Detail[0].Name);
Console.WriteLine("System Status Detail Status = " + status.SystemStatusDetail.Detail[0].Status);

Using Lucee (cfml) I got it like this:
<cfset var DescribeInstanceStatusRequest = CreateObject('java','com.amazonaws.services.ec2.model.DescribeInstanceStatusRequest', jarLocation).init()>
<cfset var describeInstanceStatusRequest = DescribeInstanceStatusRequest.withInstanceIds([arguments.instanceId])>
<cfset var statusresult = ec2client.describeInstanceStatus(describeInstanceStatusRequest).getInstanceStatuses()[1].getInstanceStatus().getDetails()[1].getStatus()>
this (statusresult) gives "passed" if the server has passed all checks.
note: coldfusion handles arrays differently so if for example you were translating back to java you would use [0] instead of 1.
If you only want the status: running, stopped etc
<cfset var result = ec2client.describeInstanceStatus(describeInstanceStatusRequest).getInstanceStatuses()[1].getInstanceState().getName()>

Related

Netsuite reconfigure inventory detail error

On a custom record creation i am calling a map reduce script that in creating a negative inventory adjustment.
The script is called on after submit.
I am using following code to populate the inventory detail subrecords
for (var n = 0; n < cp_lotsearch.length; n++) {
if (cree_onhand > 0) {
var cp_lotid = cp_lotsearch[n].getValue({name: 'internalid'});
var cp_parentcasenum = cp_lotsearch[n].getValue({name: 'custrecord_nsts_ia_lot'});
var itemsearch = search.create({
type: 'item',
filters: ['inventorynumber.inventorynumber', 'is', cp_parentcasenum],
columns: [search.createColumn({name: "quantityonhand", join: "inventorynumber"})]
}).run().getRange({
start: 0,
end: 1000
});
var qtyonhand = itemsearch[0].getValue({name: 'quantityonhand', join: 'inventorynumber'});
var remain_qtyonhand = Number(qtyonhand) - Number(cree_onhand);
if (remain_qtyonhand >= 0) {
var reduceqty = 0 - Number(cree_onhand);
} else {
var reduceqty = 0 - Number(qtyonhand);
}
log.debug("reduceqty", reduceqty);
subrecord.insertLine({sublistId: 'inventoryassignment',line: n});
subrecord.setSublistText({ sublistId: 'inventoryassignment',fieldId: 'issueinventorynumber',line: n,text: cp_parentcasenum});
subrecord.setSublistValue({sublistId: 'inventoryassignment',fieldId: 'binnumber', line: n, value: cree_bin});
subrecord.setSublistValue({sublistId: 'inventoryassignment',fieldId: 'quantity',line: n,value: reduceqty});
log.debug("reduceqty added to inventory detail", reduceqty);
cree_onhand = Number(cree_onhand) + Number(reduceqty);
}
}
var invadjid = parentcase_inv_Adj.save({
enableSourcing: true,
ignoreMandatoryFields: true
});
When i try to run this code i am getting following error:
"type":"error.SuiteScriptError","name":"USER_ERROR","message":"You still need to reconfigure the inventory detail record after changing the quantity."
Same code is running perfect in sandbox account but in production it is throwing error
Can anyone help me to solve this error?
I Got one solution in suite answer that i already tried but it is not working here is link to it:
https://netsuite.custhelp.com/app/answers/detail/a_id/80790/kw/reconfigure%20error
I've discovered this error can be triggered server-side if :
multiple units of measure feature is enabled.
the stock units of measure are not 1-to-1, i.e. the receipt unit is in packs of 20, but the base unit of the UOM is 1's.
the item is serialised.
However, if the same is attempted client-side, the error becomes "The total inventory detail quantity must be XX" (XX being the quantity set in "adjustqtyby" on the inventory adjustment line).

Cloud Spanner DB - Unable to read timestamp from ReadOnlyTransaction.getReadTimestamp()

I was trying to use ReadOnlyTransaction.getReadTimestamp() function but I keep running into exception:
"Method can only be called after read has returned data or finished"
I have returned one or two records from DB, but I can't read timestamp.
Below is sample code how and what I am doing.
IO {
val db = spannerClientInstance
val rotxn = db.singleUseReadOnlyTransaction()
val sql = "SELECT " +
"Name " +
"FROM Person " +
"WHERE Name= #Name"
val resultSet = db.singleUse.executeQuery(
Statement.newBuilder(sql).bind("Name").to(name).build()
)
(resultSet, rotxn)
}.bracket {
case (resultSet, rotxn) =>
IO {
val result =
scala.collection.mutable.Map.empty[String, Person]
while (resultSet.next()) {
result += (resultSet.getString(0) -> new Person(resultSet.getString(0)))
}
(result.toMap, rotxn.getReadTimestamp)
}
} {
case (resultSet, _) =>
IO(resultSet.close())
}
I tried closing resultSet and/or rotxn with resultSet.close() and rotxn.close() and then calling rotxn.getReadTimestamp(), but didn't have much luck. I got the same error message.
I am using Spanner Java lib: com.google.cloud:google-cloud-spanner:2.0.1
Tried googling the issue but didn't find much. Any help is welcomed :)
Thanks. :)
It seems that you are not actually executing the query on the read-only transaction that you started. The code that is executing the query is:
val resultSet = db.singleUse.executeQuery(
Statement.newBuilder(sql).bind("Name").to(name).build()
)
That query is using a single-use read-only transaction, and not your previously read-only transaction. Try executing it like this instead:
val resultSet = rotxn.executeQuery(
Statement.newBuilder(sql).bind("Name").to(name).build()
)

Multiple cloud-sql table export as csv

Is there a way to export multiple SQL tables as csv by issuing specific queries from cloud-sql.
Below is the code i currently have. When I call the exportTables for multiple tables back to back, I see a 409 error. It's probably becaause cloud-sql instance is busy with an export and it's not allowing subsequent export request.
How can I get this to work ? What would be the ideal solution here.
private void exportTables(String table_name, String query)
throws IOException, InterruptedException {
HttpClient httpclient = new HttpClient();
PostMethod httppost =
new PostMethod(
"https://www.googleapis.com/sql/v1beta4/projects/"
+ "abc"
+ "/instances/"
+ "zxy"
+ "/export");
String destination_bucket =
String.join(
"/",
"gs://" + "test",
table_name,
DateTimeUtil.getCurrentDate() + ".csv");
GoogleCredentials credentials =
GoogleCredentials.getApplicationDefault().createScoped(SQLAdminScopes.all());
AccessToken access_token = credentials.refreshAccessToken();
access_token.getTokenValue();
httppost.addRequestHeader("Content-Type", "application/json");
httppost.addRequestHeader("Authorization", "Bearer " + access_token.getTokenValue());
String request =
"{"
+ " \"exportContext\": {"
+ " \"fileType\": \"CSV\","
+ " \"uri\":\""
+ destination_bucket
+ "\","
+ " \"databases\": [\""
+ "xyz"
+ "\"],"
+ " \"csvExportOptions\": {"
+ " \"selectQuery\": \""
+ query
+ "\""
+ " }\n"
+ " }"
+ "}";
httppost.setRequestEntity(new StringRequestEntity(request, "application/json", "UTF-8"));
httpclient.executeMethod(httppost);
if (httppost.getStatusCode() > 200) {
String response = new String(httppost.getResponseBody(), StandardCharsets.UTF_8);
if (httppost.getStatusCode() != 409) {
throw new RuntimeException(
"Exception occurred while exporting the table: " + table_name + " Error " + response);
} else {
throw new IOException("SQL instance seems to be busy at the moment. Please retry");
}
}
httppost.releaseConnection();
logger.info("Finished exporting table {} to {}", table_name, destination_bucket);
}
I don't have suggestion to fix the issue on Cloud SQL directly, but a solution to execute in sequence the export thanks to a new tool: Workflow
Define the data format that you want, in JSON, to define ONE export.
Then provide an array of configuration to your workflow
In this workflow,
Make a loops on the configuration array
Perform an API call to Cloud SQL to generate the export on each configuration
Get the answer of the API Call, you have the jobId
Sleep a while
Check if the export is over (with the jobId).
If not, sleep and check again
If yes, loop (and thus start the next export)
It's serverless and the free tier makes this use case free.

How do I output information in pre-request script

Using the standalone version of Postman, how do I output some debug information in Postman pre-request script?
The code below works great for tests (post-request) but not for pre-request since there is no tests[] array.
var jsonData = JSON.parse(responseBody);
tests["key = " + jsonData.key] = true; // debug message
tests["value = " + jsonData.value] = true; // debug message
The only way I could find to accomplish this is by using:
console.log("key = " + key);
console.log("value = " + value);
And then open up the Postman console (Cmd + Option + C / Ctrl + Alt + C) to view the debugs logs in a different window.

An access token is required to request this resource FQL issue

I have a command line application which executes a query. Here is the code.
Problem is that it receives an access token of the form "abc...|xyz...". There is
no session portion. But the token returned is useless for executing my query to
select insights for a page of mine. Help !!
const string permissions = "manage_pages,read_insights,offline_access";
dynamic oauthClient = new FacebookOAuthClient() ;
oauthClient.AppId = username ;
oauthClient.AppSecret = password ;
dynamic parameters = new ExpandoObject() ;
parameters.scope = permissions ;
parameters.response_type = "token" ;
// parameters.grant_type = "client_credentials" ;
dynamic result = oauthClient.GetApplicationAccessToken(parameters);
string token = result.access_token ;
// token comes back as "abc...|xyz..."
var fb = new FacebookClient(token);
string query = " select metric, value " +
" from insights " +
" where object_id = MY_PAGE and " +
" metric in ( 'page_impressions' , 'page_stories') and " +
" end_time >= end_time_date('2012-02-21') and " +
" end_time <= end_time_date('2012-02-11') and " +
" period = period('day') " ;
dynamic result2 = fb.Query(query) ; // Exception generated on this line.
return result2 ;
Any ideas?
The error you are getting is from Facebook and it is simply saying you don't have a valid token to make the request. You must request a user access token using OAuth. After you have a valid access token you can make your request with the following code:
var fb = new FacebookClient("valid_user_access_token");
string query = "YOUR FQL QUERY HERE";
dynamic result = fb.Query(query);
To learn how to get a valid access token read the Facebook documentation here: https://developers.facebook.com/docs/authentication/