openstack npm pkgcloud createImage() function not working - openstack

I am trying to create an image of an instance in openstack using npm pkgcloud.
For this I am using the code as below:
var openstack_client_compute = null;
openstack_client_compute = pkgcloud.compute.createClient({
provider: PROVIDER, // required
username: USERNAME, // required
password: PASSWORD, // required
region: REGION,
authUrl: AUTH_URL // required
});
options = {
name: 'image1', // required
server: '0e4d56a2-173a-425d-befd-cec366605522' // required
};
openstack_client_compute.createImage(options, function(err, image){
if(err){
console.log(err);
}
console.log(image);
});
I am getting the following error :
name: 'Error',
provider: 'openstack',
failCode: 'Service Unavailable',
statusCode: 503,
href: 'http://controller:8774/v2.1/6af81940df89199f088beba7d93/servers/0e4d56a2-173a-425d-befd-cec366605522/action',method: 'POST',
headers:
{ server: 'squid',
'mime-version': '1.0',
date: 'Mon, 09 Apr 2018 07:21:15 GMT',
'content-type': 'text/html;charset=utf-8',
'content-length': '3012',
'x-squid-error': 'ERR_DNS_FAIL 0',
'x-cache': 'MISS from lproxy',
'x-cache-lookup': 'MISS from proxy:8080',
connection: 'close' },
Note : other functions such as createStack deleteStack getStack etc are functioning properly
It is showing the error that unable to resolve host name (controller is not getting resolved to IP) the code is failing due to that.
Any possibility that a change in openstack configuration may resolve it.
If yes what changes are needed?

Related

WebPush.sendNotification Node.js giving 401 "header must be specified" error on googleapis endpoint

