@milaboratories/pl-deployments 1.4.1 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ wd: ${r.opts.cwd}`),o.info(" spawning child process"),ot.spawn(r.cmd,r.args,r.o
|
|
|
4
4
|
URL: ${r}
|
|
5
5
|
Save to: ${e}`);const{body:i,statusCode:n}=await st.request(r);if(t.statusCode=n,n!=200){const s=await at.text(i);throw t.errorMsg=`failed to download archive: ${n}, response: ${s.slice(0,1e3)}`,o.error(t.errorMsg),new Error(t.errorMsg)}return t.tmpPath=e+".tmp",await U.Readable.toWeb(i).pipeTo(U.Writable.toWeb(D.createWriteStream(t.tmpPath))),t.wroteTmp=!0,t.tmpExisted=await w.fileExists(t.tmpPath),await m.rename(t.tmpPath,e),t.renamed=!0,t.newExisted=await w.fileExists(e),t}catch(i){const n=`downloadArchive: ${JSON.stringify(i)}, state: ${JSON.stringify(t)}`;throw o.error(n),new Error(n)}}const $t=".ok";async function Pt(o,r,e,t){if(o.info("extracting archive..."),o.info(` archive path: '${r}'`),o.info(` target dir: '${t}'`),!await w.fileExists(r)){const n=`Platforma Backend binary archive not found at '${r}'`;throw o.error(n),new Error(n)}const i=h.join(t,$t);if(await w.fileExists(i)){o.info(`Platforma Backend binaries unpack skipped: '${t}' exists`);return}switch(await w.fileExists(t)&&(o.info(`Removing previous incompletely unpacked folder: '${t}'`),await m.rm(t,{recursive:!0})),o.info(` creating target dir '${t}'`),await m.mkdir(t,{recursive:!0}),o.info(`Unpacking Platforma Backend archive:
|
|
6
6
|
Archive: ${r}
|
|
7
|
-
Target dir: ${t}`),e){case"tgz":await ht.x({file:r,cwd:t,gzip:!0});break;case"zip":await lt(r,t);break;default:w.assertNever(e)}await m.writeFile(i,"ok"),o.info(" ... unpack done.")}const St={linux:"tgz",macos:"tgz",windows:"zip"};function E(){return"1.
|
|
7
|
+
Target dir: ${t}`),e){case"tgz":await ht.x({file:r,cwd:t,gzip:!0});break;case"zip":await lt(r,t);break;default:w.assertNever(e)}await m.writeFile(i,"ok"),o.info(" ... unpack done.")}const St={linux:"tgz",macos:"tgz",windows:"zip"};function E(){return"1.26.0"}function Ct(){return{type:"Download",version:E()}}async function Et(o,r,e){switch(e.type){case"Download":const t=await vt(o,r,"pl",`pl-${e.version}`,F.arch(),F.platform());return h.join(t.baseName,"binaries",bt[k(F.platform())]);case"Local":return e.path;default:w.assertNever(e)}}const bt={linux:"platforma",macos:"platforma",windows:"platforma.exe"};function z(o){return h.join(o,"pl_pid")}async function At(o){if(!await w.fileExists(o))return;const r=await m.readFile(o);return Number(r.toString())}async function Ft(o,r){await m.writeFile(o,JSON.stringify(r))}function Dt(){return{}}function xt(o,r,e){return o[r]=e,e}async function R(o,r){const e=Dt();try{return await r((i,n)=>xt(e,i,n),e)}catch(t){throw o.error(`error ${t} while doing traced operation, state: ${JSON.stringify(e)}`),t}}const J="config-local.yaml";class L{constructor(r,e,t,i,n,s,a,c){f(this,"instance");f(this,"pid");f(this,"nRuns",0);f(this,"lastRunHistory",{});f(this,"wasStopped",!1);this.logger=r,this.workingDir=e,this.startOptions=t,this.initialStartHistory=i,this.onClose=n,this.onError=s,this.onCloseAndError=a,this.onCloseAndErrorNoStop=c}async start(){await R(this.logger,async(r,e)=>{this.wasStopped=!1;const t=wt(this.logger,this.startOptions);t.on("error",n=>{this.logger.error(`error '${n}', while running platforma, started opts: ${JSON.stringify(this.debugInfo())}`),this.onError!==void 0&&this.onError(this),this.onCloseAndError!==void 0&&this.onCloseAndError(this),this.onCloseAndErrorNoStop!==void 0&&!this.wasStopped&&this.onCloseAndErrorNoStop(this)}),t.on("close",()=>{this.logger.warn(`platforma was closed, started opts: ${JSON.stringify(this.debugInfo())}`),this.onClose!==void 0&&this.onClose(this),this.onCloseAndError!==void 0&&this.onCloseAndError(this),this.onCloseAndErrorNoStop!==void 0&&!this.wasStopped&&this.onCloseAndErrorNoStop(this)}),r("started",!0);const i=r("pidFile",z(this.workingDir));r("pid",w.notEmpty(t.pid)),r("pidWritten",await Ft(i,w.notEmpty(t.pid))),this.nRuns++,this.instance=t,this.pid=t.pid,this.lastRunHistory=e})}stop(){this.wasStopped=!0,H(w.notEmpty(this.pid))}async waitStopped(){await G(w.notEmpty(this.pid),15e3)}stopped(){return this.wasStopped}async isAlive(){return await O(w.notEmpty(this.pid))}debugInfo(){return{lastRunHistory:this.lastRunHistory,nRuns:this.nRuns,pid:this.pid,workingDir:this.workingDir,initialStartHistory:this.initialStartHistory,wasStopped:this.wasStopped}}}async function Ot(o,r){const e={plBinary:Ct(),spawnOptions:{},closeOld:!0,...r};return await R(o,async(t,i)=>{t("startOptions",{...e,config:"too wordy"});const n=h.resolve(e.workingDir);e.closeOld&&t("closeOld",await kt(o,n));const s=h.join(n,J);o.info(`writing configuration '${s}'...`),await m.writeFile(s,e.config);const a=h.join(n,"binaries"),c=await Et(o,a,e.plBinary),u={cmd:t("binaryPath",h.join("binaries",c)),args:["--config",s],opts:{env:{...process.env},cwd:n,stdio:["pipe","ignore","inherit"],windowsHide:!0,...e.spawnOptions}};t("processOpts",{cmd:u.cmd,args:u.args,cwd:u.opts.cwd});const d=new L(o,e.workingDir,u,i,e.onClose,e.onError,e.onCloseAndError,e.onCloseAndErrorNoStop);return await d.start(),d})}async function kt(o,r){return await R(o,async(e,t)=>{const i=e("pidFilePath",z(r)),n=e("pid",await At(i)),s=e("wasAlive",await O(n));return n!==void 0&&s&&(e("stopped",H(n)),e("waitStopped",await G(n,1e4))),t})}const Rt={keepaliveInterval:6e4,keepaliveCountMax:10};class b{constructor(r,e){f(this,"config");f(this,"homeDir");f(this,"forwardedServers",[]);this.logger=r,this.client=e}static async init(r,e){const t={...Rt,...e},i=new b(r,new S.Client);return await i.connect(t),i}getForwardedServers(){return this.forwardedServers}getFullHostName(){var r,e;return`${(r=this.config)==null?void 0:r.host}:${(e=this.config)==null?void 0:e.port}`}getUserName(){var r;return(r=this.config)==null?void 0:r.username}async connect(r){return this.config=r,await Nt(this.client,r)}async exec(r){return new Promise((e,t)=>{this.client.exec(r,(i,n)=>{if(i)return t(`ssh.exec: ${r}: ${i}`);let s="",a="";n.on("close",c=>{c===0?e({stdout:s,stderr:a}):t(new Error(`Command ${r} exited with code ${c}, stdout: ${s}, stderr: ${a}`))}).on("data",c=>{s+=c.toString()}).stderr.on("data",c=>{a+=c.toString()})})})}static async getAuthTypes(r,e){return new Promise(t=>{let i="";const n=new S.Client;n.on("ready",()=>{n.end();const s=this.extractAuthMethods(i);t(s.length===0?["publickey","password"]:s)}),n.on("error",()=>{n.end(),t(["publickey","password"])}),n.connect({host:r,port:e,username:new Date().getTime().toString(),debug:s=>{i+=`${s}
|
|
8
8
|
`}})})}static extractAuthMethods(r){const e=r.match(/Inbound: Received USERAUTH_FAILURE \((.+)\)/);return e&&e[1]?e[1].split(",").map(t=>t.trim()):[]}async forwardPort(r,e){const t=`ssh.forward:${r.localPort}:${r.remotePort}.id_${x.randomBytes(1).toString("hex")}`;e=e??this.config;const i=new w.RetryablePromise(n=>new Promise((s,a)=>{const c=new S.Client;c.on("ready",()=>{this.logger.info(`${t}.client.ready`),s(c)}),c.on("error",l=>{this.logger.info(`${t}.client.error: ${l}`),n.reset(),a(l)}),c.on("close",()=>{this.logger.info(`${t}.client.closed`),n.reset()}),c.connect(e)}));return await i.ensure(),new Promise((n,s)=>{const a=q.createServer({pauseOnConnect:!0},async c=>{const l=`${t}.sock_${x.randomBytes(1).toString("hex")}`;let u;try{u=await i.ensure()}catch(g){this.logger.info(`${l}.persistentClient.catch: ${g}`),c.end();return}u.setNoDelay(!0),c.setNoDelay(!0);let d;try{d=await Bt(this.logger,u,"127.0.0.1",0,"127.0.0.1",r.remotePort)}catch(g){this.logger.error(`${l}.forwardOut.err: ${g}`),c.end();return}c.pipe(d),d.pipe(c),c.resume(),d.on("error",g=>{this.logger.error(`${l}.stream.error: ${g}`),c.end(),d.end()}),d.on("close",()=>{c.end(),d.end()}),c.on("close",()=>{this.logger.info(`${l}.localSocket: closed`),c.end(),d.end()})});a.listen(r.localPort,"127.0.0.1",()=>{this.logger.info(`${t}.server: started listening`),this.forwardedServers.push(a),n({server:a})}),a.on("error",c=>{a.close(),s(new Error(`${t}.server: error: ${JSON.stringify(c)}`))}),a.on("close",()=>{this.logger.info(`${t}.server: closed ${JSON.stringify(r)}`),this.forwardedServers=this.forwardedServers.filter(c=>c!==a)})})}closeForwardedPorts(){this.logger.info("[SSH] Closing all forwarded ports..."),this.forwardedServers.forEach(r=>{const e=r.address();if(e&&typeof e!="string"){const t=e;this.logger.info(`[SSH] Closing port forward for server ${t.address}:${t.port}`)}r.close()}),this.forwardedServers=[]}static async checkHostAvailability(r){return new Promise(e=>{ut.lookup(r,t=>{e(!t)})})}static async isPassphraseRequiredForKey(r){return new Promise((e,t)=>{try{return S.utils.parseKey(r)instanceof Error&&e(!0),e(!1)}catch(i){console.log("Error parsing privateKey"),t(new Error(`ssh.isPassphraseRequiredForKey: err ${i}`))}})}async uploadFile(r,e){return await this.withSftp(async t=>new Promise((i,n)=>{t.fastPut(r,e,s=>{if(s){const a=new Error(`ssh.uploadFile: err: ${s}, localPath: ${r}, remotePath: ${e}`);return n(a)}i(!0)})}))}async withSftp(r){return new Promise((e,t)=>{this.client.sftp((i,n)=>{if(i)return t(new Error(`ssh.withSftp: sftp err: ${i}`));r(n).then(e).catch(s=>{t(new Error(`ssh.withSftp.callback: err ${s}`))}).finally(()=>{n==null||n.end()})})})}async writeFileOnTheServer(r,e,t=432){return this.withSftp(async i=>this.writeFile(i,r,e,t))}async getForderStructure(r,e,t={files:[],directories:[]}){return new Promise((i,n)=>{r.readdir(e,async(s,a)=>{if(s)return n(s);for(const c of a){const l=`${e}/${c.filename}`;if(c.attrs.isDirectory()){t.directories.push(l);try{await this.getForderStructure(r,l,t)}catch(u){return n(u)}}else t.files.push(l)}i(t)})})}rmdir(r,e){return new Promise((t,i)=>{r.rmdir(e,n=>n?i(n):t(!0))})}unlink(r,e){return new Promise((t,i)=>{r.unlink(e,n=>n?i(n):t(!0))})}async deleteFolder(r){return this.withSftp(async e=>{try{const t=await this.getForderStructure(e,r);this.logger.info("ssh.deleteFolder list of files and directories"),this.logger.info(`ssh.deleteFolder list of files: ${t.files}`),this.logger.info(`ssh.deleteFolder list of directories: ${t.directories}`);for(const i of t.files)this.logger.info(`ssh.deleteFolder unlink file ${i}`),await this.unlink(e,i);t.directories.sort((i,n)=>n.length-i.length);for(const i of t.directories)this.logger.info(`ssh.deleteFolder rmdir ${i}`),await this.rmdir(e,i);return await this.rmdir(e,r),!0}catch(t){this.logger.error(t);const i=t instanceof Error?t.message:"";throw new Error(`ssh.deleteFolder: path: ${r}, message: ${i}`)}})}async readFile(r){return this.withSftp(async e=>new Promise((t,i)=>{e.readFile(r,(n,s)=>{if(n)return i(new Error(`ssh.readFile: ${n}`));t(s.toString())})}))}async chmod(r,e){return this.withSftp(async t=>new Promise((i,n)=>{t.chmod(r,e,s=>s?n(new Error(`ssh.chmod: ${s}, path: ${r}, mode: ${e}`)):i(void 0))}))}async checkFileExists(r){return this.withSftp(async e=>new Promise((t,i)=>{e.stat(r,(n,s)=>{if(n)return(n==null?void 0:n.code)===2?t(!1):i(new Error(`ssh.checkFileExists: err ${n}`));t(s.isFile())})}))}async checkPathExists(r){return this.withSftp(async e=>new Promise((t,i)=>{e.stat(r,(n,s)=>{if(n)return n.code===2?t({exists:!1,isFile:!1,isDirectory:!1}):i(new Error(`ssh.checkPathExists: ${n}`));t({exists:!0,isFile:s.isFile(),isDirectory:s.isDirectory()})})}))}async writeFile(r,e,t,i=432){return new Promise((n,s)=>{r.writeFile(e,t,{mode:i},a=>{if(a)return s(new Error(`ssh.writeFile: err ${a}, remotePath: ${e}`));n(!0)})})}uploadFileUsingExistingSftp(r,e,t,i=432){return new Promise((n,s)=>{m.readFile(e).then(async a=>{this.writeFile(r,t,a,i).then(()=>{n(void 0)}).catch(c=>{const l=`uploadFileUsingExistingSftp: ${c}`;this.logger.error(l),s(new Error(l))})})})}async __uploadDirectory(r,e,t,i=432){return new Promise((n,s)=>{D.readdir(e,async(a,c)=>{if(a)return s(new Error(`ssh.__uploadDir: err ${a}, localDir: ${e}, remoteDir: ${t}`));try{await this.__createRemoteDirectory(r,t);for(const l of c){const u=h.join(e,l),d=`${t}/${l}`;D.lstatSync(u).isDirectory()?await this.__uploadDirectory(r,u,d,i):await this.uploadFileUsingExistingSftp(r,u,d,i)}n()}catch(l){const u=`ssh.__uploadDir: catched err ${l}`;this.logger.error(u),s(new Error(u))}})})}async uploadDirectory(r,e,t=432){return new Promise((i,n)=>{this.withSftp(async s=>{try{await this.__uploadDirectory(s,r,e,t),i()}catch(a){n(new Error(`ssh.uploadDirectory: ${a}`))}})})}__createRemoteDirectory(r,e){return new Promise((t,i)=>{const n=e.split("/");let s="";const a=c=>{if(c>=n.length)return t();s+=`${n[c]}/`,r.stat(s,l=>{l?r.mkdir(s,u=>{if(u)return i(new Error(`ssh.__createRemDir: err ${u}, remotePath: ${e}`));a(c+1)}):a(c+1)})};a(0)})}ensureRemoteDirCreated(r,e=493){return this.withSftp(async t=>{const i=r.split("/");let n="";for(const s of i){n+=`${s}/`;try{await new Promise((a,c)=>{t.stat(n,l=>{if(!l)return a();t.mkdir(n,{mode:e},u=>{if(u)return c(new Error(`ssh.createRemoteDir: err ${u}, remotePath: ${r}`));a()})})})}catch(a){throw console.error(`Failed to create directory: ${n}`,a),a}}})}async downloadFile(r,e){return this.withSftp(async t=>new Promise((i,n)=>{t.fastGet(r,e,s=>{if(s)return n(new Error(`ssh.downloadFile: err ${s}, remotePath: ${r}, localPath: ${e}`));i(!0)})}))}close(){this.closeForwardedPorts(),this.client.end()}}async function Nt(o,r,e,t){return new Promise((i,n)=>{o.on("ready",()=>{i(o)}),o.on("error",s=>{n(new Error(`ssh.connect: ${s}`))}),o.on("close",()=>{}),o.connect(r),o.setNoDelay(!0)})}async function Bt(o,r,e,t,i,n){return new Promise((s,a)=>{r.forwardOut(e,t,i,n,(c,l)=>c?(o.error(`forwardOut.error: ${c}`),a(c)):s(l))})}const Ut="minio-2024-12-18T13-15-44Z",_t="supervisord-0.7.3",It="supervisord_0.7.3_Linux_64-bit";function y(o){return h.join(o,".platforma_ssh")}function A(o){return h.join(y(o),"binaries")}function Tt(o,r){return h.join(A(o),`pl-${E()}-${P(r)}`)}function V(o,r){return h.join(Tt(o,r),"binaries")}function _(o,r){return h.join(V(o,r),"platforma")}function jt(o,r){return h.join(V(o,r),"free-port")}function W(o,r){return h.join(A(o),`minio-2024-12-18T13-15-44Z-${P(r)}`)}function qt(o,r){return h.join(W(o,r),"minio")}function Ht(o,r){return h.join(A(o),`supervisord-0.7.3-${P(r)}`,It)}function K(o,r){return h.join(Ht(o,r),"supervisord")}function Y(o){return h.join(y(o),"supervisor.conf")}function I(o){return h.join(y(o),"connection.txt")}async function Gt(o,r,e){const t=await N(o,r,e,"--daemon");if(t.stderr)throw new Error(`Can not run ssh Platforma ${t.stderr}`)}async function Mt(o,r,e){const t=await N(o,r,e,"ctl shutdown");if(t.stderr)throw new Error(`Can not stop ssh Platforma ${t.stderr}`)}async function zt(o,r,e,t){let i;try{i=await N(r,e,t,"ctl status")}catch(c){return{execError:String(c),allAlive:!1}}if(i.stderr)return o.info(`supervisord ctl status: stderr occurred: ${i.stderr}, stdout: ${i.stdout}`),{rawResult:i,allAlive:!1};const n=T(i.stdout,"platforma"),s=T(i.stdout,"minio"),a={rawResult:i,platforma:n,minio:s,allAlive:n&&s};return a.allAlive||(a.minio||o.warn("Minio is not running on the server"),a.platforma||o.warn("Platforma is not running on the server")),a}function Jt(o,r,e,t,i,n,s){const a=Object.entries(r).map(([u,d])=>`${u}="${d}"`).join(","),c=x.randomBytes(16).toString("hex"),l=e;return`
|
|
9
9
|
[supervisord]
|
|
10
10
|
logfile=${t}/supervisord.log
|
package/dist/index.mjs
CHANGED
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@milaboratories/pl-deployments",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"pl-version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
|
+
"pl-version": "1.26.0",
|
|
5
5
|
"description": "MiLaboratories Platforma Backend code service run wrapper",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
7
7
|
"main": "./dist/index.js",
|