Ejemplo n.º 1
0
 def __init__(self, username, password, gateway_id, env_dict, hierarchy,
              boolean_save_json_file):
     dict_configuration_path = utility.get_configuration_path()
     self.json_templates_path = dict_configuration_path[
         "json_templates_path"]
     self.excel_templates_path = dict_configuration_path[
         "excel_templates_path"]
     self.json_files_path = dict_configuration_path["json_files_path"]
     self.excel_files_path = dict_configuration_path["excel_files_path"]
     self.hierarchy_file_path = dict_configuration_path["hierarchy_path"]
     '''SET DATA'''
     self.dict_configuration_path = utility.get_configuration_path
     self.username = username
     self.password = password
     self.hierarchy_name = utility.get_substring(basename(hierarchy),
                                                 stop=".")
     self.hierarchy_path = join(self.hierarchy_file_path,
                                self.hierarchy_name + ".xml")
     self.serial_number, self.match_group_value, self.dict_meters = self.get_data_from_hierarchy(
     )
     self.gateway_id = gateway_id
     self.environment_prefix = env_dict[gateway_id]["environment_prefix"]
     self.match_group_value = self.hierarchy_name.split(
         "_")[1] + "_" + self.match_group_value
     self.dict_meter_template, self.dict_meters_not_found = self.create_dict_meter_template(
     )
Ejemplo n.º 2
0
    def getdict_logs_file(self):
        list_logs_file = utility.create_file_list(self.logs_path, ".json")
        if (list_logs_file != []):
            for logs_file in list_logs_file:
                if (utility.get_substring(logs_file, start="-",
                                          stop=".") == self.hierarchy_name):
                    return utility.read_json_file(
                        join(self.logs_path, logs_file))

            return self.gateway_id + "_" + "thing§"
        else:
            return self.gateway_id + "_" + "thing§"
Ejemplo n.º 3
0
 def create_template_list(self, template):
     try:
         logging.info("creating Template list")
         file_template = utility.read_json_file(
             join(self.json_templates_path, template))
         list_measures = []
         for model in file_template["parameters"]["filter_tag"]:
             if (model["tag"] != "CommunicationCode"):
                 list_measures.append(
                     utility.get_substring(model["tag"], start="."))
         return (list_measures)
     except Exception as e:
         logging.error(e, exc_info=True)
Ejemplo n.º 4
0
def add_file_hierarchy(path_file):
    file_path = basename(path_file)
    if (isfile(path_file)
            and utility.get_substring(file_path, start=".") == "xml"):
        copy(path_file, hierarchy_path)
        return True
    elif (isdir(path_file)):
        list_files = utility.create_file_list(path_file, ".xml")
        for file_hierarchy in list_files:
            copy(join(path_file, file_hierarchy), hierarchy_path)
        return True
    else:
        return False
Ejemplo n.º 5
0
def add_json_template(path_file):
    file_path = basename(path_file)
    if (isfile(path_file)
            and utility.get_substring(file_path, start=".") == "json"):
        copy(path_file, join(json_templates_path))
        utility.refresh_template_configuration()
        return True
    elif (isdir(path_file)):
        list_files = utility.create_file_list(path_file, ".json")
        for file in list_files:
            copy(join(path_file, file), join(json_templates_path))
        utility.add_measures_template(list_files)
        return True
    else:
        return False
