How to solve the rippled NotConnectedError? - blockchain

I installed rippled and started the service by using sudo systemctl start rippled.
When checking the status of rippled, it is working.
But I can't connect to the server in node.js.
I tried like below.
var RippleAPI = require('ripple-lib').RippleAPI;
var rippleAPI= new RippleAPI({
server: 'wss://localhost:5005'
});
rippleAPI.on('error', (errorCode, errorMessage) => {
console.log(errorCode + ': ' + errorMessage);
});
rippleAPI.on('connected', () => {
console.log('connected');
});
rippleAPI.on('disconnected', (code) => {
// code - [close code](https://developer.mozilla.org/en-
US/docs/Web/API/CloseEvent) sent by the server
// will be 1000 if this was normal closure
console.log('disconnected, code:', code);
});
rippleAPI.connect().then(() => {
}).then(() => {
return rippleAPI.disconnect();
}).catch(console.error);
When I start the node, it says NotConnectedError(socket hang up).
How can I connect?

Check if you've enabled wss in your rippled.cfg. It is commented out by default.
Otherwise rippled sometimes looks like it's running even when the server_state indicates full. And when you try ledger current it returns "error_code":17 InsufficientNetworkMode. In this case all you can do is wait.
Maybe your server doesn't have the enough resources. Check out their documentation. They've recently updated it and it's even more easier to setup a rippled server now.

Related

How to use expire_time parameter with the Node.js node-oracledb?

Sample Code
try {
const oracledb = require('oracledb');
const express = require('express');
const app = express();
// Memorized Connections
var allDBSessions = {};
app.get('/', (req, res) => {
const dbConfig = {
user: 'vph_dev_ad_gss_tran',
password: 'Gsstpl100'
// ,connectString: '//IP:PORT/SERVICE_NAME' // Working as Expected
,connectString: '//IP:PORT/SERVICE_NAME?expire_time=1' // Minutes // Not Working
// ,connectString: '//IP:PORT/SERVICE_NAME?connect_timeout=15' // Seconds // Not Working
// Your connection string could be "mydbmachine.example.com/orclpdb1?expire_time=2" // Sample From Node Oracledb Site
};
async function ExecuteQuery() {
try {
// Getting DB Connections
let dbInstance;
if (allDBSessions.first_instance) {
// Assigning From Memorized Connections
console.log('Connection Available From the Memory');
console.log('Connection Created Time - ' + allDBSessions.first_instance.created_time);
dbInstance = allDBSessions.first_instance.db_connection;
console.log('Connection Assigned From Memory');
} else {
//Creating New DB Instance
console.log('Creating New Connection');
dbInstance = await oracledb.getConnection(dbConfig);
console.log('Connection Created Successfully');
// Memorizing the DB Instance
allDBSessions.first_instance = {
db_connection: dbInstance,
created_time: new Date().toLocaleString()
}
console.log('Connection Stored into Memory');
}
// Executing Query
var query = 'select 1 from dual';
console.log('Executing the Query - ' + query);
let queryResult = await dbInstance.execute(query);
console.log('queryResult', queryResult);
var finalResult = {
'Query Result': queryResult,
'Usedd DB Session Info': allDBSessions.first_instance
};
res.send(finalResult); // Sending Response
} catch (error) {
console.log(error, '----- Catch Error in ExecuteQuery()-----');
res.send(error);
}
}
ExecuteQuery();
})
app.listen(3005, () => {
console.log(`Oracle DB Sample With Expire Timeout`);
console.log(`server is listening on PORT 3005`);
})
} catch (error) {
console.log(error, '----- Catch Error -----');
}
Above Sample Throwing Error while trying to make a successful Connection with the Oracle Db which is 19c.
Error Shown below
[Error: ORA-12514: TNS:listener does not currently know of service requested in connect descriptor] {
errorNum: 12514,
offset: 0
}
Please guide me to overcome from this issue...
Thanks In AdvancE...
HaPPy CodinG...
The Easy Connect Plus syntax like '//IP:PORT/SERVICE_NAME?expire_time=1' is usable when the Oracle Client libraries that node-oracledb uses are 19c or later. The database version doesn't matter. See the architecture diagram in the documentation.
Check what client libraries node-oracledb is using by running the example app version.js. It will output something like:
$ node version.js
Run at: Thu Mar 18 2021 08:17:22 GMT+1100 (Australian Eastern Daylight Time)
Node.js version: v12.21.0 (darwin x64)
Node-oracledb version: 5.2.0-dev
Oracle Client library version: 19.8.0.0.0
Oracle Database version: 19.3.0.0.0
Check your Oracle Client library version is 19 or later.
Update on EXPIRE_TIME:
With 18c client libraries it can be added as (EXPIRE_TIME=n) to the DESCRIPTION section of a connect descriptor (in a full connect descriptor string in the app, or in the tnsnames.ora file).
With 19c client libraries it can be used via Easy Connect: host/service?expire_time=n.
With 21c client libraries it can be used in a client-side (i.e. Node.js machine) sqlnet.ora.

