示例#1
0
 def setUp(self):
     # logger.reset()
     logger.suppress_print = True
     if os.path.isfile(logfile):
         os.remove(logfile)
     #ensure logging is allowed
     plebnet_settings.get_instance().active_logger("1")
示例#2
0
def purchase_choice_vpn(config):
    provider = plebnet_settings.get_instance().vpn_host()

    provider_instance = get_vpn_providers()[provider](child_account())

    # no need to generate new child config

    wallet = TriblerWallet(
        plebnet_settings.get_instance().wallets_testnet_created())
    c = cloudomate_providers['vpn'][provider]

    configurations = c.get_options()
    # option is assumbed to be the first vpn provider option
    option = configurations[0]

    transaction_hash = provider_instance.purchase(wallet, option)

    if not transaction_hash:
        logger.warning("Failed to purchase vpn")
        return plebnet_settings.FAILURE
    if False:
        logger.warning("Insufficient funds to purchase server")
        return plebnet_settings.UNKNOWN

    config.get('bought').append(
        (provider, transaction_hash, config.get('child_index')))
    config.get('transactions').append(transaction_hash)
    config.save()

    return plebnet_settings.SUCCESS
示例#3
0
def purchase_choice_vpn(config):
    provider = plebnet_settings.get_instance().vpn_host()

    provider_instance = get_vpn_providers()[provider](child_account())

    # no need to generate new child config

    wallet = TriblerWallet(plebnet_settings.get_instance().wallets_testnet_created())
    c = cloudomate_providers['vpn'][provider]

    configurations = c.get_options()
    # option is assumbed to be the first vpn provider option
    option = configurations[0]

    try:
        transaction_hash = provider_instance.purchase(wallet, option)
    except:
        title = "Failed to purchase vpn: %s" % sys.exc_info()[0]
        body = traceback.format_exc()
        logger.error(title)
        logger.error(body)
        git_issuer.handle_error(title, body)
        git_issuer.handle_error("Failed to purchase server", sys.exc_info()[0], ['crash'])
        return plebnet_settings.FAILURE

    if not transaction_hash:
        logger.warning("VPN probably purchased, but transaction hash not returned")

    config.get('bought').append((provider, option, transaction_hash, config.get('child_index')))
    config.get('transactions').append(transaction_hash)
    config.save()

    return plebnet_settings.SUCCESS
示例#4
0
    def __init__(self):
        logger.log("preparing an IRC connection")

        # load required settings once
        settings = plebnet_settings.get_instance()
        self.server = settings.irc_server()
        self.timeout = settings.irc_timeout()
        self.channel = settings.irc_channel()
        self.port = settings.irc_port()

        if settings.irc_nick() == settings.irc_nick_def():
            settings.irc_nick(settings.irc_nick_def() +
                              str(random.randint(1000, 10000)))

        self.nick = settings.irc_nick()
        self.ident = "plebber"
        self.gecos = "Plebbot version 2.14"

        self.irc = None
        self.init_time = time.time()
        self.last_beat = time.time()

        # prep reply functions
        self.responses = {}
        self.add_response("alive", self.msg_alive)
        self.add_response("error", self.msg_error)
        self.add_response("host", self.msg_host)
        self.add_response("init", self.msg_init)
        self.add_response("joke", self.msg_joke)

        # start running the IRC server
        logger.log("start running an IRC connection on " + self.server + " " +
                   self.channel)
        self.run()
