RSYNCWRAPPER: rsync exited with code 12 - node.js

I'm using rsyncwrapper node module.
Here is my code:
rsync({
src: source_path,
dest: dest,
ssh: true,
recursive: true,
privateKey: keystring,
port: port,
args: ['--perms','--rsync-path="mkdir -p '+dest_path+' && rsync"']
},function (error,stdout,stderr,cmd) {
if ( error ) {
// failed
var data_response = {
'Status': 'Failed',
'Message': 'Rsync Failed=>'+error+stdout+stderr+cmd
};
logger.info("[Rsync] Response=>" + JSON.stringify(data_response));
console.log(error.message);
res.json(data_response);
} else {
console.log("Success");
var data_response = {
'Status': 'Success',
'Message': 'Rsync Success'
};
logger.info("[Rsync] Response=>" + JSON.stringify(data_response));
res.json(data_response);
}
});
However I get this error:
[2018-08-07 13:15:33.491] [INFO] JDWF-API - [Rsync] Response=>{"Status":"Failed","Message":"Rsync Failed=>Error: rsync exited with code 12WARNING : Unauthorized access to this system is forbidden and will be\nprosecuted by law. By accessing this system, you agree that your actions\nmay be monitored if unauthorized usage is suspected.\nmkdir: cannot create directory `/DATA/userWorkpace/devteam/7000003': Permission denied\nrsync: connection unexpectedly closed (0 bytes received so far) [sender]\nrsync error: error in rsync protocol data stream (code 12) at io.c(600) [sender=3.0.6]\nrsync /DATA/files/gs/7000003/input// wf-sync#192.168.1.23:/DATA/userWorkpace/devteam/7000003/input// --rsh \"ssh -p 47365 -i /DATA/jdwf-api/secure/wf-sync.dat\" --recursive --perms --rsync-path=\"mkdir -p /DATA/userWorkpace/devteam/7000003/input// && rsync\""}
rsync exited with code 12
I have given 777 permissions to the folder. It doesnt fix it. Can someone help me out please.

Related

execSync throws and error trying to run node

I am running some processes inside of an EC2 instance.
To run it I initiate it with an SSM command:
cd / && cd home/ec2-user && . .nvm/nvm.sh && cd ufo && npm run start
and inside of it, I have a method in app.ts which is initialized with ts-node app.ts
import { execSync } from 'node:child_process';
import { takeNextScheduledAudit } from './sqs-scheduler';
import { uploadResultsToBucket } from './s3-uploader';
import { AuditRunParams } from "./types";
import { sendAuditResults } from "./sendResults";
(async function conductor(): Promise<void> {
const nextAuditRunParams = await takeNextScheduledAudit();
if (!nextAuditRunParams) {
execSync("sudo shutdown -h now");
}
const { targetUrl, requesterId, endpoint } = nextAuditRunParams as AuditRunParams;
try {
execSync(`npx user-flow --url=${targetUrl} --open=false`);
const resultsUrl = await uploadResultsToBucket(targetUrl);
await sendAuditResults(requesterId, endpoint, resultsUrl);
} catch (error) {
console.log(error);
}
await conductor();
})();
If I log in manually and run npm run start the scripts works as intended but if I run it using the SSM command I get this output:
> start
> ts-node app.ts
Error: Command failed: npx user-flow --url=https://deep-blue.io/ --open=false
at checkExecSyncError (node:child_process:841:11)
at execSync (node:child_process:912:15)
at conductor (/home/ec2-user/ufo/app.ts:15:17)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
status: 243,
signal: null,
output: [ null, <Buffer >, <Buffer 0a> ],
pid: 2691,
stdout: <Buffer >,
stderr: <Buffer 0a>
}
and this error:
Error: Command failed: sudo shutdown -h now
at checkExecSyncError (node:child_process:841:11)
at execSync (node:child_process:912:15)
at conductor (/home/ec2-user/ufo/app.ts:10:17)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async conductor (/home/ec2-user/ufo/app.ts:21:5) {
status: null,
signal: 'SIGTERM',
output: [ null, Buffer(0) [Uint8Array] [], Buffer(0) [Uint8Array] [] ],
pid: 2705,
stdout: Buffer(0) [Uint8Array] [],
stderr: Buffer(0) [Uint8Array] []
}
failed to run commands: exit status 1
Moreover, if I run execSync("node -v && npx -v") it also throws an error.
Why can I run this script when i am logged in but if i run it via a SSM command it does not recognize node inside of node?
--- Edit - Added Info ---
When running execSync(node -v && npx -v,{shell: '/bin/bash'}) I get an error:
Error: Command failed: node -v && npx -v
When running execSync(ps -p $$ && echo $SHELL, {shell: '/bin/bash'}):
PID TTY TIME CMD
7817 ? 00:00:00 bash
/bin/bash
And when I loggin and do ps -p $$ && echo $SHELL I get:
PID TTY TIME CMD
6873 pts/0 00:00:00 bash
/bin/bash
By default, all of the child_process functions execute in the same environment as the process that launched them. I don't have an account handy to test with, but it's quite likely that SSM skips over a traditional shell and just executes certain runtimes directly.
You can use the exec options like this to set a particular shell in which to launch the process:
const output = execSync('echo "doing stuff"', {
shell: '/bin/bash',
})
console.log('***** output:', output.toString())
This is assuming the OS you're using for the EC2 instance has bash available. Most flavors of linux should, but for what you're doing there, /bin/sh is sufficient if not. To get a list of the available shells, you can run:
cat /etc/shells
## or possibly
sudo cat /etc/shells
EDIT: Since you say it works fine in a shell already, you have presumably already handled this, but user-flow would also have to be available. It's not a module from npmjs, so would need to already be present on the box as either a local dependency or a private repo to which the EC2 instance has access.