Azure Webjob, KeyVault Configuration extension, Socket Error

Need some help to determine if this is a bug in my code or in the config kevault extensions.
I have a netcore console based webjob. all working fine until a few weeks ago when we stated getting occasional startup errors which were Socket Error 10060 - Socket timed out or "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond"
These were all related to loading configuration layers (app settings, env, command line and keyvault). The errors stemmed from the keyvault once the build was executed on the hostbuilder.
I initially added the retry policy with the default HttpStatusCodeErrorDetectionStrategy and an exponential back-off but this is not executing.
finally I added my own retry policy with my own detection strategy (see below). Still not being fired.
I have stripped down the code to a hello world like example and included the messages from the webjob.
Here is the code summary:
Main
public static async Task<int> Main(string[] args)
{
var host = CreateHostBuilder(args)
.UseConsoleLifetime()
.Build();
using var serviceScope = host.Services.CreateScope();
var services = serviceScope.ServiceProvider;
//**stripped down to logging just for debug
var loggerFactory = host.Services.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger("Main");
logger.LogDebug("Hello Test App Started OK. Exiting.");
//**Normally lots of service calls go here to do real work**
return 0;
}
HostBuilder - why hostbuilder? We use lots of components that are built for webapi and webapps so it was convenient to use a similar services model.
public static IHostBuilder CreateHostBuilder(string[] args)
{
var host = Host
.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((ctx, config) =>
{
//override with keyvault
var azureServiceTokenProvider = new AzureServiceTokenProvider(); //this is awesome - it will use MSI or Visual Studio connection
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var retryPolicy = new RetryPolicy<ServerErrorDetectionStrategy>(
new ExponentialBackoffRetryStrategy(
retryCount: 5,
minBackoff: TimeSpan.FromSeconds(1.0),
maxBackoff: TimeSpan.FromSeconds(16.0),
deltaBackoff: TimeSpan.FromSeconds(2.0)
)
);
retryPolicy.Retrying += RetryPolicy_Retrying;
keyVaultClient.SetRetryPolicy(retryPolicy);
var prebuiltConfig = config.Build();
config.AddAzureKeyVault(prebuiltConfig.GetSection("KeyVaultSettings").GetValue<string>("KeyVaultUri"), keyVaultClient, new DefaultKeyVaultSecretManager());
config.AddCommandLine(args);
})
.ConfigureLogging((ctx, loggingBuilder) => //note - this is run AFTER app configuration - whatever the order it is in.
{
loggingBuilder.ClearProviders();
loggingBuilder
.AddConsole()
.AddDebug()
.AddApplicationInsightsWebJobs(config => config.InstrumentationKey = ctx.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"]);
})
.ConfigureServices((ctx, services) =>
{
services
.AddApplicationInsightsTelemetry();
services
.AddOptions();
});
return host;
}
Event - this is never fired.
private static void RetryPolicy_Retrying(object sender, RetryingEventArgs e)
{
Console.WriteLine($"Retrying, count = {e.CurrentRetryCount}, Last Exception={e.LastException}, Delay={e.Delay}");
}
Retry Policy - only fires for the non-MSI attempt to contact the keyvault.
public class ServerErrorDetectionStrategy : ITransientErrorDetectionStrategy
{
public bool IsTransient(Exception ex)
{
if (ex != null)
{
Console.WriteLine($"Exception {ex.Message} received, {ex.GetType()?.FullName}");
HttpRequestWithStatusException httpException;
if ((httpException = ex as HttpRequestWithStatusException) != null)
{
switch(httpException.StatusCode)
{
case HttpStatusCode.RequestTimeout:
case HttpStatusCode.GatewayTimeout:
case HttpStatusCode.InternalServerError:
case HttpStatusCode.ServiceUnavailable:
return true;
}
}
SocketException socketException;
if((socketException = (ex as SocketException)) != null)
{
Console.WriteLine($"Exception {socketException.Message} received, Error Code: {socketException.ErrorCode}, SocketErrorCode: {socketException.SocketErrorCode}");
if (socketException.SocketErrorCode == SocketError.TimedOut)
{
return true;
}
}
}
return false;
}
}
WebJob Output
[SYS INFO] Status changed to Initializing
[SYS INFO] Run script 'run.cmd' with script host - 'WindowsScriptHost'
[SYS INFO] Status changed to Running
[INFO]
[INFO] D:\local\Temp\jobs\triggered\HelloWebJob\42wj5ipx.ukj>dotnet HelloWebJob.dll
[INFO] Exception Response status code indicates server error: 401 (Unauthorized). received, Microsoft.Rest.TransientFaultHandling.HttpRequestWithStatusException
[INFO] Exception A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. received, System.Net.Http.HttpRequestException
[ERR ] Unhandled exception. System.Net.Http.HttpRequestException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
[ERR ] ---> System.Net.Sockets.SocketException (10060): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
[ERR ] at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
[ERR ] --- End of inner exception stack trace ---
[ERR ] at Microsoft.Rest.RetryDelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
[ERR ] at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
[ERR ] at Microsoft.Azure.KeyVault.KeyVaultClient.GetSecretWithHttpMessagesAsync(String vaultBaseUrl, String secretName, String secretVersion, Dictionary`2 customHeaders, CancellationToken cancellationToken)
[ERR ] at Microsoft.Azure.KeyVault.KeyVaultClientExtensions.GetSecretAsync(IKeyVaultClient operations, String secretIdentifier, CancellationToken cancellationToken)
[ERR ] at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.LoadAsync()
[ERR ] at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.Load()
[ERR ] at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
[ERR ] at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
[ERR ] at Microsoft.Extensions.Hosting.HostBuilder.BuildAppConfiguration()
[ERR ] at Microsoft.Extensions.Hosting.HostBuilder.Build()
[ERR ] at HelloWebJob.Program.Main(String[] args) in C:\Users\mark\Source\Repos\HelloWebJob\HelloWebJob\Program.cs:line 21
[ERR ] at HelloWebJob.Program.<Main>(String[] args)
[SYS INFO] Status changed to Failed
[SYS ERR ] Job failed due to exit code -532462766
This is an issue in the KV connectivity which is identified by the PG. Below is an official statement from Product Group:
The Microsoft Azure App Service Team has identified an issue with the
Key Vault references for App Service and Azure Functions feature
related to intermittent failure to resolve references at runtime.
Engineers identified a regression in the system that reduced the
performance and availability of our scale unit’s ability to retrieve
key vault references at runtime. A patch has been written and deployed
to our fleet of VMs to mitigate this issue.
We are continuously taking steps to improve the Azure Web App service
and our processes to ensure such incidents do not occur in the future,
and in this case, it includes (but is not limited to): Improving
detection and testing of performance and availability of the Key Vault
App Setting References feature Improvements to our platform to ensure
high availability of this feature at runtime. We apologize for any
inconvenience.
For almost everyone, updating packages to the new Microsoft.Azure packages has mitigated this issue, so trying those would be my first suggestion.
Thanks #HarshitaSingh-MSFT, makes sense though I searched for this when I had the problem and couldn't find it.
As a work around, I added some basic retry code to the startup.
Main looks like this for now:
public static async Task<int> Main(string[] args)
{
IHost host = null;
int retries = 5;
while (true)
{
try
{
Console.WriteLine("Building Host...");
var hostBuilder = CreateHostBuilder(args)
.UseConsoleLifetime();
host = hostBuilder.Build();
break;
}
catch (HttpRequestException hEx)
{
Console.WriteLine($"HTTP Exception in host builder. {hEx.Message}, Name:{hEx.GetType().Name}");
SocketException se;
if ((se = hEx.InnerException as SocketException) != null)
{
if (se.SocketErrorCode == SocketError.TimedOut)
{
Console.WriteLine($"Socket error in host builder. Retrying...");
if (retries > 0)
{
retries--;
await Task.Delay(5000);
host?.Dispose();
}
else
{
throw;
}
}
else
{
throw;
}
}
}
}
using var serviceScope = host.Services.CreateScope();
var services = serviceScope.ServiceProvider;
var transferService = services.GetRequiredService<IRunPinTransfer>();
var result = await transferService.ProcessAsync();
return result;
}

server responded with a status of 404 (Not Found): mean stack & ionic

I making a request to the back-end server of the port number 8000. I'm making request from the android emulator. so, instead of localhost i'm using ip address. It is throwing the error as
Failed to load resource: the
http://192.168.0.102:8000/api/facebookuser server responded with a
status of 404 (Not Found)
This is my code
postFacebookData(userdata) {
alert(userdata);
let headers = new HttpHeaders();
headers.append('Content-Type','application/json');
return this.http.post('http://192.168.0.102:8000/api/facebookuser',userdata,{headers: headers})
}
This is from routes file
router.post('/facebookuser', function(req,res) {
console.log('facebook request');
It is not subscribing to the method
this.fbPage.postFacebookData(userData)
.subscribe((data: any) => {
if (data.success) {
alert('Data added sucessfully ' && data.msg);
this.authservices.storeUserData(data.token,data.user);
this.navCtrl.push(EditinfoPage);
}
else {
alert('data is not added');
}
},(err) => {
alert('error in subscribing ' + err);
I'm getting an error message in the cosole from the above code as
error in subscribing [object object]
The error is indicating, that the request cannot find the resource you are trying to request.
Make sure that the IP-Adress for your backend is correct (using ipconfig for instance)
Make sure that the endpoint "api/facebookuser" is correct
Make sure that the EMULATOR is in the same network (e.g. WLAN) than your computer (assuming that the backend is running on localhost)

How to stop Ember CLI's http-mock server throwing an error when there are websockets in one of the server files?

I have a websocket in one of my http-mock server files initialised as follows:
var WebSocketServer = require('ws').Server;
var socketServer = new WebSocketServer({port: 13434, path: "/update"});
and later in the file I have the following happen on connection:
socketServer.on('connection', function(ws) {
ws.on('close', function(message) {
clearInterval(sendResults);
});
ws.on('message', function(message) {
handleClientMessage(ws, message);
});
sendResults = setInterval(function() {
ws.send(JSON.stringify(getResultsFromEntries()));
}, resultInterval);
});
However, whenever I edit any of the server files I get the following error:
File changed: "mocks/entry.js"
Just getting started with Ember? Please visit http://localhost:4200/ember-getting-started to get going
events.js:141
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE 0.0.0.0:13434
at Object.exports._errnoException (util.js:907:11)
at exports._exceptionWithHostPort (util.js:930:20)
at Server._listen2 (net.js:1250:14)
at listen (net.js:1286:10)
at net.js:1395:9
at nextTickCallbackWith3Args (node.js:453:9)
at process._tickCallback (node.js:359:17)
I'm guessing I need to detect when the file change happens and close the current websocket connection. On process exit doesn't seem to get called until the server dies, and then process.on('exit', function() {}) is called the number of times the server has refreshed. It doesn't bother me too much as I have a script that restarts ember server if it goes down, but other developers don't like the ember server going down when they edit a server file. Any ideas?
I ended up setting a new WebSocketServer as a property of process (which persists over the server getting restarted) then at the top of the file I close the previous WebSocketServer (if there was one):
if (process["updateSocketServer"]) {
process["updateSocketServer"].close();
process["updateSocketServer"] = undefined;
}
Then setup a new WebSocketServer:
process["updateSocketServer"] = new WebSocketServer({port: 13434, path: "/update"});
Then I did the following on connection:
process["updateSocketServer"].on('connection', function(ws) {
// Connection code.
});
Should you be closing/terminating the connection on close?

asp.net core session not working , set cookie in response header but not set in browser

I am using sessions to manage application state in ASP.NET CORE and it's configured as below.
services.AddSession(options =>
{
options.CookieName = ".my.Session";
options.IdleTimeout = TimeSpan.FromSeconds(20);
});
It's working on localhost but on remote IIS 8 it's not creating cookies so not able to get the values. I also have enabled CORS and don't know what exactly caused this problem. In log it's not showing error either.
In response header set cookie is present but not set in browser
I had this problem some time ago. It may be related with the new Cookie Policy.
Try to set options.CheckConsentNeeded = context => false;. So inside "ConfigureServices" in Startup.cs it need to be like this:
public void ConfigureServices(IServiceCollection services)
{
var connection = Configuration["ConnectionStrings:DefaultConnection"];
services.AddDbContext<ProjectDbContext>(options => options.UseMySql(connection, b => b.MigrationsAssembly("PrimaryProject")));
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
//Here comes the change:
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(connection));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddSessionStateTempDataProvider();
services.AddSession();
}
Regards,
H. Eberhardt
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.CookieHttpOnly = true;
});
May be it's working, Try it now