示例#5
0
    def handle_line(self, line):
        """
        This method handles a line received from the IRC server.
        :param line: The line to process
        :type line: String
        """

        line = str.rstrip(line)
        words = str.split(line)

        # playing ping-pong with a key (words[1])
        if words[0] == "PING":
            st = "PONG %s" % words[1]
            self.send(st)

        # server status 433 --> nickname is already in use, so we chose a new one
        elif line.find("433 * " + self.nick) != -1:
            settings = plebnet_settings.get_instance()
            settings.irc_nick(settings.irc_nick_def() +
                              str(random.randint(1000, 10000)))
            self.nick = settings.irc_nick()

            self.send("NICK %s" % self.nick)
            self.send("USER %s %s %s : %s" %
                      (self.nick, self.nick, self.nick, self.gecos))

        # server status 376 and 422 means ready to join a channel
        elif line.find("376 " + self.nick) != -1 or line.find("422 " +
                                                              self.nick) != -1:
            st = "JOIN " + self.channel
            self.send(st)

        # handle incoming messages
        elif len(words) > 3 and words[3] in self.responses:
            self.responses[words[3]]()
示例#6
0
def send(title, trace_back=' ', labels=['bug']):
    settings = plebnet_settings.get_instance()
    if not settings.github_active(): return

    username = settings.github_username()
    password = settings.github_password()
    repo_owner = settings.github_owner()
    repo_name = settings.github_repo()

    full_link, gist_link = create_gist(username, password)

    body = \
        "An error occurred at a plebbot agent\n\r" \
        "\n\r" \
        "The plebnet nick is %s \r\n"\
        "More info can be added here later on\n\r" \
        "\n\r" \
        "\n\r" \
        "The trackback of the error:\n\r" \
        "\n\r" \
        "%s\n\r" \
        "\n\r" \
        "The log file can be found [here](%s)\n\r" \
        "\n\r" \
        "More details regarding this post can be found [here](%s)\n\r" \
        "\n\r" \
        "\n\r" \
        "Good luck fixing this!"

    body = body % (settings.irc_nick, trace_back, gist_link, full_link)

    create_issue(username, password, repo_owner, repo_name, title, body, labels)
示例#7
0
def create_gist(username, password):
    try:
        # the log files
        filename = plebnet_settings.get_instance().logger_file()
        content = open(filename, 'r').read()
        # Our url to create issues via POST
        url = 'https://api.github.com/gists'
        # Create an authenticated session to create the issue
        session = requests.Session()
        session.auth = (username, password)
        # Create our issue
        gist = {
            "description": "the description for this gist",
            "public": True,
            "files": {
                "logfile.txt": {
                    "content": content
                }
            }
        }

        r = session.post(url, json.dumps(gist))
        if r.status_code == 201:
            logger.success('Successfully created gist')
        else:
            logger.warning('Could not create gist')
            logger.log(r.content, 'Response:')
        return r.json()['url'], r.json()['html_url']

    except:
        logger.error(sys.exc_info()[0], "git_issuer gist")
        logger.error(traceback.format_exc())
示例#8
0
    def place_offer(self, mb_amount, chosen_est_price, timeout, config):
        """
        Sells the received MB amount for the chosen estimated price on the Tribler market.
        :param mb_amount: Amount of MB to sell
        :param config: config
        :param timeout: timeout of the offer to place
        :param chosen_est_price: Target amount of BTC to receive
        :return: success of offer placement
        """
        if chosen_est_price == 0 or mb_amount == 0:
            return False
        config.bump_offer_date()

        coin = 'TBTC' if plebnet_settings.get_instance().wallets_testnet(
        ) else 'BTC'

        config.set('last_offer', {coin: chosen_est_price, 'MB': mb_amount})

        if coin == 'TBTC':
            return market_controller.put_ask(
                first_asset_amount=mb_amount,
                first_asset_type='MB',
                second_asset_amount=btc_to_satoshi(chosen_est_price),
                second_asset_type=coin,
                timeout=timeout)
        return market_controller.put_bid(
            first_asset_amount=btc_to_satoshi(chosen_est_price),
            first_asset_type=coin,
            second_asset_amount=mb_amount,
            second_asset_type='MB',
            timeout=timeout)
示例#9
0
 def msg_general(self):
     data = {
         'host': dna.get_host(),
         'vpn': vpn_is_running(),
         'tree': dna.get_tree(),
         'exitnode': plebnet_settings.get_instance().tribler_exitnode()
     }
     self.send_msg("general: %s" % data)
