示例#1
0
    def get_context_data(self, **kwargs):
        
        context = super(ViewSafetySystemInfo, self).get_context_data(**kwargs)

        v = Version()

        info = {
            'product_name'      : 'Web Safety for Squid Proxy',
            'installed_version' : v.installed,
            'latest_version'    : v.latest,
            'need_to_upgrade'   : v.need_to_upgrade(),        # 0 - no_need_to_upgrade, 1 - may_upgrade, 2 - should_upgrade, 3 - must_upgrade
            'whats_new'         : v.whats_new
        };
        context['info'] = info

        # add hardcoded settings
        context['WEBSAFETY_ETC_DIR']      = Paths.etc_dir()
        context['WEBSAFETY_ETC_DIR_SIZE'] = long(FolderInfo(Paths.etc_dir()).get_size()) 
        context['WEBSAFETY_VAR_DIR']      = Paths.var_dir()
        context['WEBSAFETY_VAR_DIR_SIZE'] = long(FolderInfo(Paths.var_dir()).get_size())
        context['WEBSAFETY_BIN_DIR']      = Paths.bin_dir()
        context['WEBSAFETY_BIN_DIR_SIZE'] = long(FolderInfo(Paths.bin_dir()).get_size())
        context['WEBSAFETY_VERSION']      = Build.version()
        context['WEBSAFETY_ARCH']         = Distrib.arch()
        context['WEBSAFETY_DISTRIB']      = Distrib.name()
        context['WEBSAFETY_SYSTEM']       = System.name()
        
        return context
示例#2
0
    def generate(self, contents):

        # debug check
        assert (len(contents) > 0)

        # first generate a temporary file in /opt/websafety/etc/node folder (it will be removed after close automatically)
        prefix = "etc_network_interfaces."
        folder = os.path.join(Paths.etc_dir(), "node")

        # write to temp file
        with tempfile.NamedTemporaryFile(prefix=prefix,
                                         dir=folder,
                                         delete=True) as temp:

            temp.write(contents)
            temp.flush()

            # call the sudoing binary
            exe = os.path.join(Paths.bin_dir(), "network_debian.py")
            arg1 = "--file=%s" % temp.name
            arg2 = "--system=%s" % System.name()
            arg3 = "--distrib=%s" % Distrib.name()
            args = [exe, arg1, arg2, arg3]

            # and run it
            (exit_code, stdout, stderr) = CommandElevated().run(args)
            if exit_code != 0:
                raise Exception(
                    "Cannot generate network settings. Error: %d, STDOUT: %s, STDERR: %s"
                    % (exit_code, stdout, stderr))
示例#3
0
    def full_path():

    	name = "ldap"
    	if System.name() == System.WS_WINDOWS:
    		name += ".exe"

    	return os.path.join(Paths.bin_dir(), name)
示例#4
0
    def set(self, value):

        assert(len(value) > 0)

        # check the provided timezone indeed exists in the pytz
        if value not in pytz.all_timezones:
            raise Exception("Wrong timezone %s (not found pytz.all_timezones)" % value)

        # save the new timezone into the system
        exe  = os.path.join(Paths.bin_dir(), "timezone.py")
        arg1 = "--timezone=%s" % value
        arg2 = "--system=%s" % System.name()
        arg3 = "--distrib=%s" % Distrib.name()
        args = [exe, arg1, arg2, arg3]

        (ret, stdout, stderr) = CommandElevated().run(args)

        # the system zone is set if return value is 0
        if ret == 0:

            # also generate the timezone.setting file
            tz_file = os.path.join(Paths.var_dir(), "console", "console", "timezone.setting")
            with open(tz_file,"w") as fout:
                fout.write(value)

        # and return
        return (ret, stdout, stderr)
示例#5
0
    def categorize(self, domain):

        try:
            name = "categories_checker"
            if System.WS_WINDOWS == System.name():
                name += ".exe"

            exe = os.path.join(Paths.bin_dir(), name)
            arg1 = "--definitions=%s" % (os.path.join(
                Paths.var_dir(), "spool", "categories", "definitions.dat"))
            arg2 = "--domain=%s" % domain

            (exit_code, stdout, stderr) = Command().run([exe, arg1, arg2])

            if 0 == exit_code:
                data = stdout.strip()
                data = data.strip("]")
                data = data.strip("[")
                data = data.strip()
                if len(data) == 0:
                    return []
                else:
                    return data.split(':')

        except Exception as e:
            pass

        return []
示例#6
0
    def get(self, request, *args, **kwargs):

        # allocate default response
        data = {'error': False, 'desc': '', 'info': {}, 'stats': {}}

        # dump amount of free place
        (success, info) = CommandDiskFree().run(Paths.var_dir())
        if success:
            disk = {
                'free': info['avail'],
                'used': info['used'],
                'total': info['size'],
                'ratio': info['ratio'].replace('%', '')
            }
            data['stats']['disk'] = disk

        # get processes wsicapd daemon
        processes = []
        try:
            processes = CommandPs(WsUser.name()).run()
        except Exception as e:
            data['error'] = True
            data['desc'] = str(e)

        # see if wsicapd binary is there and fill the stats
        found = False
        for process in processes:
            if process['path'].find(Paths.bin_dir() + "/wsicapd") != -1:
                found = True
                data['info']['path'] = process['path']
                data['info']['pid'] = process['pid']
                data['info']['user'] = process['user']
                data['stats']['cpu_time'] = process['cpu_time']
                data['stats']['cpu_usage'] = process['cpu_usage']
                data['stats']['mem_size'] = int(process['mem_size'])
                data['stats']['mem_usage'] = process['mem_usage']

        # no wsicapd daemon means something is really bad tell the caller
        if not found:
            data['error'] = True
            data['desc'] = 'the wsicapd daemon is not running'

        # add the processes anyway
        data['info']['processes'] = processes

        # now read the connections
        connections = []
        try:
            icap_port = str(Network.objects.first().wsicap_port)
            connections = CommandNetstat().run(icap_port)
        except Exception as e:
            pass

        # add the connections
        data['info']['connections'] = connections

        # and store as array
        return HttpResponse(json.dumps([data], ensure_ascii=True),
                            content_type='application/json')