I am unable to connect Mongodb atlas Cluster from node js getting following unable to connect DB error

{ error: 1, message: 'Command failed: mongodump -h cluster0.yckk6.mongodb.net --port=27017 -d databaseName -p -u --gzip --archive=/tmp/file_name_2022-09-19T09-42-05.gz\n' + '2022-09-19T14:42:08.931+0000\tFailed: error connecting to db server: no reachable servers\n' }
Can anyone help me to solve this problem and following is my backup code
function databaseBackup() {
let backupConfig = {
mongodb: "mongodb+srv://<username>:<password>#cluster0.yckk6.mongodb.net:27017/databaseName?
retryWrites=true&w=majority&authMechanism=SCRAM-SHA-1", // MongoDB Connection URI
s3: {
accessKey: "SDETGGAKIA2GL", //AccessKey
secretKey: "Asad23rdfdg2teE8lOS3JWgdfgfdgfg", //SecretKey
region: "ap-south-1", //S3 Bucket Region
accessPerm: "private", //S3 Bucket Privacy, Since, You'll be storing Database, Private is HIGHLY Recommended
bucketName: "backupDatabase" //Bucket Name
},
keepLocalBackups: false, //If true, It'll create a folder in project root with database's name and store backups in it and if it's false, It'll use temporary directory of OS
noOfLocalBackups: 5, //This will only keep the most recent 5 backups and delete all older backups from local backup directory
timezoneOffset: 300 //Timezone, It is assumed to be in hours if less than 16 and in minutes otherwise
}
MBackup(backupConfig).then(onResolve => {
// When everything was successful
console.log(onResolve);
}).catch(onReject => {
// When Anything goes wrong!
console.log(onReject);
});
}

Execute bat file with electron