示例#10
0
def save_all_currency():
    """
    Sends leftover MB and (T)BTC to the predefined global wallet
    """
    wallet = wallet_controller.TriblerWallet(
        plebnet_settings.get_instance().wallets_testnet_created())
    wallet.pay(settings.wallets_btc_global(),
               satoshi_to_btc(wallet.get_balance()))
示例#11
0
def save_info_vpn(child_index):
    """
    Stores the child vpn information
    :param location: where to store the config
    :return:
    """
    vpn = get_vpn_providers()[plebnet_settings.get_instance().vpn_host()](
        child_account())
    info = vpn.get_configuration()
    prefix = plebnet_settings.get_instance().vpn_child_prefix()

    dir = path.expanduser(plebnet_settings.get_instance().vpn_config_path())
    credentials = prefix + str(
        child_index) + plebnet_settings.get_instance().vpn_credentials_name()

    ovpn = prefix + str(
        child_index) + plebnet_settings.get_instance().vpn_config_name()

    # the .ovpn file contains the line auth-user-pass so that it knows which credentials file to use
    # when the child config and credentials are passed to create-child, it is placed on the server as "own"
    # so the reference to "own" is put in the .ovpn file.
    own_credentials = plebnet_settings.get_instance().vpn_own_prefix() \
                      + plebnet_settings.get_instance().vpn_credentials_name()
    with io.open(path.join(dir, ovpn), 'w', encoding='utf-8') as ovpn_file:
        ovpn_file.write(info.ovpn + '\nauth-user-pass ' + own_credentials)

    # write the ovpn file to vpn dir
    with io.open(path.join(dir, credentials), 'w',
                 encoding='utf-8') as credentials_file:
        credentials_file.writelines([info.username + '\n', info.password])

    print("Saved VPN configuration to " + dir)

    return True
示例#12
0
def _install_server(ip, rootpw, vpn_child_index=None, testnet=False):
    """
    This function starts the actual installation routine.
    :param ip: The ip-address of the remote server
    :type ip: String
    :param rootpw: The root password of the remote server
    :type rootpw: String
    :return: The exit status of the installation
    :rtype: Integer
    """
    settings = setup.get_instance()
    home = settings.plebnet_home()
    script_path = os.path.join(home, "plebnet/clone/create-child.sh")
    logger.log('tot_path: %s' % script_path)

    command = ["bash", script_path, "-i", ip.strip(), "-p", rootpw.strip()]

    # additional VPN arguments
    if vpn_child_index > -1:
        prefix = settings.vpn_child_prefix()

        dir = os.path.expanduser(settings.vpn_config_path())

        # vpn credentials: ~/child_INT_credentials.conf
        credentials = os.path.join(
            dir,
            prefix + str(vpn_child_index) + settings.vpn_credentials_name())
        # vpn credentials destination: own_config.ovpn
        dest_credentials = settings.vpn_own_prefix(
        ) + settings.vpn_credentials_name()

        # vpn config: ~/child_INT_config.ovpn
        ovpn = os.path.join(
            dir, prefix + str(vpn_child_index) + settings.vpn_config_name())
        # vpn config destination: own_credentials.conf
        dest_config = settings.vpn_own_prefix() + settings.vpn_config_name()

        # the current child config is given as arguments, the destination is so that the
        # agent knows it's its own configuration, and not a child's config.
        command += [
            "-conf", ovpn, dest_config, "-cred", credentials, dest_credentials
        ]

    if testnet:
        command.append("-t")

    if settings.tribler_exitnode():
        command.append("-e")

    logger.log("Running %s" % ' '.join(command), '_install_server')
    exitcode = subprocess.call(command, cwd=home)
    if exitcode == 0:
        logger.log("Installation successful")
        return True
    else:
        logger.log("Installation unsuccessful, error code: %s" % exitcode)
        return False
