import debug from "debug" ; const L = debug ( "project:project-setup" ) ; import { setPriority } from "os" ; import { existsSync } from "fs" ; export const DEFAULT_FREE_PROCS_NICENESS = 18 ; interface ProjectConfig { quota ? : { member_host ? : boolean ; dedicated_disks ? : { name : string ; } [ ] ; } ; } export function getProjectConfig ( ) { const conf_enc = process . env . COCALC_PROJECT_CONFIG ; if ( conf_enc == null ) { return null ; } try { L ( `configure(${ conf_enc . slice ( 0 , 30 ) }...)` ) ; const conf_raw = Buffer . from ( conf_enc , "base64" ) . toString ( "utf8" ) ; return JSON . parse ( conf_raw ) ; } catch ( err ) { L ( `ERROR parsing COCALC_PROJECT_CONFIG -- '${ conf_enc }' -- ${ err }` ) ; return null ; } } export function is_free_project ( ) { const conf = getProjectConfig ( ) ; const ifp = conf ?. quota ?. member_host === false ; L ( `is_free_project: ${ ifp }` ) ; return ifp ; } export function configure ( ) { if ( is_free_project ( ) ) { L ( `member_host is false -- renicing everything` ) ; setPriority ( process . pid , DEFAULT_FREE_PROCS_NICENESS ) ; } } export function set_extra_env ( ) { sage_aarch64_hack ( ) ; if ( ! process . env . COCALC_EXTRA_ENV ) { L ( "set_extra_env: nothing provided" ) ; return ; } try { const env64 = process . env . COCALC_EXTRA_ENV ; const raw = Buffer . from ( env64 , "base64" ) . toString ( "utf8" ) ; L ( `set_extra_env: ${ raw }` ) ; const data = JSON . parse ( raw ) ; if ( typeof data === "object" ) { for ( let k in data ) { const v = data [ k ] ; if ( typeof v !== "string" || v . length === 0 ) { L ( `set_extra_env: ignoring key ${ k }, value is not a string or has length 0` ) ; continue ; } process . env [ k ] = v ; } } } catch ( err ) { return L ( `ERROR set_extra_env -- cannot process '${ process . env . COCALC_EXTRA_ENV }' -- ${ err }` ) ; } } export function cleanup ( ) { if ( process . env . PATH == null ) return ; process . env . PATH = process . env . PATH . split ( ":" ) . filter ( ( x ) => ! x . startsWith ( "/cocalc/nvm" ) ) . join ( ":" ) ; const envrm = [ "DATA" , "BASE_PATH" , "NODE_PATH" , "NODE_ENV" , "NODE_VERSION" , "NVM_CD_FLAGS" , "NVM_DIR" , "NVM_BIN" , "DEBUG" , "PATH_COCALC" , "COCALC_ROOT" , ] ; envrm . forEach ( ( name ) => delete process . env [ name ] ) ; for ( const key in process . env ) { if ( key . startsWith ( "npm_" ) ) delete process . env [ key ] ; } } function sage_aarch64_hack ( ) { const LD_PRELOAD = "/usr/lib/aarch64-linux-gnu/libgomp.so.1" ; if ( process . arch == "arm64" && existsSync ( LD_PRELOAD ) ) { process . env . LD_PRELOAD = LD_PRELOAD ; } }