'use strict'; 'require baseclass'; 'require fs'; 'require rpc'; 'require ui'; 'require uci'; 'require view.zapret2.env as env_tools'; document.head.append(E('style', {'type': 'text/css'}, ` .label-status { display: inline; margin: 0 2px 0 0 !important; padding: 2px 4px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; font-weight: bold; color: #fff !important; } .starting { background-color: #9c994c !important; } .running { background-color: #2ea256 !important; } .updating { background-color: #1e82ff !important; } .stopped { background-color: #8a8a8a !important; } .error { background-color: #ff4e54 !important; } `)); return baseclass.extend({ __init__() { env_tools.load_env(this); //console.log('appName: ' + this.appName); //console.log('PACKAGER: ' + this.packager.name); }, infoLabelRunning : '' + _('Running') + '', infoLabelStarting : '' + _('Starting') + '', infoLabelStopped : '' + _('Stopped') + '', infoLabelDisabled : '' + _('Disabled') + '', infoLabelError : '' + _('Error') + '', infoLabelUpdating : '' + _('Updating') + '', statusDict: { error : { code: 0, name: _('Error') , label: this.infoLabelError }, disabled : { code: 1, name: _('Disabled') , label: this.infoLabelDisabled }, stopped : { code: 2, name: _('Stopped') , label: this.infoLabelStopped }, starting : { code: 3, name: _('Starting') , label: this.infoLabelStarting }, running : { code: 4, name: _('Running') , label: this.infoLabelRunning }, }, callServiceList: rpc.declare({ object: 'service', method: 'list', params: [ 'name', 'verbose' ], expect: { '': {} } }), callInitState: rpc.declare({ object: 'luci', method: 'getInitList', params: [ 'name' ], expect: { '': {} } }), callInitAction: rpc.declare({ object: 'luci', method: 'setInitAction', params: [ 'name', 'action' ], expect: { result: false } }), getSvcInfo: function(svc_name = null) { let name = (svc_name) ? svc_name : this.appName; let verbose = 1; return this.callServiceList(name, verbose).then(res => { return res; }).catch(e => { ui.addNotification(null, E('p', _('Failed to get %s service info: %s').format(name, e))); }); }, getInitState: function(name) { return this.callInitState(name).then(res => { if (res) { return res[name].enabled ? true : false; } else { throw _('Command failed'); } }).catch(e => { ui.addNotification(null, E('p', _('Failed to get %s init status: %s').format(name, e))); }); }, getPackageDict: function() { let exec_cmd = this.packager.path; let exec_arg = this.packager.args; return fs.exec(exec_cmd, exec_arg).then(res => { let pdict_json = localStorage.getItem(this.skey_pkg_dict); if (res.code != 0) { console.log(this.appName + ': Unable to enumerate installed packages. code = ' + res.code); if (pdict_json != null) { return JSON.parse(pdict_json); // return cached value } return null; } let pdict = this.decode_pkg_list(res.stdout); if (pdict != pdict_json) { localStorage.setItem(this.skey_pkg_dict, JSON.stringify(pdict)); // renew cache } return pdict; }).catch(e => { ui.addNotification(null, E('p', _('Unable to enumerate installed packages.') + ' Error: %s'.format(e))); }); }, getStratList: function() { let exec_cmd = '/bin/busybox'; let exec_arg = [ 'awk', '-F', '"', '/if \\[ "\\$strat" = "/ {print $4}', this.defCfgPath ]; return fs.exec(exec_cmd, exec_arg).then(res => { if (res.code == 0) { return this.getWordsArray(res.stdout); } return [ ]; }).catch(e => { ui.addNotification(null, E('p', _('Failed to get strat list: %s').format(e))); }); }, handleServiceAction: function(name, action, throwed = false) { console.log('handleServiceAction: '+name+' '+action); return this.callInitAction(name, action).then(success => { if (!success) { throw _('Command failed'); } return true; }).catch(e => { ui.addNotification(null, E('p', _('Service action failed "%s %s": %s').format(name, action, e))); if (throwed) { throw e; } }); }, serviceActionEx: async function(action, args = [ ], throwed = false) { let errmsg = null; try { let exec_cmd = null; let exec_arg = [ ]; if (action == 'start' || action == 'restart') { exec_cmd = this.syncCfgPath; errmsg = _('Unable to run sync_config.sh script.'); } if (action == 'reset') { exec_cmd = this.defaultCfgPath; exec_arg = args; // (reset_ipset)(sync) ==> restore all configs + sync config errmsg = _('Unable to run restore-def-cfg.sh script.'); action = null; } if (exec_cmd) { let res = await fs.exec(exec_cmd, exec_arg); if (res.code != 0) { throw Error('res.code = ' + res.code); } } errmsg = null; await this.handleServiceAction(this.appName, action, throwed); } catch(e) { if (throwed) { throw e; } else { let msg = errmsg ? errmsg : _('Unable to run service action') + ' "' + action + '".'; ui.addNotification(null, E('p', msg + ' Error: ' + e.message)); } } }, baseLoad: function(callback, cbarg) { return Promise.all([ this.getSvcInfo(), // svc_info uci.load(this.appName), ]) .then( ([svcInfo, uci_data]) => { let svc_info = this.decodeSvcInfo(svcInfo); let ret = { svc_info, uci_data }; if (typeof callback === 'function') { const res = callback(cbarg, ret); if (res && typeof res.then === 'function') { return res.then(() => ret); } return ret; } return ret; }) .catch(e => { ui.addNotification(null, E('p', _('Unable to read the contents') + ' (baseLoad): %s '.format(e.message) )); return null; }); }, decodeSvcInfo: function(svc_info, svc_autorun = true, proc_list = [ ]) { if (svc_info?.autorun !== undefined && svc_info?.dmn !== undefined) { return svc_info; } if (svc_info != null && typeof(svc_info) == 'object') { return this.decode_svc_info(svc_autorun, svc_info, proc_list); } return null; }, setDefferedAction: function(action, svcInfo = null, forced = false) { let svc_info = this.decodeSvcInfo(svcInfo); if (action == 'start' && svc_info?.dmn.inited) { action = 'restart'; } if (action == 'start') { if (!forced && svc_info?.dmn.inited) { action = null; } } if (action == 'restart') { if (!forced && !svc_info?.dmn.inited) { action = null; } } if (action && localStorage.getItem(this.skey_deffered_action) == null) { localStorage.setItem(this.skey_deffered_action, action); console.log('setDefferedAction: '+this.skey_deffered_action+' = '+action); } }, execDefferedAction: function(svcInfo = null) { let svc_info = this.decodeSvcInfo(svcInfo); //console.log('execDefferedAction: svc_info = '+JSON.stringify(svc_info)); let action = localStorage.getItem(this.skey_deffered_action); if (action) { localStorage.removeItem(this.skey_deffered_action); console.log('execDefferedAction: '+action); this.serviceActionEx(action); } }, checkUnsavedChanges: function() { if (!ui.changes) return false; if (!ui.changes.changes) return false; return ui.changes.changes[this.appName] ? true : false; }, normalizeValue: function(v) { return (v && typeof(v) === 'string') ? v.trim().replace(/\r?\n/g, '') : v; }, getWordsArray: function (text, { trim = true, removeEmpty = true } = {}) { const rawLines = text.split(/\n/); const processed = trim ? rawLines.map(line => line.trim()) : rawLines.slice(); return removeEmpty ? processed.filter(line => line.length > 0) : processed; }, getConfigPar: function(txt, key, defval = null) { const re = new RegExp(`^${key}\\s*=\\s*(['"])(.*?)\\1`, 'm'); const m = txt.match(re); return m ? m[2] : defval; }, decode_pkg_list: function(pkg_list) { let pkg_dict = { }; if (!pkg_list) { return pkg_dict; } let lines = pkg_list.trim().split('\n'); for (let i = 0; i < lines.length; i++) { let line = lines[i].trim(); let name; let ver; let rev = -1; if (this.packager.name == 'apk') { let fullname = line.split(' ')[0]; let match = fullname.match(/^(.*)-r(\d+)$/); if (match) { fullname = match[1]; rev = parseInt(match[2], 10); } let mpos = fullname.lastIndexOf('-'); if (mpos <= 0) continue; // incorrect format name = fullname.slice(0, mpos).trim(); ver = fullname.slice(mpos + 1).trim(); } else { if (!line.includes(' - ')) continue; // incorrect format name = line.split(' - ')[0].trim(); ver = line.split(' - ')[1].trim(); let spos = ver.indexOf(" "); if (spos > 0) { ver = ver.substring(0, spos); } let match = ver.match(/^(.*)-r(\d+)$/); if (match) { ver = match[1]; rev = parseInt(match[2], 10); } } if (rev >= 0) { ver += '-r' + rev; } pkg_dict[name] = ver; } return pkg_dict; }, get_pid_list: function(proc_list) { let plist = [ ]; let lines = proc_list.trim().split('\n'); for (let i = 0; i < lines.length; i++) { let line = lines[i].trim(); if (line.length > 5) { let word_list = line.split(/\s+/); let pid = word_list[0]; let isnum = /^\d+$/.test(pid); if (isnum) { plist.push(parseInt(pid)); } } } return plist; }, decode_svc_info: function(svc_autorun, svc_info, proc_list, cfg = null) { let result = { "autorun": svc_autorun, "dmn": { inited: false, total: 0, running: 0, working: 0, }, "status": this.statusDict.error, }; let plist = proc_list; if (proc_list?.code !== undefined) { if (proc_list.code != 0) { return -2; } plist = this.get_pid_list(proc_list.stdout); if (plist.length < 4) { return -3; } } if (svc_info == null) { return null; } if (typeof(svc_info) !== 'object') { return -4; } let jdata = svc_info; if (typeof(jdata[this.appName]) == 'object') { result.dmn.inited = true; let dmn_list = jdata[this.appName].instances; if (typeof(dmn_list) == 'object') { for (const [dmn_name, daemon] of Object.entries(dmn_list)) { result.dmn.total += 1; if (daemon.running) { result.dmn.running += 1; } if (daemon.pid !== undefined && daemon.pid != null) { if (plist.includes(daemon.pid)) { result.dmn.working += 1; } } } } } //console.log('SVC_DAEMONS: ' + result.dmn.working + ' / ' + result.dmn.total); if (result.dmn.total == 0) { result.status = (!svc_autorun) ? this.statusDict.disabled : this.statusDict.stopped; } else { result.status = (result.dmn.inited) ? this.statusDict.started : this.statusDict.running; } return result; }, makeStatusString: function(svcinfo, pkg_arch, bllist_preset) { let svc_autorun = _('Unknown'); let svc_daemons = _('Unknown'); if (typeof(svcinfo) == 'object') { svc_autorun = (svcinfo.autorun) ? _('Enabled') : _('Disabled'); if (!svcinfo.dmn.inited) { svc_daemons = _('Stopped'); } else { svc_daemons = (!svcinfo.dmn.working) ? _('Starting') : _('Running'); svc_daemons += ' [' + svcinfo.dmn.working + '/' + svcinfo.dmn.total + ']'; } } let td_name_width = 40; let td_name_style = `style="width: ${td_name_width}%; min-width:${td_name_width}%; max-width:${td_name_width}%;"`; let out = `
| ${_('CPU architecture')}: | ${pkg_arch} |
| ${_('Service autorun status')}: | ${svc_autorun} |
| ${_('Service daemons status')}: | ${svc_daemons} |