示例#13
0
 def msg_general(self):
     qtable = QTable()
     qtable.read_dictionary()
     data = {
         'host': qtable.self_state.provider,
         'option': qtable.self_state.option,
         'vpn': vpn_is_running(),
         'tree': qtable.tree,
         'exitnode': plebnet_settings.get_instance().tribler_exitnode()
     }
     self.send_msg("general: %s" % data)
 def calculate_price(self, transaction):
     """
     Given a transaction on the market, calculates its price BTC/MB
     :param transaction: Transaction to get price
     :return: price in BTC/MB
     """
     if plebnet_settings.get_instance().wallets_testnet():
         return float(transaction['assets']['second']
                      ['amount']) / transaction['assets']['first']['amount']
     return float(transaction['assets']['first']
                  ['amount']) / transaction['assets']['second']['amount']
示例#15
0
def create_gist(filename=None):
    """
    This method can be used to send a file to github via gist.
    :param filename: the file to send, if left empty, the log file is send
    :type filename: String
    """
    # Only execute if PlebNet is activated
    settings = plebnet_settings.get_instance()
    if not settings.github_active():
        return
    if not filename:
        filename = settings.logger_file()

    try:
        # Collect variables
        username = settings.github_username()
        password = settings.github_password()
        bot_name = settings.irc_nick()

        # Get the log files
        content = open(filename, 'r').read()

        # Our url to create issues via POST
        url = 'https://api.github.com/gists'

        # Create an authenticated session to create the issue
        session = requests.Session()
        session.auth = (username, password)

        # Create our issue
        gist = {
            "description": "The logfile for %s" % bot_name,
            "public": True,
            "files": {
                "logfile.txt": {
                    "content": content
                }
            }
        }
        r = session.post(url, json.dumps(gist))

        # Inform about the results
        if r.status_code == 201:
            logger.success('Successfully created gist')
        else:
            logger.warning('Could not create gist')
            logger.log(r.content, 'Response:')
        return r.json()['url'], r.json()['html_url']

    except:
        logger.error(sys.exc_info()[0], "git_issuer gist")
        logger.error(traceback.format_exc())
        return None, None
示例#16
0
 def create_offer(self, amount_mb, timeout):
     """
     Retrieve the price of the chosen server to buy and make a new offer on the Tribler marketplace.
     :param amount_mb:
     :param timeout: offer to
     :return: None
     """
     if not self.config.get('chosen_provider'):
         return
     wallet = wallet_controller.TriblerWallet(plebnet_settings.get_instance().wallets_testnet_created())
     (provider, option, _) = self.config.get('chosen_provider')
     btc_balance = satoshi_to_btc(wallet.get_balance())
     btc_price = max(self.get_replication_price(provider, option) * self.target_vps_count - btc_balance, 0)
     self.place_offer(amount_mb, btc_price, timeout, self.config)
示例#17
0
def create_issue(title, body, labels):
    """
    This method creates a github issue when called.
    :param title: The title of the issue
    :type title: String
    :param body: The body text of the issue
    :type body: String
    :param labels: The labels which should be attached to the issue
    :type labels: String[]
    """
    # Only execute if PlebNet is activated
    settings = plebnet_settings.get_instance()
    if not settings.github_active(): return

    try:
        # Collect variables
        username = settings.github_username()
        password = settings.github_password()
        repo_owner = settings.github_owner()
        repo_name = settings.github_repo()

        # Our url to create issues via POST
        url = 'https://api.github.com/repos/%s/%s/issues' % (repo_owner,
                                                             repo_name)

        # Create an authenticated session to create the issue
        session = requests.Session()
        session.auth = (username, password)

        # Create our issue
        issue = {'title': title, 'body': body, 'labels': labels}

        # Add the issue to our repository
        r = session.post(url, json.dumps(issue))

        # Inform about the results
        if r.status_code == 201:
            logger.success('Successfully created Issue "%s"' % title)
        else:
            logger.warning('Could not create Issue "%s"' % title)
            logger.log(r.content, 'Response:')
    except:
        logger.error(sys.exc_info()[0], "git_issuer send")
        logger.error(traceback.format_exc())