Hello I'm creating an app with react and electron and I have a weird bug. My app have to execute a bat file so I use exec to launch the bat file with paramters like this
import { homedir } from 'os';
import * as path from 'path';
import { access, mkdir } from 'fs/promises';
import { promisify } from 'util';
import * as childProcess from 'child_process';
const exec = promisify(childProcess.exec);
const newProject = async (event: any, ...args: string[]): Promise<any> => {
const home = homedir();
const dir = path.join(home, '/work', args[0]);
// create project directory
try {
await access(dir);
return { ok: false, err: 'project already exist' };
} catch (e) {
await mkdir(dir, { recursive: true });
}
const scripts = path.join(__dirname, 'new-project.bat');
// C:\Users\Isai\Documents\work\hercule\apollon\electron\handlers\new-project.bat
try {
await exec(`${scripts} ${dir} ${args[1]}`);
return { ok: true, msg: 'folder successfully created' };
} catch (e) {
console.log(e);
return { ok: true, err: "unable to create project's folder" };
}
};
export default newProject;
when I do like this I get an error who said that it is not an internal or external command but if I mannualy enter the path of the bat file it work. So I replace the line :
await exec(`${scripts} ${dir} ${args[1]}`);
by
await exec(`C:\Users\Isai\Documents\work\hercule\apollon\electron\handlers\new-project.bat ${dir} ${args[1]}`);
It work perfectly. At the beginning I though I had the wrong path but they are the same. So I don't understant why it's doing that and I can't enter manually the path or it won't work on other machine
EDIT: I have forget to tell that a piece of the script is correctly executing because it create the folder at the good place but I get an error
Here is my bat file
#echo off
cd %1
git init
git checkout -b main
echo This project was created with Hercule>> readme.md
git add .
git commit -m "init commit"
git remote add origin %2
git push -u origin main
Here is the error
Error: Command failed: C:\Users\Isai\Documents\work\hercule\apollon\build\electron\handlers\new-project.bat C:\Users\Isai\work\return-of-the-patato https://github.com/Eexy/return-of-the-patato.git
[2] 'C:\Users\Isai\Documents\work\hercule\apollon\build\electron\handlers\new-project.bat' n'est pas reconnu en tant que commande interne
[2] ou externe, un programme ex�cutable ou un fichier de commandes.
[2]
[2] at ChildProcess.exithandler (child_process.js:317:12)
[2] at ChildProcess.emit (events.js:315:20)
[2] at maybeClose (internal/child_process.js:1048:16)
[2] at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5) {
[2] killed: false,
[2] code: 1,
[2] signal: null,
[2] cmd: 'C:\\Users\\Isai\\Documents\\work\\hercule\\apollon\\build\\electron\\handlers\\new-project.bat C:\\Users\\Isai\\work\\return-of-the-patato https://github.com/Eexy/return-of-the-patato.git',
[2] stdout: '',
[2] stderr: "'C:\\Users\\Isai\\Documents\\work\\hercule\\apollon\\build\\electron\\handlers\\new-project.bat' n'est pas reconnu en tant que commande interne\r\n" +
[2] 'ou externe, un programme executable ou un fichier de commandes.\r\n'
[2] }
It is in french but it said that it is not a internal command
I have found the probrem when I compile for electron __dirname is equal to " C:\Users\Isai\Documents\work\hercule\apollon\build\electron\handlers\new-project.bat" and I didn't see the build folder which is explain why I was having a issue

Untaring a file in nodeJS child process throws exception

