Ejemplo n.º 1
0
    def lock(self):
        self._homedir = get_user_dir(
        ) + utils.path_sep + u"." + self._name.lower()
        if not utils.path_exists(self._homedir):
            utils.path_makedirs(self._homedir)
        self._lockfilename = self._homedir + utils.path_sep + "monitor.lock"
        try:
            if is_linux():
                import fcntl
                self._lockfile = utils.file_open(self._lockfilename, "w")
                fcntl.lockf(self._lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
            else:
                if utils.path_exists(self._lockfilename):
                    utils.path_remove(self._lockfilename)
                self._lockfile = utils.file_open(self._lockfilename, "w")
                self._lockfile.write("\x00")
        except:
            try:
                self._lockfile.close()
            except:
                None
            if self._mode == "systray":
                print("An Instance is already running.")
            else:
                self.add_show_file()
            return False

        #self.remove_show_file()
        return True
Ejemplo n.º 2
0
 def get_cpu_logical_count(self):
     num = 0
     try:
         try:
             num = os.sysconf("SC_NPROCESSORS_ONLN")
         except ValueError:
             None
         
         if num == 0:
             f = utils.file_open('/proc/cpuinfo', 'rb')
             try:
                 lines = f.readlines()
             finally:
                 f.close()
             for line in lines:
                 if line.lower().startswith('processor'):
                     num += 1
         if num == 0:
             f = utils.file_open('/proc/stat', 'rt')
             try:
                 lines = f.readlines()
             finally:
                 f.close()
             search = re.compile('cpu\d')
             for line in lines:
                 line = line.split(' ')[0]
                 if search.match(line):
                     num += 1
     except:
         None
     return num
Ejemplo n.º 3
0
    def _write(self, path, prop):
        if "encoding" in prop:
            enc = prop["encoding"]
        else:
            enc = sys.getfilesystemencoding()
        if "endline" in prop:
            endl = prop["endline"]
        else:
            endl = utils.line_sep
        bm = None

        #CREA FILE TEMPORANEO
        pathtmp = None
        sprnpath = utils.path_dirname(path)
        while True:
            r = "".join([random.choice("0123456789") for x in xrange(6)])
            pathtmp = sprnpath + utils.path_sep + "temporary" + r + ".dwstext"
            if not utils.path_exists(pathtmp):
                utils.file_open(
                    pathtmp,
                    'wb').close()  #Crea il file per imposta i permessi
                self._agent_main.get_osmodule().fix_file_permissions(
                    "CREATE_FILE", pathtmp)
                if (enc is not None):
                    flgop = "w"
                    if "bom" in prop and prop["bom"] == 'true':
                        bm = self._get_bom_byname(enc)
                        if bm is not None:
                            #Scrive BOM
                            text_file = utils.file_open(pathtmp, 'wb')
                            text_file.write(bm["Data"])
                            text_file.close()
                            flgop = "a"
                    text_file = utils.file_open(pathtmp, flgop, enc)
                else:
                    text_file = utils.file_open(pathtmp, 'w')
                break
        try:
            s = prop["text"]
            s = endl.join(s.split("\n"))
            text_file.write(s)
        finally:
            text_file.close()
        if utils.path_exists(path):
            if utils.path_isdir(path):
                utils.path_remove(self._tmpname)
                raise Exception("PATH is directory.")
            else:
                self._agent_main.get_osmodule().fix_file_permissions(
                    "COPY_FILE", pathtmp, path)
                utils.path_remove(path)
        shutil.move(pathtmp, path)
Ejemplo n.º 4
0
 def create(self, fname, fieldsdef, fixperm=None):
     self._semaphore.acquire()
     try:
         if self._binit:
             raise Exception("Already initialized.")
         self._path = sharedmem_manager.getPath(fname)
         if utils.path_exists(self._path):
             if fixperm is not None:
                 fixperm(self._path)
             self.open(fname)
             #Verifica se la struttura è identica
             bok = True
             for f in fieldsdef:
                 if f["name"] in self._fields:
                     if f["size"] != self._fields[f["name"]]["size"]:
                         bok = False
                         break
                 else:
                     bok = False
                     break
             if not bok:
                 self.close()
                 #Prova a rimuovere il file
                 try:
                     utils.path_remove(self._path)
                 except:
                     raise Exception("Shared file is locked.")
             else:
                 self._binit = True
                 return
         #CREAZIONE DEL FILE
         self._fields = {}
         szdata = 0
         for f in fieldsdef:
             self._fields[f["name"]] = {"pos": szdata, "size": f["size"]}
             szdata += f["size"]
         shead = json.dumps(self._fields)
         self._len_def = len(shead)
         self._size = 4 + self._len_def + szdata
         with utils.file_open(self._path, "wb") as f:
             f.write(" " * self._size)
         if fixperm is not None:
             fixperm(self._path)
         self._file = utils.file_open(self._path, "r+b")
         self._mmap = mmap.mmap(self._file.fileno(), 0)
         self._mmap.seek(0)
         self._mmap.write(struct.pack('!i', self._len_def))
         self._mmap.write(shead)
         self._binit = True
     finally:
         self._semaphore.release()
Ejemplo n.º 5
0
 def _create_disk(self, fixperm):
     while True:
         self.fname = "stream_" + self._rndseq(8)
         self.fpath = SHAREDMEM_PATH + utils.path_sep + self.fname + ".shm"
         if not utils.path_exists(self.fpath):
             with utils.file_open(self.fpath, "wb") as f:
                 f.write(" " * MapFile._SIZE)
             if fixperm is not None:
                 fixperm(self.fpath)
             self.file = utils.file_open(self.fpath, "r+b")
             self.ftype = "F"
             self._prepare_map()
             self.bdestroy = False
             break
Ejemplo n.º 6
0
 def start(self, bgui=True):
     confjson = {}
     try:
         f = utils.file_open('config.json')
         confjson = json.loads(f.read())
         f.close()
     except Exception:
         None
     prmsui = {}
     if "name" in confjson:
         self._name = unicode(confjson["name"])
     prmsui["title"] = self._get_message('configureTitle')
     if "topinfo" in confjson:
         prmsui["topinfo"] = confjson["topinfo"]
     if "topimage" in confjson:
         prmsui[
             "topimage"] = u"ui" + utils.path_sep + u"images" + utils.path_sep + u"custom" + utils.path_sep + confjson[
                 "topimage"]
     applg = gdi._get_logo_from_conf(
         confjson, u"ui" + utils.path_sep + u"images" + utils.path_sep +
         u"custom" + utils.path_sep)
     if applg != "":
         prmsui["logo"] = applg
     if "leftcolor" in confjson:
         prmsui["leftcolor"] = confjson["leftcolor"]
     self._uinterface = ui.UI(prmsui, self.step_init)
     self._uinterface.start(bgui)
     self.close_req()
Ejemplo n.º 7
0
 def __init__(self,
              sock,
              body_file_name=None,
              response_transfer_progress=None):
     data = ''
     while data.find('\r\n\r\n') == -1:
         app = sock.recv(1024 * 4)
         if app is None or len(app) == 0:
             raise Exception('Close connection')
         data += app
     ar = data.split('\r\n\r\n')
     head = ar[0].split('\r\n')
     appbody = []
     appbody.append(ar[1])
     self._code = None
     self._headers = {}
     clenkey = None
     for item in head:
         if self._code is None:
             self._code = item.split(' ')[1]
         else:
             apppos = item.index(':')
             appk = item[0:apppos].strip()
             if appk.lower() == "content-length":
                 clenkey = appk
             self._headers[appk] = item[apppos + 1:].strip()
     #Legge eventuale body
     if self._code != '301' and clenkey is not None:
         self._extra_data = None
         lenbd = int(self._headers[clenkey])
         fbody = None
         try:
             if body_file_name is not None:
                 fbody = utils.file_open(body_file_name, 'wb')
                 fbody.write(''.join(appbody))
             cnt = len(''.join(appbody))
             if response_transfer_progress is not None:
                 response_transfer_progress.fire_on_data(cnt, lenbd)
             szbuff = 1024 * 2
             buff = None
             while lenbd > cnt:
                 buff = sock.recv(szbuff)
                 if buff is None or len(buff) == 0:
                     break
                 cnt += len(buff)
                 if response_transfer_progress is not None:
                     response_transfer_progress.fire_on_data(cnt, lenbd)
                 if body_file_name is None:
                     appbody.append(buff)
                 else:
                     fbody.write(buff)
         finally:
             if fbody is not None:
                 fbody.close()
             else:
                 self._body = ''.join(appbody)
     else:
         self._extra_data = ''.join(appbody)
         if len(self._extra_data) == 0:
             self._extra_data = None
Ejemplo n.º 8
0
 def get_diskpartition_info(self):
     arret = []
     phydevs = []
     f = utils.file_open("/proc/filesystems", "r")
     try:
         for line in f:
             if not line.startswith("nodev"):
                 phydevs.append(line.strip())
     finally:
         f.close()
     #Legge fstab
     f = utils.file_open("/etc/fstab", "r")
     try:
         for line in f:
             line=line.strip()
             if not line.strip().startswith("#"):
                 line=line.replace('\t',' ')
                 ar=[]
                 arapp = line.split(" ")
                 for a in arapp:
                     if a.strip()!="":
                         ar.append(a.strip())
                 if len(ar)>=3:
                     nm = ar[1]
                     tp = ar[2]
                     if tp in phydevs:
                         path=nm
                         try:
                             st = os.statvfs(path)
                         except UnicodeEncodeError:
                             if isinstance(path, unicode):
                                 try:
                                     import sys
                                     path = path.encode(sys.getfilesystemencoding())
                                 except UnicodeEncodeError:
                                     pass
                                 st = os.statvfs(path)
                             else:
                                 raise
                         free = (st.f_bavail * st.f_frsize)
                         size = (st.f_blocks * st.f_frsize)
                         arret.append({"Name":nm, "Size":size, "Free":free})
     finally:
         f.close()
     return arret    
Ejemplo n.º 9
0
 def init_guilnc(self, ag):
     self._propguilnc_semaphore.acquire()
     try:
         #COMPATIBILITA VERSIONI PRECEDENTI
         if utils.path_exists("native/dwagguilnc"):
             self._propguilnc = {}
             if not utils.path_exists("guilnc.run"):
                 f = utils.file_open("guilnc.run", "wb")
                 f.close()
     finally:
         self._propguilnc_semaphore.release()
Ejemplo n.º 10
0
 def get_service_list(self):
     ret=[]
     if self._which("systemctl"):
         p = subprocess.Popen("systemctl --all --full list-units | grep \.service", stdout=subprocess.PIPE, shell=True)
         (po, pe) = p.communicate()
         p.wait()
         if po is not None and len(po)>0:
             appar = po.split("\n")
             for appln in appar:
                 sv = ""
                 stcnt = -1
                 stapp = ""
                 ar = appln.split(" ")
                 for k in ar:
                     if len(k)>0:
                         if stcnt == -1:
                             if k.endswith(".service"):
                                 sv+=k[0:len(k)-8]
                                 stcnt+=1
                             else:
                                 sv+=k
                         else:
                             stcnt+=1
                             if stcnt==3:
                                 stapp=k
                 if stcnt != -1:
                     if  stapp == "running":
                         st = 4
                     else:
                         st = 1
                     ret.append({"Name":sv,"Label":"","Status":st})
     else:
         #SYSVINIT
         for x in utils.path_list('/etc/init.d'):
             if x.lower()!="rc" and x.lower()!="rcs" and x.lower()!="halt" and x.lower()!="reboot" and x.lower()!="single":
                 xp = "/etc/init.d/" + x
                 st = utils.path_stat(xp)
                 if bool(st.st_mode & stat.S_IXUSR) or bool(st.st_mode & stat.S_IXGRP) or bool(st.st_mode & stat.S_IXOTH):                        
                     appf = utils.file_open("/etc/init.d/" + x)
                     apps = appf.read()
                     appf.close()                        
                     if "status)" in apps or "status|" in apps:  
                         p = subprocess.Popen("/etc/init.d/" + x + " status", stdout=subprocess.PIPE, shell=True)
                         (po, pe) = p.communicate()
                         p.wait()
                         if po is not None and len(po)>0:
                             st = 999
                             if "running" in po.lower() or "started" in po.lower():
                                 st = 4
                             elif "not running" in po.lower() or "not started" in po.lower() or "failed" in po.lower():
                                 st = 1
                             ret.append({"Name":x,"Label":"","Status":st})
     return ret
Ejemplo n.º 11
0
 def _initialize(self):
     self._binit = True
     self._terminate_time = 0
     self._terminate_retry = -1
     self._side_size = (self._size - CONDITION_SIZE_BYTE) / 2
     self._condition_shared = None
     self._condition_shared_pos = 0
     if self._side == 1:
         self._state_pos = CONDITION_SIZE_BYTE + 0
         self._alive_pos = CONDITION_SIZE_BYTE + 1
         self._pid_pos = CONDITION_SIZE_BYTE + 2
         self._write_pnt_pos = CONDITION_SIZE_BYTE + 6
         self._write_data_pos = CONDITION_SIZE_BYTE + 14
         self._state_other_pos = CONDITION_SIZE_BYTE + self._side_size
         self._alive_other_pos = CONDITION_SIZE_BYTE + self._side_size + 1
         self._pid_other_pos = CONDITION_SIZE_BYTE + self._side_size + 2
         self._read_pnt_pos = CONDITION_SIZE_BYTE + self._side_size + 10
         self._read_data_pos = CONDITION_SIZE_BYTE + self._side_size + 14
         self._write_limit = CONDITION_SIZE_BYTE + self._side_size
         self._read_limit = self._size
     elif self._side == 2:
         self._state_pos = CONDITION_SIZE_BYTE + self._side_size
         self._alive_pos = CONDITION_SIZE_BYTE + self._side_size + 1
         self._pid_pos = CONDITION_SIZE_BYTE + self._side_size + 2
         self._write_pnt_pos = CONDITION_SIZE_BYTE + self._side_size + 6
         self._write_data_pos = CONDITION_SIZE_BYTE + self._side_size + 14
         self._state_other_pos = CONDITION_SIZE_BYTE + 0
         self._alive_other_pos = CONDITION_SIZE_BYTE + 1
         self._pid_other_pos = CONDITION_SIZE_BYTE + 2
         self._read_pnt_pos = CONDITION_SIZE_BYTE + 10
         self._read_data_pos = CONDITION_SIZE_BYTE + 14
         self._write_limit = self._size
         self._read_limit = CONDITION_SIZE_BYTE + self._side_size
     self._last_read_time = long(time.time() * 1000)
     self._last_write_time = long(time.time() * 1000)
     self._file = utils.file_open(self._path, "r+b")
     self._mmap = mmap.mmap(self._file.fileno(), 0)
     self._mmap.seek(0)
     self._mmap.write(
         struct.pack("!qiqqiqqiqqiq", -1, -1, -1, -1, -1, -1, -1, -1, -1,
                     -1, -1, -1))
     if self._side == 1:
         self._mmap.seek(CONDITION_SIZE_BYTE)
         self._mmap.write(struct.pack('!cciii', 'C', 'K', os.getpid(), 0,
                                      0))
         self._mmap.seek(CONDITION_SIZE_BYTE + self._side_size)
         self._mmap.write(struct.pack('!cciii', 'W', 'K', -1, 0, 0))
         self._waitconn_tm = long(time.time() * 1000)
     elif self._side == 2:
         self._mmap.seek(CONDITION_SIZE_BYTE + self._side_size)
         self._mmap.write(struct.pack('!cciii', 'C', 'K', os.getpid(), 0,
                                      0))
     sharedmem_manager.add(self)
Ejemplo n.º 12
0
 def detect_bom_file(self, path):
     enc=None
     text_file = utils.file_open(path, 'rb')
     try:
         s = text_file.read(10)
         for bm in self.TEXTFILE_BOM_TYPE :
             if s.startswith(bm["Data"]):
                 enc=bm
                 break
     finally:
         text_file.close()
     return enc;
Ejemplo n.º 13
0
def get_library_config(name):
    fn = None
    if utils.path_exists(".srcmode"):
        fn = ".." + utils.path_sep + "lib_" + name + utils.path_sep + "config.json"
    else:
        fn = "native" + utils.path_sep + "lib_" + name + ".json"
    if utils.path_exists(fn):
        f = utils.file_open(fn)
        jsapp = json.loads(f.read())
        f.close()
        return jsapp
    else:
        return None
Ejemplo n.º 14
0
 def __init__(self):
     self._name = u"DWAgent"
     self._logo = None
     self._properties = {}
     try:
         f = utils.file_open('config.json')
         self._properties = json.loads(f.read())
         f.close()
     except Exception:
         None
     if 'name' in self._properties:
         self._name = unicode(self._properties["name"])
     if "logo" in self._properties:
         self._logo = self._properties["logo"]
Ejemplo n.º 15
0
 def get_task_list(self):
     import pwd
     ret = []
     for x in utils.path_list('/proc') :
         if x.isdigit():
             try:
                 itm={}
                 #PID
                 itm["PID"]=long(x)
                 #Name
                 f = utils.file_open("/proc/%s/stat" % x)
                 try:
                     itm["Name"] = f.read().split(' ')[1].replace('(', '').replace(')', '')
                 finally:
                     f.close()
                 #Memory
                 f = utils.file_open("/proc/%s/statm" % x)
                 try:
                     vms, rss = f.readline().split()[:2]
                     itm["Memory"] = long(rss) * long(self._PAGESIZE)
                     #int(vms) * _PAGESIZE)
                 finally:
                     f.close()
                 #Owner
                 f = utils.file_open("/proc/%s/status" % x)
                 try:
                     for line in f:
                         if line.startswith('Uid:'):
                                 r = line.split()
                                 itm["Owner"] = pwd.getpwuid(int(r[1])).pw_name
                                 break
                 finally:
                     f.close()
                 ret.append(itm)
             except:
                 None
     return ret
Ejemplo n.º 16
0
 def req_read(self, cinfo ,params):
     path = self.check_and_replace_path(cinfo, agent.get_prop(params,'path',None),  self._get_app_filesystem().OPERATION_VIEW)
     position = agent.get_prop(params,'position','')
     maxline = int(agent.get_prop(params,'position','1000'))
     
     fpos = -1l
     flen = utils.path_size(path)
     if  position!="":
         fpos = int(position)
         if fpos > flen:
             fpos = -1
     arl=[]
     if fpos < flen:
         bm = self._get_app_filesystem().detect_bom_file(path)
         enc=None
         if bm is not None:
             enc = bm["Name"]
         f = utils.file_open(path, 'r')
         try:
             if (fpos!=-1):
                 f.seek(fpos)
             while True:
                 ln = f.readline()
                 if ln=="":
                     break
                 if enc is None:
                     enc="UTF-8"
                     try:
                         ln=ln.decode(enc)
                     except:
                         enc=sys.getfilesystemencoding()
                         ln=ln.decode(enc, 'replace')
                 else:
                     ln=ln.decode(enc, 'replace')
                 
                 arl.append(ln.rstrip('\n').rstrip('\r'))
                 if len(arl)>=maxline+1:
                     arl.remove(arl[0])
             if len(arl)>0:
                 arl.append("")
             fpos = f.tell()
         finally:
             f.close()
     ret={}
     ret["text"]='\n'.join(arl)
     if fpos!=-1:
         ret["position"]=str(fpos)
     return json.dumps(ret)
Ejemplo n.º 17
0
 def __init__(self):
     self._name = u"DWAgent"
     self._logo = None
     self._properties = {}
     try:
         f = utils.file_open('config.json')
         self._properties = json.loads(f.read())
         f.close()
     except Exception:
         None
     if 'name' in self._properties:
         self._name = unicode(self._properties["name"])
     applg = gdi._get_logo_from_conf(
         self._properties, u"ui" + utils.path_sep + u"images" +
         utils.path_sep + u"custom" + utils.path_sep)
     if applg != "":
         self._logo = applg
Ejemplo n.º 18
0
    def _read(self, path):

        if utils.path_size(path) > 2 * 1024 * 1024:
            raise Exception("File too large.")

        prop = {}
        enc = None
        bom = False
        text_file = utils.file_open(path, 'rb')
        try:
            s = text_file.read()
            for bm in self._get_app_filesystem().TEXTFILE_BOM_TYPE:
                if s.startswith(bm["Data"]):
                    enc = bm["Name"]
                    bom = True
                    break

            if not bom:
                #Verifica prima utf8
                enc = "UTF-8"
                try:
                    s = s.decode(enc)
                except:
                    enc = sys.getfilesystemencoding()
                    s = s.decode(enc, 'replace')
            else:
                s = self._remove_bom(s)
                s = s.decode(enc, 'replace')
            endline = utils.line_sep
            if s.find("\r\n") > 0:
                endline = "\r\n"
            elif s.find("\n") > 0:
                endline = "\n"
            elif s.find("\r") > 0 and s[len(s) - 1] != "\r":
                endline = "\r"

            prop["bom"] = bom
            prop["encoding"] = enc
            prop["endline"] = endline
            sret = s.splitlines()
            for i in range(len(sret)):
                sret[i] = sret[i].rstrip('\n').rstrip('\r')
            prop["text"] = "\n".join(sret)
        finally:
            text_file.close()
        return prop
Ejemplo n.º 19
0
 def open(self, fname, bpath=None):
     self._semaphore.acquire()
     try:
         if self._binit:
             raise Exception("Already initialized.")
         self._path = sharedmem_manager.getPath(fname, path=bpath)
         if not utils.path_exists(self._path):
             raise Exception("Shared file not found")
         self._file = utils.file_open(self._path, "r+b")
         self._mmap = mmap.mmap(self._file.fileno(), 0)
         self._mmap.seek(0)
         #Legge struttura
         self._len_def = struct.unpack('!i', self._mmap.read(4))[0]
         shead = self._mmap.read(self._len_def)
         self._fields = json.loads(shead)
         self._binit = True
     finally:
         self._semaphore.release()
Ejemplo n.º 20
0
def get_hw_name():
    sapp = platform.machine()
    if is_linux() and len(sapp)>=3 and (sapp[0:3].lower()=="arm" or sapp[0:7].lower()=="aarch64"):
        #VERIFICA SE RASPBERRY
        try:
            if utils.path_exists("/sys/firmware/devicetree/base/model"):
                fin=utils.file_open("/sys/firmware/devicetree/base/model","r")
                appmdl = fin.read()
                fin.close()
                appmdl=check_hw_string(appmdl);
                if appmdl is not None:
                    return appmdl
            appmdl=check_hw_string(platform.node());
            if appmdl is not None:
                return appmdl
        except:
            None
    return None
Ejemplo n.º 21
0
def get_hw_name():
    sapp = platform.machine()
    if is_linux() and len(sapp)>=3 and (sapp[0:3].lower()=="arm" or sapp[0:7].lower()=="aarch64"):
        #VERIFICA SE RASPBERRY
        try:
            if utils.path_exists("/sys/firmware/devicetree/base/model"):
                fin=utils.file_open("/sys/firmware/devicetree/base/model","r")
                appmdl = fin.read()
                fin.close()
                if "raspberry" in appmdl.lower():
                    return "RaspberryPi"
                elif "wandboard" in appmdl.lower():
                    return "Wandboard"
                elif "pine64" in appmdl.lower() or "rock64" in appmdl.lower():
                    return "Pine64"
        except:
            None
    return None
Ejemplo n.º 22
0
 def get_system_info(self):
     hmcpu={}
     f = utils.file_open("/proc/cpuinfo", "r")
     try:
         for line in f:
             if line.startswith("model name"):
                 ar = line.split(":")
                 n = ar[1].strip()
                 if n not in hmcpu:
                     hmcpu[n]=1
                 else:
                     hmcpu[n]=hmcpu[n]+1
     finally:
         f.close()
     cpuName=""
     for k in hmcpu:
         if cpuName!="":
             cpuName+= ", " 
         cpuName+=k
     return  {"osName":platform.platform(),  "osUpdate":"", "osBuild":platform.version(), "pcName":platform.node() , "cpuName":cpuName,  "cpuArchitecture":platform.machine()}
Ejemplo n.º 23
0
 def open(self, name):
     self.ftype = name[0]
     self.fname = name[1:]
     if self.ftype == "F":
         self.fpath = sharedmem_manager.getPath(self.fname)
         if not utils.path_exists(self.fpath):
             raise Exception("Shared file not found.")
         self.file = utils.file_open(self.fpath, "r+b")
     elif self.ftype == "M":
         if not utils.is_windows():
             if load_semaphore_lib():
                 self.fd = _sharememmap["libbase"].sharedMemoryOpen(
                     self.fname, os.O_RDWR, 0o666)
                 if self.fd != -1:
                     #print "open fd: " + str(self.fd) + " " + self.fname
                     stats = os.fstat(self.fd)
                     if stats.st_size != MapFile._SIZE:
                         raise Exception("Invalid map size.")
                 else:
                     raise Exception("Invalid fd.")
             else:
                 raise Exception("Library not loaded.")
     self._prepare_map()
Ejemplo n.º 24
0
    def getStreamFile(self, size):
        fname = None
        self._semaphore.acquire()
        try:
            while True:
                ar = []
                for x in range(8):
                    if x == 0:
                        ar.append(random.choice(string.ascii_lowercase))
                    else:
                        ar.append(
                            random.choice(string.ascii_lowercase +
                                          string.digits))
                fname = "stream_" + ''.join(ar)
                fpath = SHAREDMEM_PATH + utils.path_sep + fname + ".shm"
                if not utils.path_exists(fpath):
                    with utils.file_open(fpath, "wb") as f:
                        f.write(" " * size)
                    break

        finally:
            self._semaphore.release()
        return fname
Ejemplo n.º 25
0
    def start(self, bgui=True):

        confjson = {}
        try:
            f = utils.file_open('config.json')
            confjson = json.loads(f.read())
            f.close()
        except Exception:
            None
        prmsui = {}
        if "name" in confjson:
            self._name = unicode(confjson["name"])
        prmsui["title"] = self._get_message('configureTitle')
        if "topinfo" in confjson:
            prmsui["topinfo"] = confjson["topinfo"]
        if "topimage" in confjson:
            prmsui["topimage"] = confjson["topimage"]
        if "logo" in confjson:
            prmsui["logo"] = confjson["logo"]
        if "leftcolor" in confjson:
            prmsui["leftcolor"] = confjson["leftcolor"]
        self._uinterface = ui.UI(prmsui, self.step_init)
        self._uinterface.start(bgui)
        self.close_req()
Ejemplo n.º 26
0
 def _init_process(self):
     if self._bdestroy:
         raise Exception("Process destroyed.")
     iretry=0;
     while True:
         try:
             self._appconsoleid=None
             iretry+=1
             if agent.is_windows():
                 self._appconsoleid=self._get_osmodule().consoleSessionId();
                 if (self._get_osmodule().isWinXP()==1 or self._get_osmodule().isWin2003Server()==1) and self._appconsoleid>0:
                     self._get_osmodule().winStationConnectW()
                     time.sleep(1)
                     self._destroy_internal()
                 elif self._currentconsoleid!=None and self._appconsoleid!=self._currentconsoleid:
                     self._destroy_internal()
             elif agent.is_mac():
                 self._appconsoleid=self._get_osmodule().consoleUserId();
                 if self._currentconsoleid!=None and self._appconsoleid!=self._currentconsoleid:
                     self._destroy_internal()
                     time.sleep(1)
             
             if self._sharedmem==None:
                 self._sharedmem=sharedmem.Stream()
                 def fix_perm(fn):
                     if agent.is_mac() and self._appconsoleid!=None:
                         utils.path_change_owner(fn, self._appconsoleid, -1)
                         utils.path_change_permissions(fn, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP)
                 fname = self._sharedmem.create(fixperm=fix_perm)
                 #RUN PROCESS
                 #if utils.path_exists("apps" + utils.path_sep + "desktop.py"): ##MI SERVE IN SVILUPPO
                 #    import compileall
                 #    compileall.compile_file("apps" + utils.path_sep + "desktop.py")
                 if agent.is_windows():
                     runaselevatore=u"False"
                     if self._get_osmodule().isUserInAdminGroup()==1:
                         if self._get_osmodule().isRunAsAdmin()==1:
                             if self._get_osmodule().isProcessElevated()==1:
                                 runaselevatore=u"True"
                     #Gestito cosi perche' sys.executable creave problemi con percorsi unicode
                     exep=sys.executable
                     pyhome=u""
                     appth="native\\service.properties"
                     if (utils.path_exists(appth)):
                         f = utils.file_open(appth, 'r', encoding='utf-8')
                         sprop = f.read()
                         f.close()
                         lns = sprop.splitlines()
                         for line in lns:
                             if line.startswith("pythonPath="):
                                 exep=line[11:]
                             elif line.startswith("pythonHome="):
                                 pyhome=line[11:]
                       
                     appcmd=u"\"" + exep + u"\" -S -m agent app=desktop " + unicode(fname) + u" " + unicode(str(self._agent_main._agent_debug_mode)) + u" windows " + runaselevatore
                     self._ppid = self._get_osmodule().startProcessAsUser(appcmd,pyhome)
                     self._currentconsoleid=self._get_osmodule().consoleSessionId();                        
                 elif agent.is_linux():
                     libenv = os.environ
                     if utils.path_exists("runtime"):
                         libenv["LD_LIBRARY_PATH"]=utils.path_absname("runtime/lib")
                     #for some distro linux command below don't works because missing runpy
                     #self._process=subprocess.Popen([sys.executable, u'-S', u'-m', u'agent' , u'app=desktop', unicode(fname), unicode(str(self._agent_main._agent_debug_mode)),u'linux'], env=libenv)
                     self._process=subprocess.Popen([sys.executable, u'agent.pyc', u'app=desktop', fname, str(self._agent_main._agent_debug_mode),u'linux'], env=libenv)
                     '''
                     stat -c%U /dev/tty2                        
                     if my_args is None: my_args = sys.argv[1:]
                     user_name, cwd = my_args[:2]
                     args = my_args[2:]
                     pw_record = pwd.getpwnam(user_name)
                     user_name      = pw_record.pw_name
                     user_home_dir  = pw_record.pw_dir
                     user_uid       = pw_record.pw_uid
                     user_gid       = pw_record.pw_gid
                     env = os.environ.copy()
                     env[ 'HOME'     ]  = user_home_dir
                     env[ 'LOGNAME'  ]  = user_name
                     env[ 'PWD'      ]  = cwd
                     env[ 'USER'     ]  = user_name
                     self._process=subprocess.Popen([sys.executable, u'agent.pyc', u'app=desktop', fname, str(self._agent_main._agent_debug_mode),u'linux'], env=libenv, preexec_fn=self._init_process_demote(1000, 1000))
                     '''
                     #GESTIRE IL RENICE
                 elif agent.is_mac():
                     self._ppid = self._agent_main.get_osmodule().exec_guilnc(self._appconsoleid,"desktop",[fname, str(self._agent_main._agent_debug_mode),u'mac'])
                     if self._ppid is not None:
                         self._currentconsoleid=self._appconsoleid
                         self._process = None
                     else:
                         self._currentconsoleid=None
                         libenv = os.environ
                         if utils.path_exists("runtime"):
                             libenv["DYLD_LIBRARY_PATH"]=utils.path_absname("runtime/lib")
                         #self._process=subprocess.Popen([sys.executable, u'agent.pyc', u'app=desktop', fname, str(self._agent_main._agent_debug_mode),u'mac'], env=libenv)
                         self._process=subprocess.Popen([sys.executable, u'-S', u'-m', u'agent' , u'app=desktop', unicode(fname), unicode(str(self._agent_main._agent_debug_mode)),u'mac'], env=libenv)
                         #GESTIRE IL RENICE
                 self._appconsoleid=None
                    
                 #Attende che il processo si attiva
                 bok=False
                 for i in range(10):
                     time.sleep(0.5)
                     if self._process!=None:
                         if self._process.poll() == None:
                             bok=True
                             break
                     elif self._ppid!=None:
                         if self._agent_main.get_osmodule().is_task_running(self._ppid):
                             bok=True
                             break
                     else:
                         break
                 if bok:
                     break
                 else:
                     raise Exception("Process not started.")
             else:
                 break
          
         except Exception as e:
             time.sleep(1)
             self._destroy_internal()
             if iretry>=3:
                 raise e
Ejemplo n.º 27
0
 def _set_config_base_path(self, pth):
     self._config_base_path = pth
     f = utils.file_open(self._config_base_path + os.sep + 'config.json')
     self._properties = json.loads(f.read())
     f.close()
Ejemplo n.º 28
0
 def add_show_file(self):
     showfilename = self._homedir + utils.path_sep + "monitor.show"
     if not utils.path_exists(showfilename):
         f = utils.file_open(showfilename, "w")
         f.write("\x00")
         f.close()
Ejemplo n.º 29
0
 def get_performance_info(self):
     ret  = {}
     cpuUsagePerc=0
     #Legge info cpu
     f = utils.file_open('/proc/stat', 'rb')
     try:
         arline = f.readline().split()
     finally:
         f.close()
     cputime = {}
     cputime['user'] = float(arline[1]) / self._CLOCKTICKS
     cputime['nice'] = float(arline[2]) / self._CLOCKTICKS
     cputime['system'] = float(arline[3]) / self._CLOCKTICKS
     cputime['idle'] = float(arline[4]) / self._CLOCKTICKS
     cputime['iowait'] = float(arline[5]) / self._CLOCKTICKS
     cputime['irq'] = float(arline[6]) / self._CLOCKTICKS
     cputime['softirq'] = float(arline[7]) / self._CLOCKTICKS
     timer = lambda: self._timer() * self._cpu_logical_count
     cputime['timer']=timer()
     if self._oldcputime is not None:
         try:
             delta_proc = (cputime['user'] - self._oldcputime['user']) + (cputime['system'] - self._oldcputime['system'])
             delta_time = cputime['timer'] - self._oldcputime['timer']
             cpuUsagePerc = int(((delta_proc / delta_time) * 100) * self._cpu_logical_count)
             if cpuUsagePerc>100:
                 cpuUsagePerc=100
         except ZeroDivisionError:
             None
     self._oldcputime = cputime     
     ret["cpuUsagePerc"]=cpuUsagePerc
     
     #Legge la memoria
     f = utils.file_open('/proc/meminfo', 'rb')
     memoryPhysicalTotal=0
     memoryPhysicalAvailable=-1
     memoryFree=0
     memoryVirtualTotal=0
     memoryVirtualAvailable=0
     try:
         for line in f:
             if line.startswith("MemTotal:"):
                 memoryPhysicalTotal = long(line.split()[1]) * 1024
             elif line.startswith("MemFree:"):
                 memoryFree = long(line.split()[1]) * 1024
             elif line.startswith("MemAvailable:"):
                 memoryPhysicalAvailable = long(line.split()[1]) * 1024
             elif line.startswith("SwapTotal:"):
                 memoryVirtualTotal = long(line.split()[1]) * 1024
             elif line.startswith("SwapFree:"):
                 memoryVirtualAvailable = long(line.split()[1]) * 1024
     finally:
         f.close()
     
     ret["memoryPhysicalTotal"]=memoryPhysicalTotal
     if memoryPhysicalAvailable==-1:
         memoryPhysicalAvailable=memoryFree
     ret["memoryPhysicalAvailable"]=memoryPhysicalAvailable
     ret["memoryVirtualTotal"]=memoryVirtualTotal
     ret["memoryVirtualAvailable"]=memoryVirtualAvailable
     ret["memoryTotal"]=ret["memoryPhysicalTotal"]+ret["memoryVirtualTotal"]
     ret["memoryAvailable"]=ret["memoryPhysicalAvailable"]+ret["memoryVirtualAvailable"]
     return ret