Ejemplo n.º 6
0
def get(credentials_g, endpoint, commandId, environmentPrefix, env):
    service = 'execute-api'
    method = 'GET'
    endpoint_g = endpoint + commandId
    host = get_substring(endpoint, start="'https://", stop='/' + env)
    uri = get_substring(endpoint, start=host, stop="") + commandId
    content_type = 'application/json'
    request_parameters = 'index=jobs_' + environmentPrefix + '_%2A'

    dict_cred_g = credentials_g
    region = dict_cred_g['region']
    securitytoken = dict_cred_g['aws_security_token']

    secretkey = dict_cred_g['aws_secret_access_key']
    accesskey = dict_cred_g['aws_access_key_id']

    if accesskey is None or secretkey is None:
        print('No access key is available.')
        sys.exit()

    t = datetime.datetime.utcnow()
    amzdate = t.strftime('%Y%m%dT%H%M%SZ')
    datestamp = t.strftime('%Y%m%d')

    canonical_uri = uri
    canonical_querystring = request_parameters
    canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n'
    signed_headers = 'content-type;host;x-amz-date'
    payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()

    canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash

    algorithm = 'AWS4-HMAC-SHA256'
    credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'

    string_to_sign = algorithm + '\n' + amzdate + '\n' + credential_scope + '\n' + hashlib.sha256(
        canonical_request.encode('utf-8')).hexdigest()

    signing_key = get_signature_key(secretkey, datestamp, region, service)

    signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'),
                         hashlib.sha256).hexdigest()

    authorization_header = algorithm + ' ' + 'Credential=' + accesskey + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature

    headers = {
        'Content-Type': content_type,
        'host': host,
        'x-amz-security-token': securitytoken,
        'x-amz-date': amzdate,
        'Authorization': authorization_header
    }

    request_url = endpoint_g + '?' + canonical_querystring

    response_g = requests.get(request_url, headers=headers)

    if (response_g.status_code == 404):
        return get(credentials_g, endpoint, commandId, environmentPrefix, env)
    elif (response_g.status_code == 403):
        message = binary_to_dict(response_g._content)["message"]
        response = (response_g.status_code, message)
        return response
    elif (response_g.status_code == 400):
        message = str(response_g._content)
        response = (response_g.status_code, message)
        return response
    elif (response_g.status_code == 200 and
          binary_to_dict(response_g._content)["hits"]["max_score"] != None):
        if (binary_to_dict(response_g._content)["hits"]["documents"] != []
                and binary_to_dict(
                    response_g._content)["hits"]["documents"][0]["status"]
                == "SUCCEEDED"):
            message = binary_to_dict(
                response_g._content
            )["hits"]["documents"][0]["statusDetails"]["thing_id"]
        else:
            message = binary_to_dict(
                response_g._content)["hits"]["documents"][0]["status"]
        response = (response_g.status_code, message)
        return response
    else:
        message = "JOB DOESN'T CREATED, YET"
        response = (response_g.status_code, message)
        return response
Ejemplo n.º 7
0
def post(credentials, endpoint, stage, payload):
    service = 'execute-api'
    method = 'POST'
    host = get_substring(endpoint, start="'https://", stop='/' + stage + '/')
    uri = get_substring(endpoint, start=host, stop='')
    content_type = 'application/json'
    dict_credentials = credentials
    region = dict_credentials['region']

    if (dict_credentials['account'] == "iot-mvp-devqual"):
        securitytoken = ''
    else:
        securitytoken = dict_credentials['aws_security_token']

    secretkey = dict_credentials['aws_secret_access_key']
    accesskey = dict_credentials['aws_access_key_id']

    if accesskey is None or secretkey is None:
        print('No access key is available.')
        sys.exit()

    t = datetime.datetime.utcnow()
    amz_date = t.strftime('%Y%m%dT%H%M%SZ')
    date_stamp = t.strftime('%Y%m%d')

    canonical_uri = uri
    canonical_querystring = ''
    canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n'
    signed_headers = 'content-type;host;x-amz-date'
    payload_hash = hashlib.sha256(payload.encode('utf-8')).hexdigest()

    canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash

    algorithm = 'AWS4-HMAC-SHA256'
    credential_scope = date_stamp + '/' + region + '/' + service + '/' + 'aws4_request'

    string_to_sign = algorithm + '\n' + amz_date + '\n' + credential_scope + '\n' + hashlib.sha256(
        canonical_request.encode('utf-8')).hexdigest()

    signing_key = get_signature_key(secretkey, date_stamp, region, service)

    signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'),
                         hashlib.sha256).hexdigest()

    authorization_header = algorithm + ' ' + 'Credential=' + accesskey + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature

    if (dict_credentials["account"] == "iot-mvp-devqual"):

        headers = {
            'Content-Type': content_type,
            'x-amz-date': amz_date,
            'Authorization': authorization_header
        }

    else:
        headers = {
            'Content-Type': content_type,
            'x-amz-date': amz_date,
            'x-amz-security-token': securitytoken,
            'Authorization': authorization_header
        }

    r = requests.post(endpoint, data=payload, headers=headers)
    post_response = (r.status_code, r._content)

    return post_response