I have a file bundle.tar.gz which I am trying to untar. The command tar xvfz bundle.tar.gz works on terminal.
However it fails when executed via node child process like so:
child_process.exec(`tar xvfz bundle.tar.gz && bash file.sh`,
{ cwd: path }, (err, stdout, stderr) => {
if (err && err.code !== 0) {
deferred.reject({message: err.message});
} else {
deferred.resolve('COMPLETED');
}
}
);
The error I'm getting:
message"=>"Command failed: /bin/sh -c tar xvfz bundle.tar.gz && bash file.sh ngzip: stdin: unexpected end of file\ntar: Unexpected EOF in archive\ntar: Unexpected EOF in archive\ntar: Error is not recoverable: exiting now\n
I dont have a clue why this is not happening :(

NodeJS dbus not working

I'm trying to get status from omxplayer with NodeJS via DBus, to do that i'm just trying to execuce shell script:
#!/bin/bash
#set -x
OMXPLAYER_DBUS_ADDR="/tmp/omxplayerdbus"
OMXPLAYER_DBUS_PID="/tmp/omxplayerdbus.pid"
export DBUS_SESSION_BUS_ADDRESS=`cat $OMXPLAYER_DBUS_ADDR`
export DBUS_SESSION_BUS_PID=`cat $OMXPLAYER_DBUS_PID`
[ -z "$DBUS_SESSION_BUS_ADDRESS" ] && { echo "Must have DBUS_SESSION_BUS_ADDRESS" >&2; exit 1; }
duration=`dbus-send --print-reply=literal --session --reply-timeout=500 --dest=org.mpris.MediaPlayer2.omxplayer /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Duration`
[ $? -ne 0 ] && exit 1
duration="$(awk '{print $2}' <<< "$duration")"
position=`dbus-send --print-reply=literal --session --reply-timeout=500 --dest=org.mpris.MediaPlayer2.omxplayer /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Position`
[ $? -ne 0 ] && exit 1
position="$(awk '{print $2}' <<< "$position")"
playstatus=`dbus-send --print-reply=literal --session --reply-timeout=500 --dest=org.mpris.MediaPlayer2.omxplayer /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.PlaybackStatus`
[ $? -ne 0 ] && exit 1
playstatus="$(sed 's/^ *//;s/ *$//;' <<< "$playstatus")"
paused="true"
[ "$playstatus" == "Playing" ] && paused="false"
echo "Duration: $duration"
echo "Position: $position"
echo "Paused: $paused"
;;
with
var exec = require('child_process').exec;
exec('bash status.sh', function() {
console.log(arguments);
})
but it prints
{ '0':
{ [Error: Command failed: Failed to open connection to "session" message bus: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.
] killed: false, code: 1, signal: null },
'1': '',
'2': 'Failed to open connection to "session" message bus: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.\n' }
When I execute that script directly in console it works. NodeJS is running on Raspberry Pi.
UPDATE:
I have also tried "node-dbus" and "dbus-native" modules, but none of them worked for me, but maybe I used them incorrectly? To execute
dbus-send --print-reply=literal --session --reply-timeout=500 --dest=org.mpris.MediaPlayer2.omxplayer /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Duration
I used
dbus-native
var exec = require('child_process').exec;
exec('cat /tmp/omxplayerdbus', function(error, data, stderr) {
data = data.replace("\n",'');
var dbus = require('dbus-native');
var bus = dbus.sessionBus({
busAddress: data //unix:abstract=/tmp/dbus-7BuZanKhmv,guid=7fafe7baa2d38357478f04ff5429712a
});
bus.invoke({
path: '/org/mpris/MediaPlayer2',
destination: 'org.mpris.MediaPlayer2.omxplayer',
'interface': 'org.freedesktop.DBus.Properties.Position'
}, function(err, res) {
console.log(arguments);
});
//And this
var conn = dbus({
busAddress: data
});
conn.message({
path:'/org/mpris/MediaPlayer2',
destination: 'org.mpris.MediaPlayer2.omxplayer',
type: dbus.messageType.methodCall
});
conn.on('message', function(msg) { console.log(msg); }).on('error', function() {
console.log(arguments);
}).on('connect', function() {
console.log(arguments);
});
});
both of these methods throws me this error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at errnoException (net.js:904:11)
at Object.afterWrite (net.js:720:19)
UPDATE 2
I'm now using "dbus-native" module and still keep getting "EPIPE" error. I have checked "Handshake.js" and there is everything alright, so I dumped stdin and stdout messages:
{stdin}AUTH EXTERNAL 30
{stdout}OK df028c4a159a4db39ccc41c0542b9e3b
{stdin}BEGIN
{stdin}lmo/org/freedesktop/DBussorg.freedesktop.DBussHellosorg.freedesktop.DBus
PuTTY{stdin}l5�o/org/mpris/MediaPlayer2sorg.freedesktop.DBus.PropertiessGets org.mpris.MediaPlayer2.omxplayegss org.mpris.MediaPlayer2.omxplayePosition
{stdout} - stdout message line
{stdin} - stdin message line
and then "EPIPE".
UPDATE 3
I have found out that "EPIPE" error is throwed right after first dbus "DATA" command, in this case it's
lmo/org/freedesktop/DBussorg.freedesktop.DBussHellosorg.freedesktop.DBus
PuTTY{stdin}l5�o/org/mpris/MediaPlayer2sorg.freedesktop.DBus.PropertiessGets org.mpris.MediaPlayer2.omxplayegss org.mpris.MediaPlayer2.omxplayePosition
i'm new in communications via dbus, but according to DBus protocol, messages should be sent DATA <data in hex encoding>, but dbus-native sends messages without DATA command name.
You are trying to read dbus object propery using properties api. Note that last parameter of dbus-send is interface.member, so the message you are sending would be
var bus = dbus.sessionBus({ busAddress: fs.readFileSync('/tmp/omxplayerdbus', 'ascii').trim()})
bus.invoke({
path: "/org/mpris/MediaPlayer2",
interface: "org.freedesktop.DBus.Properties",
member: "Get",
destination: "org.mpris.MediaPlayer2.omxplayer",
signature: "ss",
body: [
"org.mpris.MediaPlayer2.omxplayer",
"Position"
]
}, function(err, position) {
console.log(err, position);
});

Resources