Exemplo n.º 1
0
def main(prog_name=os.path.basename(sys.argv[0]), args=None):
    """
    Expose core functionality of the code_smell family.

    Args:
        prog_name, program name (str)
        args, arguments to process code smells (array)
    """
    if args is None:
        args = sys.argv[1:]
    parser = create_parser(prog_name)
    args = parser.parse_args(args)

    if args.verbose is None:
        verbose_level = 0
    else:
        verbose_level = args.verbose

    setup_loggers(verbose_level=verbose_level)

    #Define health family functions
    if args.command == 'commit':
        do_commit(args)
    elif args.command == 'list':
        do_list(args)
    else:
        raise HealthException("Invalid command: {}".format(args.command))
Exemplo n.º 2
0
    def _send_request(self,
                      suffix,
                      data=None,
                      content_type=None,
                      auth_user=None,
                      auth_password=None):
        """
        send request to health processor`
        """
        if self._base_url.startswith("http://"):
            url = "{}/{}".format(self._base_url, suffix)
        else:
            url = "http://{}/{}".format(self._base_url, suffix)

        headers = {}
        if auth_user is not None:
            auth_string = "{}:{}".format(auth_user, auth_password)
            b64_string = b64encode(auth_string.encode()).decode()
            auth_header = 'Basic {}'.format(b64_string)
            headers['authorization'] = auth_header

        if content_type is not None:
            headers['Content-Type'] = content_type

        try:
            if data is not None:
                result = requests.post(url, headers=headers, data=data)
            else:
                result = requests.get(url, headers=headers)

            if result.status_code == 404:
                raise HealthException("No such transaction")
            elif not result.ok:
                raise HealthException("Error {}:{}".format(
                    result.status_code, result.reason))

        except requests.ConnectionError as err:
            raise HealthException('Failed to connect to {}:{}'.format(
                url, str(err)))

        except BaseException as err:
            raise HealthException(err)

        return result.text
Exemplo n.º 3
0
def do_commit(args):
    """
    load a set of default code smells.

    Args:
        args (array) arguments
    """
    if args.giturl is None:
        raise HealthException("Missing Commit URL")
    if args.gituser is None:
        raise HealthException("Missing User ID")

    url = _get_url(args)
    keyfile = _get_keyfile(args)
    client = HealthClient(base_url=url, keyfile=keyfile, work_path=HOME)

    response = client.commit(commit_url=args.giturl, github_id=args.gituser)

    print("Response: {}".format(response))
Exemplo n.º 4
0
    def __init__(self, base_url, work_path, keyfile=None):
        self._base_url = base_url
        self._work_path = work_path

        if keyfile is None:
            self._signer = None
            return

        try:
            with open(keyfile) as file_ptr:
                private_key_str = file_ptr.read().strip()
        except OSError as err:
            raise HealthException('Failed to read private key {}: {}'.format(keyfile, str(err)))

        try:
            private_key = Secp256k1PrivateKey.from_hex(private_key_str)
        except ParseError as parser_error:
            raise HealthException('Unable to load private key: {}'.format(str(parser_error)))

        self._signer = CryptoFactory(create_context('secp256k1')).new_signer(private_key)
Exemplo n.º 5
0
def do_commit(args):
    """
    load a set of default code smells.

    Args:
        args (array) arguments
    """
    if args.giturl is None:
        raise HealthException("Missing Commit URL")
    if args.gituser is None:
        raise HealthException("Missing User ID")
    if args.date is None:
        raise HealthException("Missing Commit Date")
    if args.client_key is None:
        raise HealthException("Missing Client Key")

    url = _get_url(args)
    keyfile = _get_keyfile(args)
    client = HealthClient(base_url=url, keyfile=keyfile, work_path=HOME)

    client.commit(commit_url=args.giturl,
                  github_id=args.gituser,
                  commit_date=args.date,
                  client_key=args.client_key)
Exemplo n.º 6
0
def do_list(args):
    """
    list transactions of code smell family

    Args:
        args (array) arguments
    """
    url = _get_url(args)
    keyfile = _get_keyfile(args)
    client = HealthClient(base_url=url, keyfile=keyfile, work_path=HOME)

    transactions = client.list(txn_type=args.type, limit=args.limit)

    if len(transactions) == 0:
        raise HealthException("No transactions found")
    else:
        print(transactions)
Exemplo n.º 7
0
def _get_config_file():
    work_path = os.path.dirname(os.path.dirname(
        os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))

    #identify code_smell family configuration file
    conf_file = work_path + '/etc/.suse'

    if os.path.isfile(conf_file):
        try:
            with open(conf_file) as config:
                raw_config = config.read()
        except IOError as error:
            raise HealthException("Unable to load code smell family configuration file: {}"
                                  .format(error))
    #load toml config into a dict
    toml_config = toml.loads(raw_config)
    return toml_config