示例#18
0
    def __init__(self):
        logger.log("preparing an IRC connection")

        # load required settings once
        settings = plebnet_settings.get_instance()
        self.server = settings.irc_server()
        self.timeout = settings.irc_timeout()
        self.channel = settings.irc_channel()
        self.port = settings.irc_port()

        self.nick = settings.irc_nick()
        nick_number = self.nick[len(settings.irc_nick_def()):]
        self.ident = "plebber"
        self.gecos = "Plebbot version 2.15"

        self.irc = None
        self.init_time = time.time()
        self.last_beat = time.time()

        # prep reply functions
        self.responses = {}
        self.add_response("alive", self.msg_alive)
        self.add_response("error", self.msg_error)
        self.add_response("init", self.msg_init)
        self.add_response("joke", self.msg_joke)
        self.add_response("MB_wallet", self.msg_MB_wallet)
        self.add_response("BTC_wallet", self.msg_BTC_wallet)
        self.add_response("TBTC_wallet", self.msg_TBTC_wallet)
        self.add_response("MB_balance", self.msg_MB_balance)
        self.add_response("BTC_balance", self.msg_BTC_balance)
        self.add_response("TBTC_balance", self.msg_TBTC_balance)
        self.add_response("matchmakers", self.msg_match_makers)
        self.add_response("uploaded", self.msg_uploaded)
        self.add_response("downloaded", self.msg_downloaded)
        self.add_response("general", self.msg_general)
        self.add_response("helped", self.msg_helped)
        self.add_response("helped_by", self.msg_helped_by)
        self.add_response("qtables" + str(nick_number), self.msg_qtable)

        # start running the IRC server
        self.init_irc()
        self.run()
示例#19
0
def purchase_choice(config):
    """
    Purchase the cheapest provider in chosen_providers. If buying is successful this provider is
    moved to bought. In any case the provider is removed from choices.
    :param config: config
    :return: plebnet_settings errorcode
    """

    (provider, option, _) = config.get('chosen_provider')
    provider_instance = cloudomate_providers['vps'][provider](child_account())

    wallet = TriblerWallet(
        plebnet_settings.get_instance().wallets_testnet_created())

    vps_option = get_vps_option(provider, option)
    try:
        transaction_hash = provider_instance.purchase(wallet, vps_option)
    except:
        title = "Failed to purchase server: %s" % sys.exc_info()[0]
        body = traceback.format_exc()
        logger.error(title)
        logger.error(body)
        git_issuer.handle_error(title, body)
        git_issuer.handle_error("Failed to purchase server",
                                sys.exc_info()[0], ['crash'])
        return plebnet_settings.FAILURE

    # Cloudomate should throw an exception when purchase fails. The transaction hash is not in fact required,
    # and even when cloudomate fails to return it, the purchase itself could have been successful.
    if not transaction_hash:
        logger.warning(
            "Server probably purchased, but transaction hash not returned")

    config.get('bought').append(
        (provider, option, transaction_hash, config.get('child_index')))
    config.get('transactions').append(transaction_hash)
    config.set('chosen_provider', None)
    config.save()

    return plebnet_settings.SUCCESS
示例#20
0
def check():
    """
    The method is the main function which should run periodically. It controls the behaviour of the agent,
    starting Tribler and buying servers.
    """
    global config, qtable
    global sold_mb_tokens, previous_mb_tokens
    logger.log("Checking PlebNet", log_name)

    # Read general configuration
    if settings.wallets_testnet_created():
        os.environ['TESTNET'] = '1'
    config = PlebNetConfig()
    qtable = QTable()
    qtable.read_dictionary()
    # check if own vpn is installed before continuing
    if not check_vpn_install():
        logger.error("!!! VPN is not installed, child may get banned !!!",
                     "Plebnet Check")

    # Requires time to setup, continue in the next iteration.
    if not check_tribler():
        return

    check_irc()

    if not settings.wallets_initiate_once():
        create_wallet()

    select_provider()

    # if is going to die, move all currency to a wallet
    if config.time_to_expiration() < plebnet_settings.TIME_IN_HOUR:
        save_all_currency()

    # These need a matchmaker, otherwise agent will be stuck waiting.
    if market_controller.has_matchmakers():
        strategies[plebnet_settings.get_instance().strategy_name()]().apply()

    install_vps()
