Python simplejson.loads() Examples

The following are code examples for showing how to use simplejson.loads(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 6 votes vote down vote up
def load_payload(self, payload, serializer=None):
        """Loads the encoded object.  This function raises :class:`BadPayload`
        if the payload is not valid.  The `serializer` parameter can be used to
        override the serializer stored on the class.  The encoded payload is
        always byte based.
        """
        if serializer is None:
            serializer = self.serializer
            is_text = self.is_text_serializer
        else:
            is_text = is_text_serializer(serializer)
        try:
            if is_text:
                payload = payload.decode('utf-8')
            return serializer.loads(payload)
        except Exception as e:
            raise BadPayload('Could not load the payload because an '
                'exception occurred on unserializing the data',
                original_error=e) 
Example 2
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 6 votes vote down vote up
def load_payload(self, payload, serializer=None):
        """Loads the encoded object.  This function raises :class:`BadPayload`
        if the payload is not valid.  The `serializer` parameter can be used to
        override the serializer stored on the class.  The encoded payload is
        always byte based.
        """
        if serializer is None:
            serializer = self.serializer
            is_text = self.is_text_serializer
        else:
            is_text = is_text_serializer(serializer)
        try:
            if is_text:
                payload = payload.decode('utf-8')
            return serializer.loads(payload)
        except Exception as e:
            raise BadPayload('Could not load the payload because an '
                'exception occurred on unserializing the data',
                original_error=e) 
Example 3
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 6 votes vote down vote up
def get_host_by_displayname(self, displayname):
        """Returns a host object for the host matching the
        specified display name"""
        self.module.debug("Running LogicMonitor.get_host_by_displayname...")

        self.module.debug("Looking for displayname " + displayname)
        self.module.debug("Making RPC call to 'getHost'")
        host_json = (json.loads(self.rpc("getHost",
                                         {"displayName": displayname})))

        if host_json["status"] == 200:
            self.module.debug("RPC call succeeded")
            return host_json["data"]
        else:
            self.module.debug("RPC call failed")
            self.module.debug(host_json)
            return None 
Example 4
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 6 votes vote down vote up
def get_group(self, fullpath):
        """Returns a JSON group object for the group matching the
        specified path"""
        self.module.debug("Running LogicMonitor.get_group...")

        self.module.debug("Making RPC call to getHostGroups")
        resp = json.loads(self.rpc("getHostGroups", {}))

        if resp["status"] == 200:
            self.module.debug("RPC called succeeded")
            groups = resp["data"]

            self.module.debug("Looking for group matching " + fullpath)
            for group in groups:
                if group["fullPath"] == fullpath.lstrip('/'):
                    self.module.debug("Group match found")
                    return group

            self.module.debug("No group match found")
            return None
        else:
            self.module.debug("RPC call failed")
            self.module.debug(resp)

        return None 
Example 5
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 6 votes vote down vote up
def get_properties(self, final=False):
        """Returns a hash of the properties
        associated with this LogicMonitor host"""
        self.module.debug("Running Hostgroup.get_properties...")

        if self.info:
            self.module.debug("Group found")

            self.module.debug("Making RPC call to 'getHostGroupProperties'")
            properties_json = json.loads(self.rpc(
                "getHostGroupProperties",
                {'hostGroupId': self.info["id"],
                 "finalResult": final}))

            if properties_json["status"] == 200:
                self.module.debug("RPC call succeeded")
                return properties_json["data"]
            else:
                self.module.debug("RPC call failed")
                self.fail(msg=properties_json["status"])
        else:
            self.module.debug("Group not found")
            return None 
Example 6
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor_facts.py    MIT License 6 votes vote down vote up
def get_host_by_displayname(self, displayname):
        """Returns a host object for the host matching the
        specified display name"""
        self.module.debug("Running LogicMonitor.get_host_by_displayname...")

        self.module.debug("Looking for displayname " + displayname)
        self.module.debug("Making RPC call to 'getHost'")
        host_json = (json.loads(self.rpc("getHost",
                                         {"displayName": displayname})))

        if host_json["status"] == 200:
            self.module.debug("RPC call succeeded")
            return host_json["data"]
        else:
            self.module.debug("RPC call failed")
            self.module.debug(host_json)
            return None 
Example 7
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor_facts.py    MIT License 6 votes vote down vote up
def get_group(self, fullpath):
        """Returns a JSON group object for the group matching the
        specified path"""
        self.module.debug("Running LogicMonitor.get_group...")

        self.module.debug("Making RPC call to getHostGroups")
        resp = json.loads(self.rpc("getHostGroups", {}))

        if resp["status"] == 200:
            self.module.debug("RPC called succeeded")
            groups = resp["data"]

            self.module.debug("Looking for group matching " + fullpath)
            for group in groups:
                if group["fullPath"] == fullpath.lstrip('/'):
                    self.module.debug("Group match found")
                    return group

            self.module.debug("No group match found")
            return None
        else:
            self.module.debug("RPC call failed")
            self.module.debug(resp)

        return None 
Example 8
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor_facts.py    MIT License 6 votes vote down vote up
def get_properties(self, final=False):
        """Returns a hash of the properties
        associated with this LogicMonitor host"""
        self.module.debug("Running Hostgroup.get_properties...")

        if self.info:
            self.module.debug("Group found")

            self.module.debug("Making RPC call to 'getHostGroupProperties'")
            properties_json = json.loads(self.rpc(
                "getHostGroupProperties",
                {'hostGroupId': self.info["id"],
                 "finalResult": final}))

            if properties_json["status"] == 200:
                self.module.debug("RPC call succeeded")
                return properties_json["data"]
            else:
                self.module.debug("RPC call failed")
                self.fail(msg=properties_json["status"])
        else:
            self.module.debug("Group not found")
            return None 
Example 9
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 6 votes vote down vote up
def load_payload(self, payload, serializer=None):
        """Loads the encoded object.  This function raises :class:`BadPayload`
        if the payload is not valid.  The `serializer` parameter can be used to
        override the serializer stored on the class.  The encoded payload is
        always byte based.
        """
        if serializer is None:
            serializer = self.serializer
            is_text = self.is_text_serializer
        else:
            is_text = is_text_serializer(serializer)
        try:
            if is_text:
                payload = payload.decode('utf-8')
            return serializer.loads(payload)
        except Exception as e:
            raise BadPayload('Could not load the payload because an '
                'exception ocurred on unserializing the data',
                original_error=e) 
Example 10
Project: wemoo-center   Author: wemoo   File: webhook.py    MIT License 6 votes vote down vote up
def webhook():
    data = simplejson.loads(request.data)
    print(data)

    event = data.get('event')
    repo = data.get('repository')
    if not repo:
        print('>>> not a repo')
        return render.ok('not a repo')

    repo_name = repo.get('name')
    if not repo_name:
        print('>>> repo name missing')
        return render.ok('repo name missing')

    if event in ('push', 'merge_request', 'pull_request'):
        if repo_name in ('test'):
            output = str(execute(script, 300), 'utf-8')
            print(output)
            return render.ok(output)

    return render.ok() 
Example 11
Project: wemoo-center   Author: wemoo   File: hosts.py    MIT License 6 votes vote down vote up
def hosts_post():
    data = simplejson.loads(request.data)

    now = datetime.datetime.now()
    result = Host.objects(uuid=data['uuid']).update(
        set__system=data['system'],
        set__hostname=data['node'],
        set__release=data['release'],
        set__version=data['version'],
        set__machine=data['machine'],
        set__processor=data['processor'],
        set_on_insert__created_at=now,
        updated_at=now,
        upsert=True)

    if result > 0:
        host = Host.objects(uuid=data['uuid']).get(0)
        return render.ok(host.to_dict())
    else:
        return render.error() 
Example 12
Project: ngo-addons-backport   Author: camptocamp   File: main.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def index(self, req, data, token):
        params = simplejson.loads(data)
        model, fields, ids, domain, import_compat = \
            operator.itemgetter('model', 'fields', 'ids', 'domain',
                                'import_compat')(
                params)

        Model = req.session.model(model)
        context = dict(req.context or {}, **params.get('context', {}))
        ids = ids or Model.search(domain, 0, False, False, context)

        field_names = map(operator.itemgetter('name'), fields)
        import_data = Model.export_data(ids, field_names, context).get('datas',[])

        if import_compat:
            columns_headers = field_names
        else:
            columns_headers = [val['label'].strip() for val in fields]


        return req.make_response(self.from_data(columns_headers, import_data),
            headers=[('Content-Disposition',
                            content_disposition(self.filename(model), req)),
                     ('Content-Type', self.content_type)],
            cookies={'fileToken': token}) 
Example 13
Project: openhatch   Author: campbe13   File: jsonrpc.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __call__(self, *args):
        json = dict(method=self.name,
                    id=None,
                    params=list(args))
        req = Request.blank(self.parent._url)
        req.method = 'POST'
        req.content_type = 'application/json'
        req.body = dumps(json)
        resp = req.get_response(self.parent.proxy)
        if resp.status_code != 200 and not (
            resp.status_code == 500
            and resp.content_type == 'application/json'):
            raise ProxyError(
                "Error from JSON-RPC client %s: %s"
                % (self.parent._url, resp.status),
                resp)
        json = loads(resp.body)
        if json.get('error') is not None:
            e = Fault(
                json['error'].get('message'),
                json['error'].get('code'),
                json['error'].get('error'),
                resp)
            raise e
        return json['result'] 
Example 14
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: wrappers.py    Apache License 2.0 5 votes vote down vote up
def json(self):
        """Get the result of simplejson.loads if possible."""
        if 'json' not in self.environ.get('CONTENT_TYPE', ''):
            raise BadRequest('Not a JSON request')
        try:
            return loads(self.data)
        except Exception:
            raise BadRequest('Unable to read JSON request') 
Example 15
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: testtools.py    Apache License 2.0 5 votes vote down vote up
def json(self):
        """Get the result of simplejson.loads if possible."""
        if 'json' not in self.mimetype:
            raise AttributeError('Not a JSON response')
        try:
            from simplejson import loads
        except ImportError:
            from json import loads
        return loads(self.data) 
Example 16
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads(self, payload):
        return json.loads(payload) 
Example 17
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads(self, s, salt=None):
        """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
        signature validation fails.
        """
        s = want_bytes(s)
        return self.load_payload(self.make_signer(salt).unsign(s)) 
Example 18
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads_unsafe(self, s, salt=None):
        """Like :meth:`loads` but without verifying the signature.  This is
        potentially very dangerous to use depending on how your serializer
        works.  The return value is ``(signature_okay, payload)`` instead of
        just the payload.  The first item will be a boolean that indicates
        if the signature is okay (``True``) or if it failed.  This function
        never fails.

        Use it for debugging only and if you know that your serializer module
        is not exploitable (eg: do not use it with a pickle serializer).

        .. versionadded:: 0.15
        """
        return self._loads_unsafe_impl(s, salt) 
Example 19
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def _loads_unsafe_impl(self, s, salt, load_kwargs=None,
                           load_payload_kwargs=None):
        """Lowlevel helper function to implement :meth:`loads_unsafe` in
        serializer subclasses.
        """
        try:
            return True, self.loads(s, salt=salt, **(load_kwargs or {}))
        except BadSignature as e:
            if e.payload is None:
                return False, None
            try:
                return False, self.load_payload(e.payload,
                    **(load_payload_kwargs or {}))
            except BadPayload:
                return False, None 
Example 20
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def load_unsafe(self, f, *args, **kwargs):
        """Like :meth:`loads_unsafe` but loads from a file.

        .. versionadded:: 0.15
        """
        return self.loads_unsafe(f.read(), *args, **kwargs) 
Example 21
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads(self, s, max_age=None, return_timestamp=False, salt=None):
        """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
        signature validation fails.  If a `max_age` is provided it will
        ensure the signature is not older than that time in seconds.  In
        case the signature is outdated, :exc:`SignatureExpired` is raised
        which is a subclass of :exc:`BadSignature`.  All arguments are
        forwarded to the signer's :meth:`~TimestampSigner.unsign` method.
        """
        base64d, timestamp = self.make_signer(salt) \
            .unsign(s, max_age, return_timestamp=True)
        payload = self.load_payload(base64d)
        if return_timestamp:
            return payload, timestamp
        return payload 
Example 22
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads(self, s, salt=None, return_header=False):
        """Reverse of :meth:`dumps`. If requested via `return_header` it will
        return a tuple of payload and header.
        """
        payload, header = self.load_payload(
            self.make_signer(salt, self.algorithm).unsign(want_bytes(s)),
            return_header=True)
        if header.get('alg') != self.algorithm_name:
            raise BadHeader('Algorithm mismatch', header=header,
                            payload=payload)
        if return_header:
            return payload, header
        return payload 
Example 23
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: wrappers.py    Apache License 2.0 5 votes vote down vote up
def json(self):
        """Get the result of simplejson.loads if possible."""
        if 'json' not in self.environ.get('CONTENT_TYPE', ''):
            raise BadRequest('Not a JSON request')
        try:
            return loads(self.data)
        except Exception:
            raise BadRequest('Unable to read JSON request') 
Example 24
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: testtools.py    Apache License 2.0 5 votes vote down vote up
def json(self):
        """Get the result of simplejson.loads if possible."""
        if 'json' not in self.mimetype:
            raise AttributeError('Not a JSON response')
        try:
            from simplejson import loads
        except ImportError:
            from json import loads
        return loads(self.data) 
Example 25
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads(self, payload):
        return json.loads(payload) 
Example 26
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads(self, s, salt=None):
        """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
        signature validation fails.
        """
        s = want_bytes(s)
        return self.load_payload(self.make_signer(salt).unsign(s)) 
Example 27
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads_unsafe(self, s, salt=None):
        """Like :meth:`loads` but without verifying the signature.  This is
        potentially very dangerous to use depending on how your serializer
        works.  The return value is ``(signature_okay, payload)`` instead of
        just the payload.  The first item will be a boolean that indicates
        if the signature is okay (``True``) or if it failed.  This function
        never fails.

        Use it for debugging only and if you know that your serializer module
        is not exploitable (eg: do not use it with a pickle serializer).

        .. versionadded:: 0.15
        """
        return self._loads_unsafe_impl(s, salt) 
Example 28
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def _loads_unsafe_impl(self, s, salt, load_kwargs=None,
                           load_payload_kwargs=None):
        """Lowlevel helper function to implement :meth:`loads_unsafe` in
        serializer subclasses.
        """
        try:
            return True, self.loads(s, salt=salt, **(load_kwargs or {}))
        except BadSignature as e:
            if e.payload is None:
                return False, None
            try:
                return False, self.load_payload(e.payload,
                    **(load_payload_kwargs or {}))
            except BadPayload:
                return False, None 
Example 29
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def load_unsafe(self, f, *args, **kwargs):
        """Like :meth:`loads_unsafe` but loads from a file.

        .. versionadded:: 0.15
        """
        return self.loads_unsafe(f.read(), *args, **kwargs) 
Example 30
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads(self, s, max_age=None, return_timestamp=False, salt=None):
        """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
        signature validation fails.  If a `max_age` is provided it will
        ensure the signature is not older than that time in seconds.  In
        case the signature is outdated, :exc:`SignatureExpired` is raised
        which is a subclass of :exc:`BadSignature`.  All arguments are
        forwarded to the signer's :meth:`~TimestampSigner.unsign` method.
        """
        base64d, timestamp = self.make_signer(salt) \
            .unsign(s, max_age, return_timestamp=True)
        payload = self.load_payload(base64d)
        if return_timestamp:
            return payload, timestamp
        return payload 
Example 31
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def loads(self, s, salt=None, return_header=False):
        """Reverse of :meth:`dumps`. If requested via `return_header` it will
        return a tuple of payload and header.
        """
        payload, header = self.load_payload(
            self.make_signer(salt, self.algorithm).unsign(want_bytes(s)),
            return_header=True)
        if header.get('alg') != self.algorithm_name:
            raise BadHeader('Algorithm mismatch', header=header,
                            payload=payload)
        if return_header:
            return payload, header
        return payload 
Example 32
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 5 votes vote down vote up
def rpc(self, action, params):
        """Make a call to the LogicMonitor RPC library
        and return the response"""
        self.module.debug("Running LogicMonitor.rpc")

        param_str = urlencode(params)
        creds = urlencode(
            {"c": self.company,
                "u": self.user,
                "p": self.password})

        if param_str:
            param_str = param_str + "&"

        param_str = param_str + creds

        try:
            url = ("https://" + self.company + "." + self.lm_url +
                   "/rpc/" + action + "?" + param_str)

            # Set custom LogicMonitor header with version
            headers = {"X-LM-User-Agent": self.__version__}

            # Set headers
            f = open_url(url, headers=headers)

            raw = f.read()
            resp = json.loads(raw)
            if resp["status"] == 403:
                self.module.debug("Authentication failed.")
                self.fail(msg="Error: " + resp["errmsg"])
            else:
                return raw
        except IOError as ioe:
            self.fail(msg="Error: Exception making RPC call to " +
                          "https://" + self.company + "." + self.lm_url +
                          "/rpc/" + action + "\nException" + str(ioe)) 
Example 33
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 5 votes vote down vote up
def get_collectors(self):
        """Returns a JSON object containing a list of
        LogicMonitor collectors"""
        self.module.debug("Running LogicMonitor.get_collectors...")

        self.module.debug("Making RPC call to 'getAgents'")
        resp = self.rpc("getAgents", {})
        resp_json = json.loads(resp)

        if resp_json["status"] is 200:
            self.module.debug("RPC call succeeded")
            return resp_json["data"]
        else:
            self.fail(msg=resp) 
Example 34
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 5 votes vote down vote up
def get_host_by_hostname(self, hostname, collector):
        """Returns a host object for the host matching the
        specified hostname"""
        self.module.debug("Running LogicMonitor.get_host_by_hostname...")

        self.module.debug("Looking for hostname " + hostname)
        self.module.debug("Making RPC call to 'getHosts'")
        hostlist_json = json.loads(self.rpc("getHosts", {"hostGroupId": 1}))

        if collector:
            if hostlist_json["status"] == 200:
                self.module.debug("RPC call succeeded")

                hosts = hostlist_json["data"]["hosts"]

                self.module.debug(
                    "Looking for host matching: hostname " + hostname +
                    " and collector " + str(collector["id"]))

                for host in hosts:
                    if (host["hostName"] == hostname and
                            host["agentId"] == collector["id"]):

                        self.module.debug("Host match found")
                        return host
                self.module.debug("No host match found")
                return None
            else:
                self.module.debug("RPC call failed")
                self.module.debug(hostlist_json)
        else:
            self.module.debug("No collector specified")
            return None 
Example 35
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 5 votes vote down vote up
def _create(self):
        """Create a new collector in the associated
        LogicMonitor account"""
        self.module.debug("Running Collector._create...")

        if self.platform == "Linux":
            self.module.debug("Platform is Linux")
            ret = self.info or self._get()

            if ret is None:
                self.change = True
                self.module.debug("System changed")

                if self.check_mode:
                    self.exit(changed=True)

                h = {"autogen": True,
                     "description": self.description}

                self.module.debug("Making RPC call to 'addAgent'")
                create = (json.loads(self.rpc("addAgent", h)))

                if create["status"] is 200:
                    self.module.debug("RPC call succeeded")
                    self.info = create["data"]
                    self.id = create["data"]["id"]
                    return create["data"]
                else:
                    self.fail(msg=create["errmsg"])
            else:
                self.info = ret
                self.id = ret["id"]
                return ret
        else:
            self.fail(
                msg="Error: LogicMonitor Collector must be " +
                "installed on a Linux device.") 
Example 36
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 5 votes vote down vote up
def _unreigster(self):
        """Delete this collector from the associated
        LogicMonitor account"""
        self.module.debug("Running Collector._unreigster...")

        if self.info is None:
            self.module.debug("Retrieving collector information")
            self.info = self._get()

        if self.info is not None:
            self.module.debug("Collector found")
            self.module.debug("System changed")
            self.change = True

            if self.check_mode:
                self.exit(changed=True)

            self.module.debug("Making RPC call to 'deleteAgent'")
            delete = json.loads(self.rpc("deleteAgent",
                                         {"id": self.id}))

            if delete["status"] is 200:
                self.module.debug("RPC call succeeded")
                return delete
            else:
                # The collector couldn't unregister. Start the service again
                self.module.debug("Error unregistering collecting. " +
                                  delete["errmsg"])
                self.fail(msg=delete["errmsg"])
        else:
            self.module.debug("Collector not found")
            return None 
Example 37
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 5 votes vote down vote up
def get_properties(self):
        """Returns a hash of the properties
        associated with this LogicMonitor host"""
        self.module.debug("Running Host.get_properties...")

        if self.info:
            self.module.debug("Making RPC call to 'getHostProperties'")
            properties_json = (json.loads(self.rpc("getHostProperties",
                                                   {'hostId': self.info["id"],
                                                    "filterSystemProperties": True})))

            if properties_json["status"] == 200:
                self.module.debug("RPC call succeeded")
                return properties_json["data"]
            else:
                self.module.debug("Error: there was an issue retrieving the " +
                                  "host properties")
                self.module.debug(properties_json["errmsg"])

                self.fail(msg=properties_json["status"])
        else:
            self.module.debug(
                "Unable to find LogicMonitor host which matches " +
                self.displayname + " (" + self.hostname + ")"
            )
            return None 
Example 38
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 5 votes vote down vote up
def add(self):
        """Add this device to monitoring
        in your LogicMonitor account"""
        self.module.debug("Running Host.add...")

        if self.collector and not self.info:
            self.module.debug("Host not registered. Registering.")
            self.module.debug("System changed")
            self.change = True

            if self.check_mode:
                self.exit(changed=True)

            h = self._build_host_hash(
                self.hostname,
                self.displayname,
                self.collector,
                self.description,
                self.groups,
                self.properties,
                self.alertenable)

            self.module.debug("Making RPC call to 'addHost'")
            resp = json.loads(self.rpc("addHost", h))

            if resp["status"] == 200:
                self.module.debug("RPC call succeeded")
                return resp["data"]
            else:
                self.module.debug("RPC call failed")
                self.module.debug(resp)
                return resp["errmsg"]
        elif self.collector is None:
            self.fail(msg="Specified collector doesn't exist")
        else:
            self.module.debug("Host already registered") 
Example 39
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 5 votes vote down vote up
def _verify_property(self, propname):
        """Check with LogicMonitor server to
        verify property is unchanged"""
        self.module.debug("Running Host._verify_property...")

        if self.info:
            self.module.debug("Host is registered")
            if propname not in self.properties:
                self.module.debug("Property " + propname + " does not exist")
                return False
            else:
                self.module.debug("Property " + propname + " exists")
                h = {"hostId": self.info["id"],
                     "propName0": propname,
                     "propValue0": self.properties[propname]}

                self.module.debug("Making RCP call to 'verifyProperties'")
                resp = json.loads(self.rpc('verifyProperties', h))

                if resp["status"] == 200:
                    self.module.debug("RPC call succeeded")
                    return resp["data"]["match"]
                else:
                    self.fail(
                        msg="Error: unable to get verification " +
                            "from server.\n%s" % resp["errmsg"])
        else:
            self.fail(
                msg="Error: Host doesn't exist. Unable to verify properties") 
Example 40
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 5 votes vote down vote up
def _compare_groups(self, hostresp):
        """Function to compare the host's current
        groups against provided groups"""
        self.module.debug("Running Host._compare_groups")

        g = []
        fullpathinids = hostresp["fullPathInIds"]
        self.module.debug("Building list of groups")
        for path in fullpathinids:
            if path != []:
                h = {'hostGroupId': path[-1]}

                hgresp = json.loads(self.rpc("getHostGroup", h))

                if (hgresp["status"] == 200 and
                        hgresp["data"]["appliesTo"] == ""):

                    g.append(path[-1])

        if self.groups is not None:
            self.module.debug("Comparing group lists")
            for group in self.groups:
                groupjson = self.get_group(group)

                if groupjson is None:
                    self.module.debug("Group mismatch. No result.")
                    return True
                elif groupjson['id'] not in g:
                    self.module.debug("Group mismatch. ID doesn't exist.")
                    return True
                else:
                    g.remove(groupjson['id'])

            if g != []:
                self.module.debug("Group mismatch. New ID exists.")
                return True
            self.module.debug("Groups match") 
Example 41
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 5 votes vote down vote up
def _verify_property(self, propname):
        """Check with LogicMonitor server
        to verify property is unchanged"""
        self.module.debug("Running Hostgroup._verify_property")

        if self.info:
            self.module.debug("Group exists")
            if propname not in self.properties:
                self.module.debug("Property " + propname + " does not exist")
                return False
            else:
                self.module.debug("Property " + propname + " exists")
                h = {"hostGroupId": self.info["id"],
                     "propName0": propname,
                     "propValue0": self.properties[propname]}

                self.module.debug("Making RCP call to 'verifyProperties'")
                resp = json.loads(self.rpc('verifyProperties', h))

                if resp["status"] == 200:
                    self.module.debug("RPC call succeeded")
                    return resp["data"]["match"]
                else:
                    self.fail(
                        msg="Error: unable to get verification " +
                            "from server.\n%s" % resp["errmsg"])
        else:
            self.fail(
                msg="Error: Group doesn't exist. Unable to verify properties") 
Example 42
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: sensu_silence.py    MIT License 5 votes vote down vote up
def query(module, url, check, subscription):
    headers = {
        'Content-Type': 'application/json',
    }

    url = url + '/silenced'

    request_data = {
        'check': check,
        'subscription': subscription,
    }

    # Remove keys with None value
    for k, v in dict(request_data).items():
        if v is None:
            del request_data[k]

    response, info = fetch_url(
        module, url, method='GET',
        headers=headers, data=json.dumps(request_data)
    )

    if info['status'] == 500:
        module.fail_json(
            msg="Failed to query silence %s. Reason: %s" % (subscription, info)
        )

    try:
        json_out = json.loads(response.read())
    except:
        json_out = ""

    return False, json_out, False 
Example 43
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor_facts.py    MIT License 5 votes vote down vote up
def rpc(self, action, params):
        """Make a call to the LogicMonitor RPC library
        and return the response"""
        self.module.debug("Running LogicMonitor.rpc")

        param_str = urlencode(params)
        creds = urlencode(
            {"c": self.company,
                "u": self.user,
                "p": self.password})

        if param_str:
            param_str = param_str + "&"

        param_str = param_str + creds

        try:
            url = ("https://" + self.company + "." + self.lm_url +
                   "/rpc/" + action + "?" + param_str)

            # Set custom LogicMonitor header with version
            headers = {"X-LM-User-Agent": self.__version__}

            # Set headers
            f = open_url(url, headers=headers)

            raw = f.read()
            resp = json.loads(raw)
            if resp["status"] == 403:
                self.module.debug("Authentication failed.")
                self.fail(msg="Error: " + resp["errmsg"])
            else:
                return raw
        except IOError as ioe:
            self.fail(msg="Error: Exception making RPC call to " +
                          "https://" + self.company + "." + self.lm_url +
                          "/rpc/" + action + "\nException" + to_native(ioe)) 
Example 44
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor_facts.py    MIT License 5 votes vote down vote up
def get_host_by_hostname(self, hostname, collector):
        """Returns a host object for the host matching the
        specified hostname"""
        self.module.debug("Running LogicMonitor.get_host_by_hostname...")

        self.module.debug("Looking for hostname " + hostname)
        self.module.debug("Making RPC call to 'getHosts'")
        hostlist_json = json.loads(self.rpc("getHosts", {"hostGroupId": 1}))

        if collector:
            if hostlist_json["status"] == 200:
                self.module.debug("RPC call succeeded")

                hosts = hostlist_json["data"]["hosts"]

                self.module.debug(
                    "Looking for host matching: hostname " + hostname +
                    " and collector " + str(collector["id"]))

                for host in hosts:
                    if (host["hostName"] == hostname and
                            host["agentId"] == collector["id"]):

                        self.module.debug("Host match found")
                        return host
                self.module.debug("No host match found")
                return None
            else:
                self.module.debug("RPC call failed")
                self.module.debug(hostlist_json)
        else:
            self.module.debug("No collector specified")
            return None 
Example 45
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor_facts.py    MIT License 5 votes vote down vote up
def get_properties(self):
        """Returns a hash of the properties
        associated with this LogicMonitor host"""
        self.module.debug("Running Host.get_properties...")

        if self.info:
            self.module.debug("Making RPC call to 'getHostProperties'")
            properties_json = (json.loads(self.rpc("getHostProperties",
                                                   {'hostId': self.info["id"],
                                                    "filterSystemProperties": True})))

            if properties_json["status"] == 200:
                self.module.debug("RPC call succeeded")
                return properties_json["data"]
            else:
                self.module.debug("Error: there was an issue retrieving the " +
                                  "host properties")
                self.module.debug(properties_json["errmsg"])

                self.fail(msg=properties_json["status"])
        else:
            self.module.debug(
                "Unable to find LogicMonitor host which matches " +
                self.displayname + " (" + self.hostname + ")"
            )
            return None 
Example 46
Project: flasky   Author: RoseOu   File: wrappers.py    MIT License 5 votes vote down vote up
def json(self):
        """Get the result of simplejson.loads if possible."""
        if 'json' not in self.environ.get('CONTENT_TYPE', ''):
            raise BadRequest('Not a JSON request')
        try:
            return loads(self.data)
        except Exception:
            raise BadRequest('Unable to read JSON request') 
Example 47
Project: flasky   Author: RoseOu   File: testtools.py    MIT License 5 votes vote down vote up
def json(self):
        """Get the result of simplejson.loads if possible."""
        if 'json' not in self.mimetype:
            raise AttributeError('Not a JSON response')
        try:
            from simplejson import loads
        except ImportError:
            from json import loads
        return loads(self.data) 
Example 48
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def loads(self, payload):
        return json.loads(payload) 
Example 49
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def loads(self, s, salt=None):
        """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
        signature validation fails.
        """
        s = want_bytes(s)
        return self.load_payload(self.make_signer(salt).unsign(s)) 
Example 50
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def loads_unsafe(self, s, salt=None):
        """Like :meth:`loads` but without verifying the signature.  This is
        potentially very dangerous to use depending on how your serializer
        works.  The return value is ``(signature_okay, payload)`` instead of
        just the payload.  The first item will be a boolean that indicates
        if the signature is okay (``True``) or if it failed.  This function
        never fails.

        Use it for debugging only and if you know that your serializer module
        is not exploitable (eg: do not use it with a pickle serializer).

        .. versionadded:: 0.15
        """
        return self._loads_unsafe_impl(s, salt) 
Example 51
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def _loads_unsafe_impl(self, s, salt, load_kwargs=None,
                           load_payload_kwargs=None):
        """Lowlevel helper function to implement :meth:`loads_unsafe` in
        serializer subclasses.
        """
        try:
            return True, self.loads(s, salt=salt, **(load_kwargs or {}))
        except BadSignature as e:
            if e.payload is None:
                return False, None
            try:
                return False, self.load_payload(e.payload,
                    **(load_payload_kwargs or {}))
            except BadPayload:
                return False, None 
Example 52
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def load_unsafe(self, f, *args, **kwargs):
        """Like :meth:`loads_unsafe` but loads from a file.

        .. versionadded:: 0.15
        """
        return self.loads_unsafe(f.read(), *args, **kwargs) 
Example 53
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def loads(self, s, max_age=None, return_timestamp=False, salt=None):
        """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
        signature validation fails.  If a `max_age` is provided it will
        ensure the signature is not older than that time in seconds.  In
        case the signature is outdated, :exc:`SignatureExpired` is raised
        which is a subclass of :exc:`BadSignature`.  All arguments are
        forwarded to the signer's :meth:`~TimestampSigner.unsign` method.
        """
        base64d, timestamp = self.make_signer(salt) \
            .unsign(s, max_age, return_timestamp=True)
        payload = self.load_payload(base64d)
        if return_timestamp:
            return payload, timestamp
        return payload 
Example 54
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def loads(self, s, salt=None, return_header=False):
        """Reverse of :meth:`dumps`. If requested via `return_header` it will
        return a tuple of payload and header.
        """
        payload, header = self.load_payload(
            self.make_signer(salt, self.algorithm).unsign(want_bytes(s)),
            return_header=True)
        if header.get('alg') != self.algorithm_name:
            raise BadSignature('Algorithm mismatch')
        if return_header:
            return payload, header
        return payload 
Example 55
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: vif_rules.py    Apache License 2.0 5 votes vote down vote up
def main(dom_id, command, only_this_vif=None):
    xsls = novalib.execute_get_output('/usr/bin/xenstore-ls',
                              '/local/domain/%s/vm-data/networking' % dom_id)
    macs = [line.split("=")[0].strip() for line in xsls.splitlines()]

    for mac in macs:
        xsread = novalib.execute_get_output('/usr/bin/xenstore-read',
                                    '/local/domain/%s/vm-data/networking/%s' %
                                    (dom_id, mac))
        data = json.loads(xsread)
        for ip in data['ips']:
            if data["label"] == "public":
                vif = "vif%s.0" % dom_id
            else:
                vif = "vif%s.1" % dom_id

            if (only_this_vif is None) or (vif == only_this_vif):
                params = dict(IP=ip['ip'], VIF=vif, MAC=data['mac'])
                apply_ebtables_rules(command, params)
                apply_arptables_rules(command, params)
                apply_iptables_rules(command, params)


# A note about adding rules:
#   Whenever we add any rule to iptables, arptables or ebtables we first
#   delete the same rule to ensure the rule only exists once. 
Example 56
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: xenstore.py    Apache License 2.0 5 votes vote down vote up
def jsonify(fnc):
    def wrapper(*args, **kwargs):
        ret = fnc(*args, **kwargs)
        try:
            json.loads(ret)
        except ValueError:
            # Value should already be JSON-encoded, but some operations
            # may write raw sting values; this will catch those and
            # properly encode them.
            ret = json.dumps(ret)
        return ret
    return wrapper 
Example 57
Project: wemoo-center   Author: wemoo   File: logs.py    MIT License 5 votes vote down vote up
def get_user():
    data = simplejson.loads(request.data)
    app_id = data.get('app_id', None)
    level = data.get('level', None)
    log_type = data.get('log_type', None)
    content = data.get('content', None)
    if not (app_id and level and log_type and content):
        return render.error('missing')

    Log(app_id=app_id, level=level, log_type=log_type, content=content).save()

    return render.ok() 
Example 58
Project: wemoo-center   Author: wemoo   File: log_test.py    MIT License 5 votes vote down vote up
def test_create_one_log(self):
        app_id = 'test-app-id'
        level = 'info'
        log_type = 'test-type'
        content = {'level1_1': 1, 'level1_2': {'leve2_1': 1}}
        data = {'app_id': app_id, 'level': level, 'log_type': log_type, 'content': content}

        url = '/api/logs'
        res = self.test.post(url, data=simplejson.dumps(data))
        assert res.status_code == 200
        assert simplejson.loads(res.data)['status'] == 'ok' 
Example 59
Project: ngo-addons-backport   Author: camptocamp   File: fields.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _symbol_get_struct(self, val):
        return simplejson.loads(val or '{}') 
Example 60
Project: ngo-addons-backport   Author: camptocamp   File: main.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def saveas_ajax(self, req, data, token):
        jdata = simplejson.loads(data)
        model = jdata['model']
        field = jdata['field']
        data = jdata['data']
        id = jdata.get('id', None)
        filename_field = jdata.get('filename_field', None)
        context = jdata.get('context', {})
        content_type = 'application/octet-stream'

        Model = req.session.model(model)
        fields = [field]
        if filename_field:
            fields.append(filename_field)
        if data:
            res = { field: data }
        elif id:
            fields.append('file_type')
            res = Model.read([int(id)], fields, context)[0]
            if res.get('file_type'):
                content_type = res['file_type']
        else:
            res = Model.default_get(fields, context)
        filecontent = base64.b64decode(res.get(field, ''))
        if not filecontent:
            raise ValueError(_("No content found for field '%s' on '%s:%s'") %
                (field, model, id))
        else:
            filename = '%s_%s' % (model.replace('.', '_'), id)
            if filename_field:
                filename = res.get(filename_field, '') or filename
            return req.make_response(
                filecontent, headers=[('Content-Type', content_type),
                                      ('Content-Disposition',
                                       content_disposition(filename, req))],
                cookies={'fileToken': token}) 
Example 61
Project: ngo-addons-backport   Author: camptocamp   File: edi.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def deserialize(self, edi_documents_string):
        """Return deserialized version of the given EDI Document string.

        :param str|unicode edi_documents_string: UTF-8 string (or unicode) containing
                                                 JSON-serialized EDI document(s)
        :return: Python object representing the EDI document(s) (usually a list of dicts)
        """
        return json.loads(edi_documents_string) 
Example 62
Project: openhatch   Author: campbe13   File: jsonrpc.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def process(self, req):
        if not req.method == 'POST':
            raise exc.HTTPMethodNotAllowed(
                "Only POST allowed",
                allowed='POST')
        try:
            json = loads(req.body)
        except ValueError, e:
            raise ValueError('Bad JSON: %s' % e) 
Example 63
Project: openhatch   Author: campbe13   File: request.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _json_body__get(self):
        """Access the body of the request as JSON"""
        return json.loads(self.body.decode(self.charset)) 
Example 64
Project: openhatch   Author: campbe13   File: response.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _json_body__get(self):
        """Access the body of the response as JSON"""
        # Note: UTF-8 is a content-type specific default for JSON:
        return json.loads(self.body.decode(self.charset or 'UTF-8')) 
Example 65
Project: ti.doorbell   Author: alejonext   File: build.py    MIT License 5 votes vote down vote up
def parse_deps(self, deps):
		found = []
		if len(deps) > 2:
			deps = deps[1:-1]
			deps = deps.split(',')
			for dep in deps:
				dep = dep.strip().split(' ')[0].strip()
				if dep.startswith('\'') or dep.startswith('"'):
					found.append(simplejson.loads(dep))
		return found 
Example 66
Project: contentful.py   Author: contentful   File: content_type_field_types.py    MIT License 5 votes vote down vote up
def coerce(self, value, **kwargs):
        """Coerces JSON values properly."""

        return json.loads(json.dumps(value)) 
Example 67
Project: iddaa-bets   Author: akaniklaus   File: utils.py    GNU General Public License v2.0 5 votes vote down vote up
def get_json_data(url):
    response = urllib2.urlopen(url)
    j = response.read()
    j = re.sub(r"{\s*(\w+):", r'{"\1":', j)
    j = re.sub(r",\s*(\w+):", r',"\1":', j)
    j = j.replace("'", '"')
    result = simplejson.loads(j)
    return result 
Example 68
Project: sower   Author: aeroxis   File: contract.py    MIT License 5 votes vote down vote up
def load_yaml_data(contract_contents):
    """
    Given a string 'contract_contents', this method assumes it's 
    contents are YAML, and loads it into memory.
    """
    return yaml.load(
        textwrap.dedent(contract_contents),
        Loader=YAMLLoader
    ) 
Example 69
Project: sower   Author: aeroxis   File: contract.py    MIT License 5 votes vote down vote up
def load_json_data(contract_contents):
    """
    Given a string 'contract_contents', this method assumes it's
    contents are JSON, and loads it into memory
    """
    return json.loads(
        contract_contents, object_pairs_hook=OrderedDict
    ) 
Example 70
Project: Pancas   Author: Sup3Roque   File: genesisresolvers.py    GNU General Public License v2.0 5 votes vote down vote up
def hosts(self):
        try:
            if self.status() == False: raise Exception()

            url = 'http://api.premiumize.me/pm-api/v1.php?method=hosterlist&params[login]=%s&params[pass]=%s' % (self.user, self.password)

            result = getUrl(url).result

            pz = json.loads(result)['result']['hosterlist']
            pz = [i.rsplit('.' ,1)[0].lower() for i in pz]
            return pz
        except:
            return 
Example 71
Project: Pancas   Author: Sup3Roque   File: genesisresolvers.py    GNU General Public License v2.0 5 votes vote down vote up
def resolve(self, url):
        try:
            if self.status() == False: raise Exception()

            url = 'http://api.premiumize.me/pm-api/v1.php?method=directdownloadlink&params[login]=%s&params[pass]=%s&params[link]=%s' % (self.user, self.password, urllib.quote_plus(url))

            result = getUrl(url, close=False).result

            url = json.loads(result)['result']['location']
            return url
        except:
            return 
Example 72
Project: Pancas   Author: Sup3Roque   File: genesisresolvers.py    GNU General Public License v2.0 5 votes vote down vote up
def hosts(self):
        try:
            if self.status() == False: raise Exception()

            url = 'http://real-debrid.com/api/hosters.php'

            result = getUrl(url).result

            rd = json.loads('[%s]' % result)
            rd = [i.rsplit('.' ,1)[0].lower() for i in rd]
            return rd
        except:
            return 
Example 73
Project: FireMISP   Author: deralexxx   File: firemisp.py    MIT License 4 votes vote down vote up
def do_POST(self):
        logger.debug("someone sended a post")
        # get the posted data and remove newlines
        # https://stackoverflow.com/questions/2121481/python3-http-server-post-example
        length = int(self.headers['Content-Length'])
        post_data2 = self.rfile.read(length).decode('utf-8')
        clean = post_data2.replace('\n', '')
        theJson = json.loads(clean)

        # TODO give something as response back
        self.wfile.write("Lorem Ipsum".encode("utf-8"))

        try:
            # Write the data to a file as well for debugging later on
            import datetime
            filename1 = './testing/real/'+datetime.datetime.now().strftime("%Y%m%d-%H%M%S")+".json"
            f = open(filename1, 'w')

            #f.write(data)
            json.dump(theJson, f)
            f.close

            self.send_response(200)
            self.end_headers()
            #processAlert(theJson)
            # deal with multiple alerts embedded as an array
            if isinstance(theJson['alert'], list):
                # alertJson = theJson
                # del alertJson['alert']
                for element in theJson['alert']:
                    alertJson = {}  # added for Issue #4
                    alertJson['alert'] = element
                    logger.info("Processing FireEye Alert: " + str(alertJson['alert']['id']))
                    processAlert(alertJson)
            else:
                logger.debug("Processing FireEye Alert: " + str(theJson['alert']['id']))
                processAlert(theJson)

        except ValueError as e:
            logger.error("Value Error2: %s %s",e.message,e.args)
            self.send_response(500)

# ---------------- end class MyRequestHandler ----------------


# ---------------- Class handles requests in a separate thread. ---------------- 
Example 74
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 4 votes vote down vote up
def update(self):
        """This method takes changes made to this host
        and applies them to the corresponding host
        in your LogicMonitor account."""
        self.module.debug("Running Host.update...")

        if self.info:
            self.module.debug("Host already registed")
            if self.is_changed():
                self.module.debug("System changed")
                self.change = True

                if self.check_mode:
                    self.exit(changed=True)

                h = (self._build_host_hash(
                     self.hostname,
                     self.displayname,
                     self.collector,
                     self.description,
                     self.groups,
                     self.properties,
                     self.alertenable))
                h["id"] = self.info["id"]
                h["opType"] = "replace"

                self.module.debug("Making RPC call to 'updateHost'")
                resp = json.loads(self.rpc("updateHost", h))

                if resp["status"] == 200:
                    self.module.debug("RPC call succeeded")
                else:
                    self.module.debug("RPC call failed")
                    self.fail(msg="Error: unable to update the host.")
            else:
                self.module.debug(
                    "Host properties match supplied properties. " +
                    "No changes to make."
                )
                return self.info
        else:
            self.module.debug("Host not registed. Registering")
            self.module.debug("System changed")
            self.change = True

            if self.check_mode:
                self.exit(changed=True)

            return self.add() 
Example 75
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 4 votes vote down vote up
def sdt(self):
        """Create a scheduled down time
        (maintenance window) for this host"""
        self.module.debug("Running Datasource.sdt...")

        self.module.debug("System changed")
        self.change = True

        if self.check_mode:
            self.exit(changed=True)

        duration = self.duration
        starttime = self.starttime
        offsetstart = starttime

        if starttime:
            self.module.debug("Start time specified")
            start = datetime.datetime.strptime(starttime, '%Y-%m-%d %H:%M')
            offsetstart = start
        else:
            self.module.debug("No start time specified. Using default.")
            start = datetime.datetime.utcnow()

            # Use user UTC offset
            self.module.debug("Making RPC call to 'getTimeZoneSetting'")
            accountresp = json.loads(self.rpc("getTimeZoneSetting", {}))

            if accountresp["status"] == 200:
                self.module.debug("RPC call succeeded")

                offset = accountresp["data"]["offset"]
                offsetstart = start + datetime.timedelta(0, offset)
            else:
                self.fail(msg="Error: Unable to retrieve timezone offset")

        offsetend = offsetstart + datetime.timedelta(0, int(duration) * 60)

        h = {"hostDataSourceId": self.id,
             "type": 1,
             "notifyCC": True,
             "year": offsetstart.year,
             "month": offsetstart.month - 1,
             "day": offsetstart.day,
             "hour": offsetstart.hour,
             "minute": offsetstart.minute,
             "endYear": offsetend.year,
             "endMonth": offsetend.month - 1,
             "endDay": offsetend.day,
             "endHour": offsetend.hour,
             "endMinute": offsetend.minute}

        self.module.debug("Making RPC call to 'setHostDataSourceSDT'")
        resp = json.loads(self.rpc("setHostDataSourceSDT", h))

        if resp["status"] == 200:
            self.module.debug("RPC call succeeded")
            return resp["data"]
        else:
            self.module.debug("RPC call failed")
            self.fail(msg=resp["errmsg"]) 
Example 76
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 4 votes vote down vote up
def update(self):
        """Idempotent function to ensure the host group settings
        (alertenable, properties, etc) in the
        LogicMonitor account match the current object."""
        self.module.debug("Running Hostgroup.update")

        if self.info:
            if self.is_changed():
                self.module.debug("System changed")
                self.change = True

                if self.check_mode:
                    self.exit(changed=True)

                h = self._build_host_group_hash(
                    self.fullpath,
                    self.description,
                    self.properties,
                    self.alertenable)
                h["opType"] = "replace"

                if self.fullpath != "/":
                    h["id"] = self.info["id"]

                self.module.debug("Making RPC call to 'updateHostGroup'")
                resp = json.loads(self.rpc("updateHostGroup", h))

                if resp["status"] == 200:
                    self.module.debug("RPC call succeeded")
                    return resp["data"]
                else:
                    self.module.debug("RPC call failed")
                    self.fail(msg="Error: Unable to update the " +
                              "host.\n" + resp["errmsg"])
            else:
                self.module.debug(
                    "Group properties match supplied properties. " +
                    "No changes to make"
                )
                return self.info
        else:
            self.module.debug("Group doesn't exist. Creating.")

            self.module.debug("System changed")
            self.change = True

            if self.check_mode:
                self.exit(changed=True)

            return self.add() 
Example 77
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logicmonitor.py    MIT License 4 votes vote down vote up
def sdt(self, duration=30, starttime=None):
        """Create a scheduled down time
        (maintenance window) for this host"""
        self.module.debug("Running Hostgroup.sdt")

        self.module.debug("System changed")
        self.change = True

        if self.check_mode:
            self.exit(changed=True)

        duration = self.duration
        starttime = self.starttime
        offset = starttime

        if starttime:
            self.module.debug("Start time specified")
            start = datetime.datetime.strptime(starttime, '%Y-%m-%d %H:%M')
            offsetstart = start
        else:
            self.module.debug("No start time specified. Using default.")
            start = datetime.datetime.utcnow()

            # Use user UTC offset
            self.module.debug("Making RPC call to 'getTimeZoneSetting'")
            accountresp = json.loads(self.rpc("getTimeZoneSetting", {}))

            if accountresp["status"] == 200:
                self.module.debug("RPC call succeeded")

                offset = accountresp["data"]["offset"]
                offsetstart = start + datetime.timedelta(0, offset)
            else:
                self.fail(
                    msg="Error: Unable to retrieve timezone offset")

        offsetend = offsetstart + datetime.timedelta(0, int(duration) * 60)

        h = {"hostGroupId": self.info["id"],
             "type": 1,
             "year": offsetstart.year,
             "month": offsetstart.month - 1,
             "day": offsetstart.day,
             "hour": offsetstart.hour,
             "minute": offsetstart.minute,
             "endYear": offsetend.year,
             "endMonth": offsetend.month - 1,
             "endDay": offsetend.day,
             "endHour": offsetend.hour,
             "endMinute": offsetend.minute}

        self.module.debug("Making RPC call to setHostGroupSDT")
        resp = json.loads(self.rpc("setHostGroupSDT", h))

        if resp["status"] == 200:
            self.module.debug("RPC call succeeded")
            return resp["data"]
        else:
            self.module.debug("RPC call failed")
            self.fail(msg=resp["errmsg"]) 
Example 78
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: sensu_silence.py    MIT License 4 votes vote down vote up
def clear(module, url, check, subscription):
    # Test if silence exists before clearing
    (rc, out, changed) = query(module, url, check, subscription)

    d = dict((i['subscription'], i['check']) for i in out)
    subscription_exists = subscription in d
    if check and subscription_exists:
        exists = (check == d[subscription])
    else:
        exists = subscription_exists

    # If check/subscription doesn't exist
    # exit with changed state of False
    if not exists:
        return False, out, changed

    # module.check_mode is inherited from the AnsibleMOdule class
    if not module.check_mode:
        headers = {
            'Content-Type': 'application/json',
        }

        url = url + '/silenced/clear'

        request_data = {
            'check': check,
            'subscription': subscription,
        }

        # Remove keys with None value
        for k, v in dict(request_data).items():
            if v is None:
                del request_data[k]

        response, info = fetch_url(
            module, url, method='POST',
            headers=headers, data=json.dumps(request_data)
        )

        if info['status'] != 204:
            module.fail_json(
                msg="Failed to silence %s. Reason: %s" % (subscription, info)
            )

        try:
            json_out = json.loads(response.read())
        except:
            json_out = ""

        return False, json_out, True
    return False, out, True 
Example 79
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: ovs_configure_vif_flows.py    Apache License 2.0 4 votes vote down vote up
def main(command, vif_raw, net_type):
    if command not in ('online', 'offline'):
        return

    vif_name, dom_id, vif_index = vif_raw.split('-')
    vif = "%s%s.%s" % (vif_name, dom_id, vif_index)

    bridge = novalib.execute_get_output('/usr/bin/ovs-vsctl',
                                                    'iface-to-br', vif)

    xsls = novalib.execute_get_output('/usr/bin/xenstore-ls',
                              '/local/domain/%s/vm-data/networking' % dom_id)
    macs = [line.split("=")[0].strip() for line in xsls.splitlines()]

    for mac in macs:
        xsread = novalib.execute_get_output('/usr/bin/xenstore-read',
                                    '/local/domain/%s/vm-data/networking/%s' %
                                    (dom_id, mac))
        data = json.loads(xsread)
        if data["label"] == "public":
            this_vif = "vif%s.0" % dom_id
            phys_dev = "eth0"
        else:
            this_vif = "vif%s.1" % dom_id
            phys_dev = "eth1"

        if vif == this_vif:
            vif_ofport = novalib.execute_get_output('/usr/bin/ovs-vsctl',
                                    'get', 'Interface', vif, 'ofport')
            phys_ofport = novalib.execute_get_output('/usr/bin/ovs-vsctl',
                                    'get', 'Interface', phys_dev, 'ofport')

            params = dict(VIF_NAME=vif,
                          MAC=data['mac'],
                          OF_PORT=vif_ofport,
                          PHYS_PORT=phys_ofport)

            ovs = OvsFlow(bridge, params)

            if command == 'offline':
                # I haven't found a way to clear only IPv4 or IPv6 rules.
                ovs.clear_flows(vif_ofport)

            if command == 'online':
                if net_type in ('ipv4', 'all') and 'ips' in data:
                    for ip4 in data['ips']:
                        ovs.params.update({'IPV4_ADDR': ip4['ip']})
                        apply_ovs_ipv4_flows(ovs, bridge, params)
                if net_type in ('ipv6', 'all') and 'ip6s' in data:
                    for ip6 in data['ip6s']:
                        mac_eui64 = netaddr.EUI(data['mac']).eui64()
                        link_local = str(mac_eui64.ipv6_link_local())
                        ovs.params.update({'IPV6_LINK_LOCAL_ADDR': link_local})
                        ovs.params.update({'IPV6_GLOBAL_ADDR': ip6['ip']})
                        apply_ovs_ipv6_flows(ovs, bridge, params) 
Example 80
Project: ngo-addons-backport   Author: camptocamp   File: main.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def image(self, req, model, id, field, **kw):
        last_update = '__last_update'
        Model = req.session.model(model)
        headers = [('Content-Type', 'image/png')]
        etag = req.httprequest.headers.get('If-None-Match')
        hashed_session = hashlib.md5(req.session_id).hexdigest()
        id = None if not id else simplejson.loads(id)
        if type(id) is list:
            id = id[0] # m2o
        if etag:
            if not id and hashed_session == etag:
                return werkzeug.wrappers.Response(status=304)
            else:
                date = Model.read([id], [last_update], req.context)[0].get(last_update)
                if hashlib.md5(date).hexdigest() == etag:
                    return werkzeug.wrappers.Response(status=304)

        retag = hashed_session
        try:
            if not id:
                res = Model.default_get([field], req.context).get(field)
                image_base64 = res
            else:
                res = Model.read([id], [last_update, field], req.context)[0]
                retag = hashlib.md5(res.get(last_update)).hexdigest()
                image_base64 = res.get(field)

            if kw.get('resize'):
                resize = kw.get('resize').split(',')
                if len(resize) == 2 and int(resize[0]) and int(resize[1]):
                    width = int(resize[0])
                    height = int(resize[1])
                    # resize maximum 500*500
                    if width > 500: width = 500
                    if height > 500: height = 500
                    image_base64 = openerp.tools.image_resize_image(base64_source=image_base64, size=(width, height), encoding='base64', filetype='PNG')

            image_data = base64.b64decode(image_base64)

        except (TypeError, xmlrpclib.Fault):
            image_data = self.placeholder(req)
        headers.append(('ETag', retag))
        headers.append(('Content-Length', len(image_data)))
        try:
            ncache = int(kw.get('cache'))
            headers.append(('Cache-Control', 'no-cache' if ncache == 0 else 'max-age=%s' % (ncache)))
        except:
            pass
        return req.make_response(image_data, headers)