Exemplo n.º 8
0
    def code_analysis(self, github_url, github_user):
        """
        send github url to code analysis to generate new health

        Args:
            github_url (str): commit url
            github_user (str): github user id
        """
        #get time
        localtime = time.localtime(time.time())
        txn_time = str(localtime.tm_year) + str(localtime.tm_mon) + str(localtime.tm_mday)
        txn_date = str(txn_time)

        work_path = os.path.dirname(os.path.dirname(
            os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
        sawtooth_home = work_path + "/results"

        #get repo path
        conf_file = work_path + '/etc/.repo'
        try:
            with open(conf_file, 'r') as path:
                repo_path = path.read()
            path.close()
        except IOError as error:
            raise HealthException("Unable to open configuration file {}".format(error))

        repo_path = repo_path.replace('\n', '') + 'CodeAnalysis/SourceMeter_Interface/src/sourceMeterWrapper.py'
        csv_path = subprocess.check_output( ['python', repo_path, github_url, sawtooth_home]).decode('utf-8')
        csv_path = csv_path[csv_path.rfind('OK\n')+4:-4]#check if "OK\n" is in project name or read from file
        #print ("repo path: " + repo_path)
        suse_config = _get_config_file()
        suse_config = suse_config["code_smells"]
        health = calculate_health(toml_config=suse_config, csv_path=csv_path)
        #health = calculate_health(toml_config=suse_config, csv_path="/home/mrwayne/Desktop/Susereum/results/")

        response = self._send_health_txn(
            txn_type='health',
            txn_id=github_user,
            data=str(health),
            state='processed',
            txn_date=txn_date)
        return response
Exemplo n.º 9
0
    def code_analysis(self, github_url, github_user, commit_date, client_key):
        """
        send github url to code analysis to generate new health

        Args:
            github_url (str): commit url
            github_user (str): github user id
        """
        #get time
        txn_date = _get_date()

        #get host ip adress
        process_flag = 1
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        my_ip = s.getsockname()[0]
        s.close()

        if my_ip == client_key[6:].split(':')[0]:
            process_flag = 0

        #if process is zero then check latest health
        #get latest health
        if process_flag == 0:
            result = self._send_request("transactions")
            transactions = {}
            try:
                encoded_entries = yaml.safe_load(result)["data"]
                for entry in encoded_entries:
                    #try to pull the specific transaction, if the format is not right
                    #the transaction corresponds to the consesus family
                    try:
                        transaction_type = base64.b64decode(
                            entry["payload"]).decode().split(',')[0]
                        if transaction_type == "health":
                            transactions[
                                entry["header_signature"]] = base64.b64decode(
                                    entry["payload"])
                            #assuming we got all transactions in order
                            break
                    except:
                        pass
            except BaseException:
                return None

            for entry in transactions:
                previous_commit = transactions[entry].decode().split(',')[4]
                if previous_commit == github_url:
                    #if the commit url of the previous health is equal to the new commit url
                    #then ignore the transaction
                    process_flag == 1
                break

        #we got a new commit, calculate health
        if process_flag == 0:
            work_path = os.path.dirname(
                os.path.dirname(
                    os.path.dirname(os.path.dirname(
                        os.path.realpath(__file__)))))
            sawtooth_home = work_path + "/results"

            #get repo path
            conf_file = work_path + '/etc/.repo'
            try:
                with open(conf_file, 'r') as path:
                    repo_path = path.read()
                path.close()
            except IOError as error:
                raise HealthException(
                    "Unable to open configuration file {}".format(error))

            repo_path = repo_path.replace(
                '\n', ''
            ) + '/CodeAnalysis/SourceMeter_Interface/src/sourceMeterWrapper.py'
            print('CALLING ANLSYIS WITH:',
                  ['python2.7', repo_path, github_url, sawtooth_home])
            subprocess.check_output(
                ['python2.7', repo_path, github_url, sawtooth_home])

            for filename in os.listdir(sawtooth_home):
                csv_path = sawtooth_home + '/' + filename
                break

            try:
                suse_config = _get_config_file()
                suse_config = suse_config["code_smells"]
                health = calculate_health(suse_config=suse_config,
                                          csv_path=csv_path)

                if health > 0:
                    do_suse(url=self._base_url,
                            health=health,
                            github_id=github_user)

                response = self._send_health_txn(txn_type='health',
                                                 txn_id=github_user,
                                                 data=str(health),
                                                 state='processed',
                                                 url=github_url,
                                                 client_key=client_key,
                                                 txn_date=txn_date)
                return response
            except Exception as error:
                return error