示例#21
0
def purchase_choice(config):
    """
    Purchase the cheapest provider in chosen_providers. If buying is successful this provider is
    moved to bought. In any case the provider is removed from choices.
    :param config: config
    :return: plebnet_settings errorcode
    """

    (provider, option, _) = config.get('chosen_provider')
    provider_instance = cloudomate_providers['vps'][provider](child_account())

    wallet = TriblerWallet(
        plebnet_settings.get_instance().wallets_testnet_created())
    c = cloudomate_providers['vps'][provider]

    configurations = c.get_options()
    option = configurations[option]

    try:
        transaction_hash = provider_instance.purchase(wallet, option)
    except:
        title = "Failed to purchase server: %s" % sys.exc_info()[0]
        body = traceback.format_exc()
        logger.error(title)
        logger.error(body)
        git_issuer.handle_error(title, body)
        git_issuer.handle_error("Failed to purchase server",
                                sys.exc_info()[0], ['crash'])
        return plebnet_settings.FAILURE

    if not transaction_hash:
        return plebnet_settings.FAILURE
    config.get('bought').append(
        (provider, transaction_hash, config.get('child_index')))
    config.get('transactions').append(transaction_hash)
    config.set('chosen_provider', None)
    config.save()

    return plebnet_settings.SUCCESS
示例#22
0
def purchase_choice(config):
    """
    Purchase the cheapest provider in chosen_providers. If buying is successful this provider is moved to bought. In any
    case the provider is removed from choices.
    :param config: config
    :return: success
    """

    (provider, option, _) = config.get('chosen_provider')

    provider_instance = cloudomate_providers['vps'][provider](child_account())
    PlebNetConfig().increment_child_index()
    fake_generator.generate_child_account()

    wallet = TriblerWallet(
        plebnet_settings.get_instance().wallets_testnet_created())
    c = cloudomate_providers['vps'][provider]

    configurations = c.get_options()
    option = configurations[option]

    transaction_hash, _ = provider_instance.purchase(wallet, option)

    if not transaction_hash:
        logger.warning("Failed to purchase server")
        return plebnet_settings.FAILURE
    # TODO: how to spot the difference?
    if False:
        logger.warning("Insufficient funds to purchase server")
        return plebnet_settings.UNKNOWN

    config.get('bought').append(
        (provider, transaction_hash, config.get('child_index') - 1))
    config.get('transactions').append(transaction_hash)
    config.set('chosen_provider', None)
    config.save()

    return plebnet_settings.SUCCESS
示例#23
0
def handle_error(title, trace_back=' ', labels=['bug']):
    """
    This method can be called with information regarding an error. It creates a git issue about it and
    send the log files along.
    :param title: The title of the error
    :type title: String
    :param trace_back: The trace back resulting in the error
    :type trace_back: String
    :param labels: the labels to attach to the issue
    :type labels:
    """
    # only execute if plebnet is activated
    settings = plebnet_settings.get_instance()
    if not settings.github_active(): return

    body = \
        "An error occurred at a plebbot agent\n\r" \
        "\n\r" \
        "The plebnet nick is _%s_ \r\n"\
        "More info can be added here later on\n\r" \
        "\n\r" \
        "\n\r" \
        "The track back of the error:\n\r" \
        "\n\r" \
        "```\n\r" \
        "%s\n\r" \
        "```\n\r" \
        "\n\r" \
        "The log file can be found [here](%s)\n\r" \
        "\n\r" \
        "More details regarding this post can be found [here](%s)\n\r" \
        "\n\r" \
        "\n\r" \
        "Good luck fixing this!"

    full_link, gist_link = create_gist()
    body = body % (settings.irc_nick(), trace_back, gist_link, full_link)
    create_issue(title, body, labels)
