Esempio n. 1
0
    def _check_status_code(status_code):
        """Method to test that the request went as expected.

        Parameters
        ----------
        status_code: int
            status code return by the request (requests.status_code)

        Exception
        ---------
        ZenodoException:
            Raise exception if the request ended with a problem

        .. note:
            If the error is a Server conncetion problem,
            the exception is not raised (problem with the test in other hand)
        """
        # Test that everything went as expected
        if status_code < 400:
            logger.debug('Request succeed '
                         'with status code: {}'.format(status_code))
            return status_code

        if status_code >= 500:
            message = 'Server connection failed ' \
                      'with error: {}'.format(status_code)
            logger.error(message)
            raise ZenodoException(message)

        if status_code >= 400:
            message = 'Request failed ' \
                      'with error: {}'.format(status_code)
            logger.error(message)
            raise ZenodoException(message)
 def send_email(self, email_content):
     send_email_notification(self.gmail_user,
                             self.gmail_password,
                             self.target_email,
                             email_content,
                             self.email_subject)
     logger.debug('Email sent for subject = {}, content = {}'.format(self.email_subject, email_content))
Esempio n. 3
0
    def publish(self):
        """Method which will publish the deposition linked with the id.

        .. warning:

            After publishing it is not possible to delete anything.

        Exception
        ---------
        ZenodoException
            raise if token not define (token = None) or
            if connection return status >= 400
        """
        # Test if token was defined
        self._verify_token()

        publish_url = (self.depositions_url +
                       '/{}/actions/publish'.format(self.deposition_id))
        request = requests.post(publish_url,
                                params={'access_token': self.token})

        self.status_code = request.status_code
        self._check_status_code(self.status_code)

        # Test that everything went as expected
        if self.status_code == 202:
            logger.info('Deposition id: {}'.format(self.deposition_id))
            logger.debug('Status code: {}'.format(self.status_code))
            return
Esempio n. 4
0
def greet_user(message):
  """ Send the standard greetings to a user. """
  user = message['user']
  logger.debug("greeting user %s", user)

  response = slack_client.api_call("chat.postEphemeral",
    link_names = True,
    user = user, channel=message['channel'], text=WELCOME_MSG)
Esempio n. 5
0
    def delete(self, _id=None):
        """Method to delete deposition.

        Parameters
        ----------
        _id: int
            deposition id of the record to delete

        .. note::
            it worked only if it is not publish.

        Exception
        ---------
        ZenodoException
            raise if token not define (token = None) or if connection
            return status >= 400
        """
        # Test if token was defined
        self._verify_token()

        # Use provided if if not None. If not provided use self.deposition_id

        if _id is not None:
            self.deposition_id = _id

        # Create the request url
        request_url = (self.depositions_url + '/{}'.format(self.deposition_id))

        logger.info('Delete url: {}'.format(request_url))
        try:
            request = requests.delete(request_url,
                                      params={'access_token': self.token})
            self.status_code = request.status_code
            logger.debug('Status code: {}'.format(self.status_code))
            if self.status_code >= 400:
                raise ZenodoException
        except ZenodoException:
            message = 'Request_url does not exist or bad token. ' \
                      'Error: {}'.format(self.status_code)
            logger.error(message)
            raise ZenodoException(message)
Esempio n. 6
0
    def get_deposition_id(self):
        """Method to obtain the deposition id need to upload documents to Zenodo

        Attributes
        ----------
        deposition_id: int
            Deposition id gave by Zenodo deposition api to be used to upload
            files and metadata.

        Exception
        ---------
        ZenodoException
            raise if token not define (token = None) or if connection
            return status >= 400
        """
        headers = {'Content-Type': 'application/json'}

        # Test if Token defined and access zenodo to test the token if exist
        self._verify_token()

        request = requests.post(self.depositions_url,
                                params={'access_token': self.token},
                                json={},
                                headers=headers)
        self.status_code = request.status_code
        logger.debug('Status code: {}'.format(self.status_code))
        logger.debug('deposition url: {}'.format(self.depositions_url))

        # Test that the request succeed
        if self.status_code >= 400:
            message = ('Deposition id not obtain, '
                       'error: {}'.format(self.status_code))
            logger.error(message)
            raise ZenodoException(message)
        else:
            self.deposition_id = request.json()['id']
            logger.info('Deposition id: {}'.format(self.deposition_id))
            logger.info('Deposition url: {}'.format(self.deposition_id))