示例#7
0
    def __init__(self, server1, port1, server2, port2, token):

        self.exe = os.path.join(Paths.bin_dir(), "inspector_auth.py")
        self.server1 = server1
        self.port1 = str(port1)
        self.server2 = server2
        self.port2 = str(port2)
        self.token = token
示例#8
0
    def run(self, only_reload):

        name = "restart.sh"
        if only_reload:
            name = "reload.sh"

        args = [os.path.join(Paths.bin_dir(), name)]
        
        return CommandElevated().run(args)
示例#9
0
    def get(self, request, *args, **kwargs):

        # allocate default response
        data = { 'error' : False, 'desc' : '', 'info' : {}, 'stats' : {} }

        # dump amount of free place
        (success, info) = CommandDiskFree().run(os.path.join(Paths.var_dir(), "monitor"))
        if success:
            disk = {
                'free'  : info['avail'],
                'used'  : info['used'],
                'total' : info['size'],
                'ratio' : info['ratio'].replace('%', '')
            }
            data['stats']['disk'] = disk

        # we also need to know how many files to upload
        data['stats']['queue'] = FolderInfo(os.path.join(Paths.var_dir(), "monitor")).get_size()

        data['stats']['dbtype'] = 'mysql'
        data['stats']['dbsize'] = self.get_mysqldb_size()
        if DATABASES['monitor']['ENGINE'] == 'django.db.backends.sqlite3':
            data['stats']['dbsize'] = os.path.getsize(DATABASES['monitor']['NAME'])
            data['stats']['dbtype'] = 'sqlite'

        # get processes wsmgrd daemon
        processes = []
        try:
            processes = CommandPs(WsUser.name()).run()
        except Exception as e:
            data['error'] = True
            data['desc']  = str(e)

        # see if wsmgrd binary is there and fill the stats
        found = False
        for process in processes:
            if process['path'].find(Paths.bin_dir() + "/wsmgrd") != -1:
                found = True
                data['info']['path']  = process['path']
                data['info']['pid']   = process['pid']
                data['info']['user']   = process['user']
                data['stats']['cpu_time']  = process['cpu_time']
                data['stats']['cpu_usage'] = process['cpu_usage']
                data['stats']['mem_size']  = int(process['mem_size'])
                data['stats']['mem_usage'] = process['mem_usage']

        # no wsmgrd daemon means something is really bad tell the caller
        if not found:
            data['error'] = True
            data['desc']  = 'the wsmgrd daemon is not running'

        # add the processes anyway
        data['info']['processes'] = processes

        # and store as array
        return HttpResponse(json.dumps([data], ensure_ascii=True), content_type='application/json')
示例#10
0
    def set(self, value):

        assert (len(value) > 0)

        exe = os.path.join(Paths.bin_dir(), "hostname.py")
        arg1 = "--hostname=%s" % value
        arg2 = "--system=%s" % System.name()
        arg3 = "--distrib=%s" % Distrib.name()
        args = [exe, arg1, arg2, arg3]

        return CommandElevated().run(args)
示例#11
0
    def run(self, file):

        name = "ldap"
        if System.name() == System.WS_WINDOWS:
            name += ".exe"

        args = [os.path.join(Paths.bin_dir(), name), "--file=" + file]

        # run this command
        (exit_code, stdout, stderr) = Command.run(self, args)

        # and convert
        return {'exit_code': exit_code, 'stdout': stdout, 'stderr': stderr}
示例#12
0
    def run(self, path):    

    	name = "license"
        if System.name() == System.WS_WINDOWS:
            name += ".exe"

        exe = os.path.join(Paths.bin_dir(), name)
        
        # run this command
        (exit_code, stdout, stderr) = Command.run(self, [exe, "--path", path])

        if exit_code == 0:

            # for some reason lic command gives out the array of license keys
            array = json.loads(stdout)
            if not len(array) > 0:
                raise Exception("Cannot check license key status, exit code %d, stdout - %s, stderr - %s" % (exit_code, stdout, stderr))

            return array[0]

        else:
            raise Exception("License key check failed; exit code %d, stdout - '%s', stderr - '%s'" % (exit_code, stdout, stderr))
示例#13
0
    def run(self, params):

        name = "database"
        if System.name() == System.WS_WINDOWS:
            name += ".exe"

        exe = os.path.join(Paths.bin_dir(), name)
        args = [exe]
        args.extend(params)

        (exit_code, stdout, stderr) = Command.run(self, args)
        if exit_code != 0:
            logging.error("ERROR: ")
            logging.error("ERROR: Cannot switch database, error: %d",
                          exit_code)
            logging.error("ERROR: ")

            logging.error("STDOUT: ")
            logging.error(stdout)

            logging.error("STDERR: ")
            logging.error(stderr)

            raise Exception("FAILURE!!!")
示例#14
0
    def full_path():
    	return os.path.join(Paths.bin_dir(), "cachemgr.py")


# print BinaryCacheMgr.full_path()