示例#24
0
def place_offer(chosen_est_price, config):
    """
    Sell all available MB for the chosen estimated price on the Tribler market.
    :param config: config
    :param chosen_est_price: Target amount of BTC to receive
    :return: success of offer placement
    """
    available_mb = market_controller.get_balance('MB')
    if available_mb == 0:
        logger.log("No MB available")
        return False
    config.bump_offer_date()

    coin = 'TBTC' if plebnet_settings.get_instance().wallets_testnet(
    ) else 'BTC'

    config.set('last_offer', {coin: chosen_est_price, 'MB': available_mb})
    price_per_unit = max(0.0001, chosen_est_price / float(available_mb))
    return market_controller.put_ask(price=price_per_unit,
                                     price_type=coin,
                                     quantity=available_mb,
                                     quantity_type='MB',
                                     timeout=plebnet_settings.TIME_IN_HOUR)
示例#25
0
This file is used to control all dependencies with Tribler.

Other files should never have a direct import from Tribler, as this reduces the maintainability of this code.
If Tribler alters its call methods, this should be the only file which needs to be updated in PlebNet.
"""

import os
import subprocess
import requests

from requests.exceptions import ConnectionError

from plebnet.utilities import logger
from plebnet.settings import plebnet_settings

setup = plebnet_settings.get_instance()


def running():
    """
    Checks if Tribler is running.
    :return: True if twistd.pid exists in /root/tribler
    """
    path = os.path.join(setup.tribler_home(), setup.tribler_pid())
    return os.path.isfile(path)


def start():
    """
    Starts Tribler by using the twistd plugin.
    :return: boolean representing the success of starting Tribler
示例#26
0
 def tearDown(self):
     if os.path.isfile(logfile):
         os.remove(logfile)
     # disable logging for further tests
     plebnet_settings.get_instance().active_logger("0")
示例#27
0
import unittest
import mock
from mock.mock import MagicMock
from appdirs import user_config_dir
import os
import sys
from plebnet.utilities import logger
from plebnet.settings import plebnet_settings

logfile = plebnet_settings.get_instance().logger_file()

msg1 = "this is a log"
msg2 = "this is another log"
msg3 = "this is a nice line"
msg4 = "this is a beautiful line of text"


class TestLogger(unittest.TestCase):
    def setUp(self):
        # logger.reset()
        logger.suppress_print = True
        if os.path.isfile(logfile):
            print(logfile)
            os.remove(logfile)
        #ensure logging is allowed
        plebnet_settings.get_instance().active_logger("1")

    def tearDown(self):
        if os.path.isfile(logfile):
            os.remove(logfile)
        # disable logging for further tests