Esempio n. 7
0
    def connection(self):
        """Method to test that connection with Zenodo website is working.

        Exception
        ---------
        ZenodoException
            raise if token not define (token = None) or if connection
            return status >= 400
        """
        # Test if Token defined and access zenodo to test the token if exist
        self._verify_token()

        request = requests.get(self.depositions_url,
                               params={'access_token': self.token})
        self.status_code = request.status_code
        logger.debug('Status code: {}'.format(self.status_code))

        # Raise exception if Error from Zenodo (status >= 400)
        if self.status_code >= 400:
            message = 'Access token not accepted by Zenodo. ' \
                      'Error: {}'.format(self.status_code)
            logger.error(message)
            self.token = None
            raise ZenodoException(message)
Esempio n. 8
0
# coding=utf-8
"""
@author: shenke
@project: c3d
@file: test.py
@date: 2021/4/20
@description: 
"""

import os
import sys

root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if sys.path[0] != root_path:
    sys.path.insert(0, root_path)

from conf import logger
import torch

if __name__ == '__main__':
    logger.info("Info")
    logger.debug(sys.path)

    x = torch.empty(5, 3)
    print(x)
def run_monitoring_tool():
    email_sender = AlertEmailSender(c.MAIL.GMAIL_USERNAME,
                                    c.MAIL.GMAIL_PASSWORD,
                                    c.MAIL.NOTIFICATION_EMAIL,
                                    c.MAIL.EMAIL_SUBJECT)

    # part online - offline
    addr = c.BITCOIN_WALLET_PUBLIC_ID
    nice_hash_client = NiceHashClient(addr)
    polling_interval_sec = 60  # 1 minute
    rig_names_to_monitor = c.RIG_HOSTNAMES
    previous_rig_statuses = [True] * len(rig_names_to_monitor)  # initial statuses
    rig_statuses = list(previous_rig_statuses)

    # part balance
    interval_between_balance_reporting_sec = 60 * 60 * 4  # in seconds
    last_balance_reporting_time = 0

    while True:
        logger.debug('run_monitoring_tool() - RUNNING')
        try:
            # PART ONLINE - OFFLINE INSPECTION
            rig_names, speeds, up_time_minutes, locations, algo_ids = nice_hash_client.get_mining_rigs()
            connected_rig_names = set(rig_names)

            for i, rig_name_to_monitor in enumerate(rig_names_to_monitor):
                if rig_name_to_monitor not in connected_rig_names:
                    logger.debug('{} is down.'.format(rig_name_to_monitor))
                    rig_statuses[i] = False
                    if previous_rig_statuses[i] is True:
                        email_sender.send_email(email_content='[{}] host is down. Please check.'.format(
                            rig_name_to_monitor))
                else:
                    logger.debug('{} is connected.'.format(rig_name_to_monitor))
                    rig_statuses[i] = True
                    if previous_rig_statuses[i] is False:
                        email_sender.send_email(email_content='[{}] host successfully connected.'.format(
                            rig_name_to_monitor))

            previous_rig_statuses = list(rig_statuses)

            # PART BALANCE
            if (time() - last_balance_reporting_time) > interval_between_balance_reporting_sec:
                ref_fiat_currencies = c.REFERENCE_FIAT_CURRENCY
                if ',' in ref_fiat_currencies:
                    ref_fiat_currencies = ref_fiat_currencies.split(',')
                else:
                    ref_fiat_currencies = [ref_fiat_currencies]

                unpaid_balance_btc = nice_hash_client.get_unpaid_balance_btc()
                unpaid_balance_fiat_list = list()
                for ref_fiat_currency in ref_fiat_currencies:
                    price_for_one_btc_in_fiat_currency = get_btc_usd_rate(ref_fiat_currency)
                    if price_for_one_btc_in_fiat_currency is None:
                        price_for_one_btc_in_fiat_currency = -1.0
                    unpaid_balance_fiat = unpaid_balance_btc * price_for_one_btc_in_fiat_currency
                    unpaid_balance_fiat_list.append(unpaid_balance_fiat)

                d = ', '.join(
                    ['{0:.2f} {1}'.format(u, v) for (u, v) in zip(unpaid_balance_fiat_list, ref_fiat_currencies)])
                d = 'Your unpaid balance is now {0:.8f} BTC ({1} approx).'.format(unpaid_balance_btc, d)
                email_sender.send_email(email_content=d)
                last_balance_reporting_time = time()

        except Exception as e:
            logger.error(e)
        logger.debug('Going to sleep for {} seconds.'.format(polling_interval_sec))
        sleep(polling_interval_sec)