I'm getting the following error:
WebPushError: Received unexpected response code
at IncomingMessage.<anonymous> (/Users/sepp/.../node_modules/web-push/src/web-push-lib.js:347:20)
at IncomingMessage.emit (node:events:406:35)
at endReadableNT (node:internal/streams/readable:1331:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
statusCode: 401,
headers: {
'content-type': 'text/plain; charset=utf-8',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '0',
date: 'Wed, 01 Feb 2023 19:57:43 GMT',
'content-length': '40',
'alt-svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000',
connection: 'close'
},
body: 'authorization header must be specified.\n',
endpoint: 'https://fcm.googleapis.com/fcm/send/duj-etc-etc
The code involved is:
import * as webPush from "web-push";
const subDetails = {
endpoint: "https://fcm.googleapis.com/fcm/send/duja6etc-etc",
expirationTime: null,
keys: {
p256dh: "BHtwM-etc-etc",
auth: "aYkx0etc-etc"
}
}
await webPush.sendNotification(subDetails, "test message", );
I found this issue on Github, and there was some debilitation as to whether or not it has to do with the environment. I am running my front-end page and back-end server both locally. There is a 'x-frame-options': 'SAMEORIGIN' header in the response.
As you can see from the code above, I do not have VAPID set up.
If I use console.log(webPush.generateRequestDetails(pushSub.details, args.msg)) to see what the headers and body of the request are, I get the following details, which show that the auth header is not set:
{
method: 'POST',
headers: {
TTL: 2419200,
'Content-Length': 121,
'Content-Type': 'application/octet-stream',
'Content-Encoding': 'aes128gcm'
},
body: <Buffer ....>,
endpoint: 'https://fcm.googleapis.com/fcm/send/duj-etc-etc'
}
Questions
Are there any special requirements for localhost stuff?
What does it take for auth headers to be included?
EDIT: The browser I'm using is Opera GX. I did find a browser support table, which says that opera does not yet support push on desktop. The error still seems to imply something else may be the issue. Testing in Firefox Dev Edition, it works! Unfortunately, in Chrome the same exact error as Opera GX is given.
The issue is two-fold.
Issue #1: Opera GX does not support push notifications on desktop. Check this table for details on your browser.
Issue #2: For any push services which use a https://fcm.googleapis.com/fcm/send/ endpoint, you'll need auth headers. To create them, you'll need a VAPID. Here's how to set that up in web-push:
Create your public and private keys in command line (you many need to do ./node_modules/.bin/web-push instead):
$ web-push generate-vapid-keys --json
Store the private key somewhere safe only your server can get to it. Public key will be needed by both front and back end.
Update your code to generate auth headers and add them to the request
import * as webPush from "web-push";
const subDetails = {
endpoint: "https://fcm.googleapis.com/fcm/send/duja6etc-etc",
expirationTime: null,
keys: {
p256dh: "BHtwM-etc-etc",
auth: "aYkx0etc-etc"
}
}
const VAPID = {
publicKey: "lalalla-etc-etc-put-anywhere",
privateKey: "lCRVkwS-etc-etc-put-somewhere-safe"
}
const parsedUrl = new URL(subDetails.endpoint);
const audience = `${parsedUrl.protocol}//${parsedUrl.hostname}`;
// technically, the audience doesn't change between calls, so this can be cached in a non-minimal example
const vapidHeaders = webPush.getVapidHeaders(
audience,
'mailto: example#web-push-node.org',
VAPID.publicKey,
VAPID.privateKey,
'aes128gcm'
);
await webPush.sendNotification(subDetails, "test msg", {
headers: vapidHeaders
});
The code above should work fine in chrome and firefox. Let me know if this minimal example needs more for some other browser.

Post multiple logs to DataDog with 1 HTTP request

I want to post multiple logs to DataDog from a JS function, using a single HTTP request. Looking at the v2 docs for DataDog's 'send logs' POST endpoint, it sounds like this is possible:
For a single log request, the API ... For a multi-logs request, the API ...
But it's not clear to me from the docs how to actually send a 'multi-logs' request. I've tried the following:
const dataDogEndpoint = 'https://http-intake.logs.datadoghq.com/api/v2/logs';
const body = {
ddtags: 'env:production,status:info',
hostname: 'my-host',
message: ['My first production log.', 'My second production log.'],
service: 'my-service'
};
const response = await fetch(dataDogEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'DD-API-KEY': apiKey
},
body: JSON.stringify(body)
});
Perhaps unsurprisingly, this appears in DataDog as a single log with the following content:
[My first production log., My second production log.]
How can I achieve this?
Got it - this can be achieved by adding multiple log objects to the body like so:
const dataDogEndpoint = 'https://http-intake.logs.datadoghq.com/api/v2/logs';
const body = [{
ddtags: 'env:production,status:info',
hostname: 'my-host',
message: 'My first production log.',
service: 'my-service'
},{
ddtags: 'env:production,status:info',
hostname: 'my-host',
message: 'My second production log.',
service: 'my-service'
}];
const response = await fetch(dataDogEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'DD-API-KEY': apiKey
},
body: JSON.stringify(body)
});
(You'll probably want a loop instead of instantiating each log object separately.)

Dynamoose: The Model object doesn't allow config as a parameter

I have created a model that was working when I had my backend functions running on my local machine, but when it uses AWS I get and authentication problem when the table is being queried:
2022-02-18T08:54:58.149Z 31785a81-ea8c-434b-832f-6dcff583c01c ERROR Unhandled Promise Rejection
{
"errorType": "Runtime.UnhandledPromiseRejection",
"errorMessage": "AccessDeniedException: User: arn:aws:sts::xxxxxxxxx:assumed-role/dev-production-history-role/ppc-backend-functions-dev-queryProductionHistoryItems is not authorized to perform: dynamodb:CreateTable on resource: arn:aws:dynamodb:eu-west-1:xxxxxxxxxxxx:table/dev-production-history-table",
"trace": [
"Runtime.UnhandledPromiseRejection: AccessDeniedException: User: arn:aws:sts::xxxxxxxxx:assumed-role/dev-production-history-role/ppc-backend-functions-dev-queryProductionHistoryItems is not authorized to perform: dynamodb:CreateTable on resource: arn:aws:dynamodb:eu-west-1:xxxxxxxxx:table/dev-production-history-table",
" at process.<anonymous> (/var/runtime/index.js:35:15)",
" at process.emit (events.js:400:28)",
" at processPromiseRejections (internal/process/promises.js:245:33)",
" at processTicksAndRejections (internal/process/task_queues.js:96:32)"
]
}
This is how my model is defined:
const model = dynamoose.model<ProductionHistory>(DatabaseTableNames.productionHistoryTable, {schema});
From looking at possible solutions, it seems that adding {“create”: false} to the parameters might solve the issue, but in version 3 of Dynamoose you cannot add three parameters, so this will not work:
const model = dynamoose.model<ProductionHistory>(DatabaseTableNames.productionHistoryTable,
schema, {“create”: false});
Does anyone know how to overcome this problem so that it works with Dynamoose version 3?
I have made the changes that Charlie Fish suggested and I am now getting the following error:
2022-02-18T16:39:39.211Z b00a36b8-c612-4886-b9fc-da7084527bf0 INFO AccessDeniedException: User: arn:aws:sts::874124979428:assumed-role/dev-production-history-role/ppc-backend-functions-dev-queryProductionHistoryItems is not authorized to perform: dynamodb:Query on resource: arn:aws:dynamodb:eu-west-1:874124979428:table/dev-production-history-table
at deserializeAws_json1_0QueryCommandError (/var/task/node_modules/dynamoose/node_modules/#aws-sdk/client-dynamodb/dist-cjs/protocols/Aws_json1_0.js:2984:41)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async /var/task/node_modules/dynamoose/node_modules/#aws-sdk/middleware-serde/dist-cjs/deserializerMiddleware.js:7:24
at async /var/task/node_modules/dynamoose/node_modules/#aws-sdk/middleware-signing/dist-cjs/middleware.js:11:20
at async StandardRetryStrategy.retry (/var/task/node_modules/dynamoose/node_modules/#aws-sdk/middleware-retry/dist-cjs/StandardRetryStrategy.js:51:46)
at async /var/task/node_modules/dynamoose/node_modules/#aws-sdk/middleware-logger/dist-cjs/loggerMiddleware.js:6:22
at async main (/var/task/node_modules/dynamoose/dist/aws/ddb/internal.js:6:20)
at async /var/task/node_modules/dynamoose/dist/ItemRetriever.js:105:32
at async Object.queryByDate (/var/task/functions/production-history/query.js:1:1723)
at async Runtime.l [as handler] (/var/task/functions/production-history/query.js:1:1974) {
__type: 'com.amazon.coral.service#AccessDeniedException',
'$fault': 'client',
'$metadata': {
httpStatusCode: 400,
requestId: 'DCB6SNOH9O2NTRAS9LL3OJGEU7VV4KQNSO5AEMVJF66Q9ASUAAJG',
extendedRequestId: undefined,
cfId: undefined,
attempts: 1,
totalRetryDelay: 0
},
'$response': HttpResponse {
statusCode: 400,
headers: {
server: 'Server',
date: 'Fri, 18 Feb 2022 16:39:39 GMT',
'content-type': 'application/x-amz-json-1.0',
'content-length': '331',
connection: 'keep-alive',
'x-amzn-requestid': 'DCB6SNOH9O2NTRAS9LL3OJGEU7VV4KQNSO5AEMVJF66Q9ASUAAJG',
'x-amz-crc32': '2950006190'
},
body: IncomingMessage {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
socket: null,
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Array],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 400,
statusMessage: 'Bad Request',
client: [TLSSocket],
_consuming: false,
_dumped: false,
req: [ClientRequest],
[Symbol(kCapture)]: false,
[Symbol(RequestTimeout)]: undefined
}
}
}
This is my code now:
const model = dynamoose.model<ProductionHistory>(DatabaseTableNames.productionHistoryTable, schema);
const Table = new dynamoose.Table(DatabaseTableNames.productionHistoryTable, [model], {"create": false, "waitForActive": false});
Any ideas?
Disclaimer: this answer is based on Dynamoose v3.0.0 beta 1. Answers based on beta versions can become outdated quickly, so be sure to check for any updated details for your version of Dynamoose.
In Dynamoose v3, a new class was introduced called Table. This represents a single DynamoDB Table. In previous versions of Dynamoose, a Model represented a single DynamoDB Table, but based on the API also kinda represented a specific entity or model in your data structure (ex. Movie, Order, User, etc). This lead to complications and confusion when it comes to single table design structures especially.
In terms of code, what this means is the following.
// If you have the following code in v2:
const User = dynamoose.model("User", {"id": String});
// It will be converted to this in v3:
const User = dynamoose.model("User", {"id": String});
const DBTable = new dynamoose.Table("DBTable", [User]);
So basically you create a new Table instance based on your Model. In v3 if you try to use your Model without created a Table instance based on it, it will throw an error.
Once you do that, the 3rd parameter of your Table constructor, you can pass in settings. Once of which being create. So you can set that to false as that parameter.
Your code specifically would look something like:
const model = dynamoose.model<ProductionHistory(DatabaseTableNames.productionHistoryTable, schema);
const DBTable = new dynamoose.Table(DatabaseTableNames.productionHistoryTable, [model], {"create": false});

Using firebase RestApi to signup users using email and password

I'm creating a project where users need to able to log in to their account and see some data. I'm creating a windows application with unity, so from what I understood from researching, I have to use the firebase RestAPI, not the SDK. I managed to use the realTime database but I'm struggling with the authentication side of things.
I followed this tutorial and used the documentation for signing up users into firebase with the RestAPI. I keep getting a 400 (Bad Request) error. I found this post, where the solution was to use a strong password, but that didn't work.
Since I'm using a not so reliable unity c# package as a client, I tested my code with nodeJs as well. Same error.
My code:
C#
private void SignUpUser(string email, string username, string password)
{
string userData = "{\"email\":\"" + email + "\",\"password\":\"" + password + "\",\"returnSecureToken\":true}";
// Content type is json by default
RestClient.Post<SignResponse>("https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=" + AuthKey, userData).Then(
response =>
{
Debug.Log("Success");
}).Catch(error =>
{
Debug.Log(error);
});
}
Javascript
const axios = require("axios");
axios
.post(
'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=' + API_KEY,
{
email: "myEmddail#example",
password: "superStrongzi344##",
returnSecureToken: true,
},
{
'Content-Type': 'application/json',
}
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Part of response:
response:
{ status: 400,
statusText: 'Bad Request',
headers:
{ expires: 'Mon, 01 Jan 1990 00:00:00 GMT',
pragma: 'no-cache',
date: 'Sun, 10 May 2020 21:09:52 GMT',
'cache-control': 'no-cache, no-store, max-age=0, must-revalidate',
vary: 'X-Origin, Referer, Origin,Accept-Encoding',
'content-type': 'application/json; charset=UTF-8',
server: 'ESF',
'x-xss-protection': '0',
'x-frame-options': 'SAMEORIGIN',
'x-content-type-options': 'nosniff',
'alt-svc':
'h3-27=":443"; ma=2592000,h3-25=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"', 'accept-ranges': 'none',
connection: 'close',
'transfer-encoding': 'chunked' },
config:
{ url:
'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=API_KEY',
method: 'post',
data:
'{"email":"myEmddail#example","password":"superStrongzi344##","returnSecureToken":true}',
Is there anything I'm missing?
Thanks
Try enabling registering with e-mail in your firebase console. Also the c# library you're using doesn't seem very reliable and might not be well suited for error handling, I would suggest the native System.net.http library that's built in. An example of a request:
using System.Net.Http;
private static readonly HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();

Hubot with slack adapter - cannot perform rtm.start

I'm trying to have hubot + slack on my local machine.
installed hubot and slack client.
running:
bin\hubot -a slack
and got error (after adding log messages to the script)
INFO Connecting...
INFO { ok: false, error: { [Error: socket hang up] code:
'ECONNRESET' } }
from reading code in node_modules\slack-client\src\client.js
found the problem occurs in a POST request:
Client.prototype.login = function() {
this.logger.info('Connecting...');
return this._apiCall('rtm.start', {
agent: 'node-slack'
}, this._onLogin); };
Client.prototype._apiCall = function(method, params, callback) {
var options, post_data, req;
params['token'] = this.token;
post_data = querystring.stringify(params);
options = {
hostname: this.host,
method: 'POST',
path: '/api/' + method,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
req = https.request(options);
tried to do: Node.js POST causes [Error: socket hang up] code: 'ECONNRESET'
with no success

Resources