示例#28
0
def install_available_servers(config, qtable):
    """
    This function checks if any of the bought servers are ready to be installed and installs
    PlebNet on them.
    :param config: The configuration of this Plebbot
    :type config: dict
    :param qtable: The qtable of this Plebbot
    :type qtable: QTable
    :return: None
    :rtype: None
    """
    bought = config.get('bought')
    logger.log("install: %s" % bought, "install_available_servers")

    for bought_item in list(bought):
        [provider, option, transaction_hash, child_index] = bought_item

        # skip vpn providers as they show up as 'bought' as well
        if provider in cloudomate_controller.get_vpn_providers():
            continue

        try:
            provider_class = cloudomate_controller.get_vps_providers()[provider]
            ip = cloudomate_controller.get_ip(provider_class, cloudomate_controller.child_account(child_index))
        except Exception as e:
            logger.log(str(e) + "%s not ready yet" % str(provider), "install_available_servers")
            continue

        if is_valid_ip(ip):
            # VPN configuration, enable tun/tap settings
            if provider_class.TUN_TAP_SETTINGS:
                tun_success = provider_class(cloudomate_controller.child_account(child_index)).enable_tun_tap()
                logger.log("Enabling %s tun/tap: %s"%(provider, tun_success))
                if not cloudomate_controller.save_info_vpn(child_index):
                    logger.log("VPN not ready yet, can't save ovpn config")
                    # continue

            logger.log("Installing child #%s on %s with ip %s" % (child_index, provider, str(ip)))

            account_settings = cloudomate_controller.child_account(child_index)
            rootpw = account_settings.get('server', 'root_password')

            try:
                provider_class(cloudomate_controller.child_account(child_index)).change_root_password(rootpw)
            except Exception as e:
                logger.error("Cannot change root password: %s" % str(e), "install_available_servers")
                continue

            time.sleep(5)

            qtable.create_child_qtable(provider, option, transaction_hash, child_index)

            # Save config before entering possibly long lasting process
            config.get('bought').remove(bought_item)
            config.get('installing').append(bought_item)
            config.save()

            success = _install_server(ip, rootpw, child_index, setup.get_instance().wallets_testnet())

            # Reload config in case install takes a long time
            config.load()
            config.get('installing').remove(bought_item)
            if success:
                config.get('installed').append(bought_item)
            else:
                # Try again next time
                config.get('bought').append(bought_item)
            config.save()

            # Only install one server at a time
            return
        else:
            logger.log("Server not ready")
示例#29
0
def install_available_servers(config, dna):
    """
    This function checks if any of the bought servers are ready to be installed and installs
    PlebNet on them.
    :param config: The configuration of this Plebbot
    :type config: dict
    :param dna: The DNA of this Plebbot
    :type dna: DNA
    :return: None
    :rtype: None
    """
    bought = config.get('bought')
    logger.log("install: %s" % bought, "install_available_servers")

    for provider, transaction_hash, child_index in list(bought):

        # skip vpn providers as they show up as 'bought' as well
        if provider in cloudomate_controller.get_vpn_providers():
            return

        try:
            provider_class = cloudomate_controller.get_vps_providers(
            )[provider]
            ip = cloudomate_controller.get_ip(
                provider_class,
                cloudomate_controller.child_account(child_index))
        except Exception as e:
            logger.log(
                str(e) + "%s not ready yet" % str(provider),
                "install_available_servers")
            return

        if is_valid_ip(ip):

            # VPN configuration, enable tun/tap settings
            if provider_class.TUN_TAP_SETTINGS:
                tun_success = provider_class(
                    cloudomate_controller.child_account(
                        child_index)).enable_tun_tap()
                logger.log("Enabling %s tun/tap: %s" % (provider, tun_success))
                if not cloudomate_controller.save_info_vpn(child_index):
                    logger.log("VPN not ready yet, can't save ovpn config")
                    return

            logger.log("Installing child on %s with ip %s" %
                       (provider, str(ip)))

            account_settings = cloudomate_controller.child_account(child_index)
            rootpw = account_settings.get('server', 'root_password')

            provider_class(cloudomate_controller.child_account(
                child_index)).change_root_password(rootpw)
            time.sleep(5)

            child_tree = dna.get_own_tree() + '.' + str(child_index)

            dna.create_child_dna(provider, child_tree, transaction_hash)

            # Save config before entering possibly long lasting process
            config.save()

            success = _install_server(ip, rootpw, child_index,
                                      setup.get_instance().wallets_testnet())

            # Reload config in case install takes a long time
            config.load()
            config.get('installed').append({provider: success})
            if [provider, transaction_hash,
                    child_index] in config.get('bought'):
                config.get('bought').remove(
                    [provider, transaction_hash, child_index])
            config.save()
        else:
            logger.log("Server not ready")
示例#30
0
 def __init__(self):
     Strategy.__init__(self)
     self.target_vps_count = int(
         plebnet_settings.get_instance().strategy_vps_count())