Example #1
0
def get_delta_samples(metering,pom,meter_list,meters_used,periodic_counts,meters_ids,reden_br,id_price,tenant):
    delta_list={}
    delta_list[reden_br]=[None]*5
    for i in range(len(meters_used)):
        status,sample_list=ceilometer_api.get_meter_samples(str(meters_used[i]),metering,pom,False,meter_list,False,"")
        logger.info('In periodic: Getting meter samples')
        if status:
            print '--------------------------------------------------------------------------------------------------------------------------' 
            for j in range(len(sample_list)):     
                print "Resource id: " + str(sample_list[j]["resource-id"]) 
                print "Counter volume: "+ str(sample_list[j]["counter-volume"]) 
                print "Timestamp: " + str(sample_list[j]["timestamp"])
          
                datetime1=str(sample_list[j]["timestamp"]).split("T")
                
                #list with a list of the metered data from every count for each separate meter thats used in the pricing function
                periodic_counts[i].append(sample_list[j]["counter-volume"])

                #calculate the difference between the metered data from each count for every meter used in the pricing function
                delta=periodic_counts[i][reden_br]-periodic_counts[i][reden_br-1]
                print "Delta: " +str(delta)
                
                delta_list[reden_br][i]=delta
                user=sample_list[j]["user-id"]
                
                #get the row count; if its first entry-id=0; else get the last id and increment it by one
                cursor = conn.execute("SELECT max(ID)  from METERS_COUNTER")
                row_count=conn.execute("SELECT COUNT(*) from METERS_COUNTER ")
                result=row_count.fetchone()
                number_of_rows=result[0]

                if number_of_rows==0:
                    id_last=1
                    conn.execute("INSERT INTO METERS_COUNTER (ID,METER_ID,METER_NAME,USER_ID,RESOURCE_ID,COUNTER_VOLUME,UNIT,TIMESTAMP,TENANT_ID) \
                          VALUES ("+str(id_last)+", '"+ str(meters_ids[i]) +"', '"+ str(meters_used[i]) +"','" + str(sample_list[j]["user-id"]) +" ','"+ str(sample_list[j]["resource-id"]) +"' ,' "+ str(sample_list[j]["counter-volume"])+"' ,' "+ str(sample_list[j]["counter-unit"]) +"' ,' "+ str(datetime1[0])+" "+str(datetime1[1])+"' ,' "+tenant+" ')")
                else:
                    id_last = cursor.fetchone()[0]+1
                    conn.execute("INSERT INTO METERS_COUNTER (ID,METER_ID,METER_NAME,USER_ID,RESOURCE_ID,COUNTER_VOLUME,UNIT,TIMESTAMP,TENANT_ID) \
                            VALUES ("+str(id_last)+",' "+ str(meters_ids[i]) +"', '"+ str(meters_used[i]) +"','" + str(sample_list[j]["user-id"]) +" ','"+ str(sample_list[j]["resource-id"]) +"' ,' "+ str(sample_list[j]["counter-volume"])+"' ,' "+ str(sample_list[j]["counter-unit"]) +"' ,' "+ str(datetime1[0])+" "+str(datetime1[1])+"' ,' "+tenant+" ')")                   

                conn.commit()
                logger.info('Insert data in meters_counter ')     
        
    date_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    conn.execute("INSERT INTO UDR(USER_ID,TIMESTAMP,PRICING_FUNC_ID,PARAM1,PARAM2,PARAM3,PARAM4,PARAM5) \
           VALUES ( '"+ str(user) +"', '"+str(date_time)+"', '"+str(id_price)+"', '"+ str(delta_list[reden_br][0]) +"','" +str(delta_list[reden_br][1]) +"','" +str(delta_list[reden_br][2]) +"','" + str(delta_list[reden_br][3]) +" ','"+ str(delta_list[reden_br][4]) +" ')")        
    reden_br+=1      
    conn.commit() 
    return status                 
Example #2
0
def main(argv):
    print "Hello There. This is a simple test application making a test API call to OpenStack"
    auth_uri = 'http://160.85.4.64:5000' #internal test-setup, replace it with your own value
    status, token_data = keystone_api.get_token_v2(auth_uri)
    if status:
        print 'The authentication was successful, below are the data we got:'
        print '--------------------------------------------------------------------------------------------------------'
        print '%1s %32s %2s %64s %1s' % ('|', 'key', '|', 'value', '|')
        print '--------------------------------------------------------------------------------------------------------'
        for key, value in token_data.iteritems():
            if key not in {'token-id'}:
                print '%1s %32s %2s %64s %1s' % ('|', key, '|', value, '|')
        print '--------------------------------------------------------------------------------------------------------'
        print 'The authentication token is: ', token_data["token-id"]

    else:
        print "Authentication was not successful."
    if status:
        status, server_list = compute_api.get_server_list(token_data["token-id"], token_data["nova"])

        if status:
            print "The list of servers are printed next."
            print server_list
        status, meter_list = ceilometer_api.get_meter_list(token_data["token-id"], token_data["ceilometer"])
        if status:
            print "The list of available meters are printed next."
            print '--------------------------------------------------------------------------------------------------------------------------'
            print '%1s %16s %2s %10s %2s %10s %2s %70s %1s' % ('|','meter-name', '|', 'meter-type', '|', 'meter-unit', '|', 'meter-id', '|')
            print '--------------------------------------------------------------------------------------------------------------------------'
            for i in range(len(meter_list)):
                print '%1s %16s %2s %10s %2s %10s %2s %70s %1s' % ('|', meter_list[i]["meter-name"], '|', meter_list[i]["meter-type"], '|', meter_list[i]["meter-unit"], '|', meter_list[i]["meter-id"].strip(), '|')
            print '--------------------------------------------------------------------------------------------------------------------------'

            
            meter_name=raw_input("Enter meter name: ")
            st,stat_list=ceilometer_api.meter_statistics(meter_name, token_data["ceilometer"],token_data["token-id"],meter_list)
            if status:
                print "The statistics for your meters is printed next."
                print '--------------------------------------------------------------------------------------------------------------------------'
            
                for i in range(len(stat_list)):
                    print "Average: " + str(stat_list[i]["average"]) 
                    print "Count: " + str(stat_list[i]["count"])
                    print "Duration: "+ str(stat_list[i]["duration"]) 
                    print "Duration end: " + str(stat_list[i]["duration-end"]) 
                    print "Duration start: "+ str(stat_list[i]["duration-start"]) 
                    print "Max: " + str(stat_list[i]["max"])
                    print "Min: " + str(stat_list[i]["min"]) 
                    print "Period: " + str(stat_list[i]["period"]) 
                    print "Period end: " + str(stat_list[i]["period-end"]) 
                    print "Period start: " + str(stat_list[i]["period-start"]) 
                    print "Sum: " + str(stat_list[i]["sum"]) 
                    print "Unit: " + str(stat_list[i]["unit"]) 
                    print "Group by: " + str(stat_list[i]["group-by"]) 
                print '--------------------------------------------------------------------------------------------------------------------------'
        
            status,sample_list=ceilometer_api.get_meter_samples(meter_name, token_data["ceilometer"],token_data["token-id"],True,meter_list,False)
            if status:
                print '--------------------------------------------------------------------------------------------------------------------------'
                print "The samples for your meter are printed next."
                print '--------------------------------------------------------------------------------------------------------------------------'
            
                for i in range(len(sample_list)):
                    print "Counter name: " + str(sample_list[i]["counter-name"]) 
                    print "Counter unit: " + str(sample_list[i]["counter-unit"])
                    print "Counter volume: "+ str(sample_list[i]["counter-volume"]) 
                    print "Counter type: " + str(sample_list[i]["counter-type"]) 
                    print "Message id: "+ str(sample_list[i]["message-id"]) 
                    print "Project id: " + str(sample_list[i]["project-id"])
                    print "Resource id: " + str(sample_list[i]["resource-id"]) 
                    print "Resource metadata: " 

                    print sample_list[i]["resource-metadata"]
                    print "Source: " + str(sample_list[i]["source"]) 
                    print "Timestamp: " + str(sample_list[i]["timestamp"]) 
                    print "User ID: " + str(sample_list[i]["user-id"]) 
                    print '--------------------------------------------------------------------------------------------------------------------------'    

            status,resources_list=ceilometer_api.get_resources(token_data["ceilometer"], token_data["token-id"],True)
            if status:
                print '--------------------------------------------------------------------------------------------------------------------------'
                print "The resources for your meter are printed next."
                print '--------------------------------------------------------------------------------------------------------------------------'
            
                for i in range(len(resources_list)):
                    print "Resource id: " + str(resources_list[i]["resource-id"])
                    print "Links: " 
                    for j in range(len(resources_list[i]["links"])):
                        print "Href: " + str(resources_list[i]["links"][j]["href"])
                        print "Rel: " + str(resources_list[i]["links"][j]["rel"])
                    print "Project id: " + str(resources_list[i]["project-id"])       
                    print "Resource metadata: " 
                    print resources_list[i]["metadata"]
                    #print "Source: " + str(resources_list[i]["source"]) 
                    
                    print "User ID: " + str(resources_list[i]["user-id"]) 
                    print '--------------------------------------------------------------------------------------------------------------------------'         
  
            resource_id=raw_input("Enter resource id: ")
            status,resources_list=ceilometer_api.get_resources_by_id(token_data["ceilometer"], token_data["token-id"],resource_id)
            if status:
                print '--------------------------------------------------------------------------------------------------------------------------'
                print "The resources for your meter are printed next."
                print '--------------------------------------------------------------------------------------------------------------------------'
            
                for i in range(len(resources_list)):
                    print "Resource id: " + str(resources_list[i]["resource-id"])
                    print "Links: " 
                    for j in range(len(resources_list[i]["links"])):
                        print "Href: " + str(resources_list[i]["links"][j]["href"])
                        print "Rel: " + str(resources_list[i]["links"][j]["rel"])
                        print "Project id: " + str(resources_list[i]["project-id"])
                 
                        print "Resource metadata: " 
                        print resources_list[i]["metadata"]
                        #print "Source: " + str(resources_list[i]["source"]) 
                        #print "First sample timestamp: " + str(resources_list[i]["first-sample-timestamp"]) 
                        #print "Last sample timestamp: " + str(resources_list[i]["last-sample-timestamp"]) 
                        print "User ID: " + str(resources_list[i]["user-id"]) 
                        print '--------------------------------------------------------------------------------------------------------------------------'         
              
    
    return True
def main(argv):
    print "Hello There. This is a simple test pricing function."
    auth_uri = 'http://160.85.4.64:5000' #internal test-setup, replace it with your own value
    status, token_data = keystone_api.get_token_v3(auth_uri)
    if status:
        print 'The authentication was successful.'
        print '--------------------------------------------------------------------------------------------------------'
        print 'The authentication token is: ', token_data["token-id"]
        pom=token_data["token-id"]
        logger.info('Authentication was successful')
    else:
        print "Authentication was not successful."
        logger.info('Authentication was not successful')
    if status:
        status, meter_list = ceilometer_api.get_meter_list(pom, token_data["metering"])
        if status:
            print "The list of available meters are printed next."
            print '--------------------------------------------------------------------------------------------------------------------------'
            print '%1s %16s %2s %10s %2s %10s %2s %70s %1s' % ('|','meter-name', '|', 'meter-type', '|', 'meter-unit', '|', 'meter-id', '|')
            print '--------------------------------------------------------------------------------------------------------------------------'
            for i in range(len(meter_list)):
                print '%1s %16s %2s %10s %2s %10s %2s %70s %1s' % ('|', meter_list[i]["meter-name"], '|', meter_list[i]["meter-type"], '|', meter_list[i]["meter-unit"], '|', meter_list[i]["meter-id"].strip(), '|')
            print '--------------------------------------------------------------------------------------------------------------------------'
 
            #user defined price function; usage of white space for parsing the data
            price=0
            price_def=raw_input("Define the pricing function. Use only the meters from above and numbers as arguments. Use the following signs: '+' for sum, '-' for substraction, '*' for multiplying, '/' for division or '%' for percentage. Use whitespace in between. ")
            price_def=price_def.split(" ")
            if len(price_def)>9:
                print "You can use only 5 parameters"
                logger.warn('Pricing function not properly defined')
                price_def=raw_input("Define the pricing function. Use only the meters from above and numbers as arguments. Use the following signs: '+' for sum, '-' for substraction, '*' for multiplying, '/' for division or '%' for percentage. Use whitespace in between. ")            
            
            meters_used=[None]
            
            for i in range(len(price_def)):
                j=0
                while j<len(meter_list):
                    if price_def[i]==meter_list[j]["meter-name"]:
                        meters_used.append(price_def[i])
                        print "Enter query arguments."
                        status,sample_list=ceilometer_api.get_meter_samples(price_def[i],token_data["metering"],pom,True,meter_list)
                        logger.info('Getting meter samples')
                        if sample_list==[]:
                            price_def[i]=str(0)

                        #replace the meter name with the metered data
                        for n,m in enumerate(price_def):
                            if m==price_def[i]:
                                for k in range(len(sample_list)):
                                    price_def[n]=str(sample_list[k]["counter-volume"])                                 
                        break
                    else:
                        j=j+1
                       
            
            status_ret=True 
            
            for i in range(len(price_def)):
                if i==0:   
                     if is_number(price_def[i]):    
                         price=price+float(price_def[i]) 
                                  
                     else:
                         status_ret=False  
                if i%2!=0:
                    if price_def[i] in ["+","-","*","/","%"]:
   
                            #check if every other parameter is a number and the parameters in between math signs
                            if is_number(price_def[i+1]):
                                 x=float(price_def[i+1])
                                
                            else:
                                status_ret=False
                                break
                            
                            if price_def[i]=="+":
                                price=price+x
                            if price_def[i]=="-": 
                                price=price-x
                            if price_def[i]=="*":
                                price=price*x
                            if price_def[i]=="/":
                                if x!=0:
                                    price=price/x
                                else:
                                    print "Division by zero."
                                    logger.warn('Division by zero')
                                    status_ret=False
                            if price_def[i]=="%":
                                price=price*x/100.0
                                print price
                    else:
                        status_ret=False
                else:
                    continue
            if status_ret==True:
                print "The price value is: " + str(price)
                logger.info('Calculated price is: %s',price)
            else:
                print "Error. Poorly defined pricing function."
                logger.warn('Pricing function not properly defined')
        return status_ret,meters_used
def main(argv):
    print "Hello There. This is a simple test application making a test API call to OpenStack"
    auth_uri = 'http://160.85.4.64:5000'  #internal test-setup, replace it with your own value
    status, token_data = keystone_api.get_token_v3(auth_uri, False)
    if status:
        print 'The authentication was successful, below are the data we got:'
        print '--------------------------------------------------------------------------------------------------------'
        print '%1s %32s %2s %64s %1s' % ('|', 'key', '|', 'value', '|')
        print '--------------------------------------------------------------------------------------------------------'
        for key, value in token_data.iteritems():
            if key not in {'token_id'}:
                print '%1s %32s %2s %64s %1s' % ('|', key, '|', value, '|')
        print '--------------------------------------------------------------------------------------------------------'
        print 'The authentication token is: ', token_data["token_id"]
        pom = token_data["token_id"]

    else:
        print "Authentication was not successful."
    if status:
        status, tenant_list = keystone_api.get_list_tenants(pom, auth_uri)
        status, user_list = keystone_api.get_users_per_tenant(
            pom, auth_uri, '4e9c4e1b93124cdba2a930e98eb26ede')
        for i in range(len(user_list)):
            print '%20s %20s' % (user_list[i]["user_id"],
                                 user_list[i]["user_name"])

        #status, server_list = compute_api.get_server_list(token_data["token-id"], token_data["computev3"])
        #if status:
        #   print "The list of servers are printed next."
        #   print server_list
        status, meter_list = ceilometer_api.get_meter_list(
            pom, token_data["metering"])
        total_price = periodic.daily_count("2014-02-26", 1,
                                           "323936522894416b903d3528fa971537")
        if status:
            print "The list of available meters are printed next."
            print '--------------------------------------------------------------------------------------------------------------------------'
            print '%1s %16s %2s %10s %2s %10s %2s %40s %1s %70s' % (
                '|', 'meter-name', '|', 'meter-type', '|', 'meter-unit', '|',
                'meter-id', '|', 'resource-id')
            print '--------------------------------------------------------------------------------------------------------------------------'
            for i in range(len(meter_list)):
                print '%1s %16s %2s %10s %2s %10s %2s %40s %1s %70s' % (
                    '|', meter_list[i]["meter-name"], '|',
                    meter_list[i]["meter-type"], '|',
                    meter_list[i]["meter-unit"], '|',
                    meter_list[i]["meter-id"].strip(), '|',
                    meter_list[i]["resource-id"])
            print '--------------------------------------------------------------------------------------------------------------------------'

        meter_name = raw_input("Enter meter name: ")

        st, stat_list = ceilometer_api.meter_statistics(
            meter_name, token_data["metering"], pom, meter_list, False)
        if st:
            print '--------------------------------------------------------------------------------------------------------------------------'
            print "The statistics for your meters is printed next."
            print '--------------------------------------------------------------------------------------------------------------------------'

            for i in range(len(stat_list)):
                print "Average: " + str(stat_list[i]["average"])
                print "Count: " + str(stat_list[i]["count"])
                print "Duration: " + str(stat_list[i]["duration"])
                print "Duration end: " + str(stat_list[i]["duration-end"])
                print "Duration start: " + str(stat_list[i]["duration-start"])
                print "Max: " + str(stat_list[i]["max"])
                print "Min: " + str(stat_list[i]["min"])
                print "Period: " + str(stat_list[i]["period"])
                print "Period end: " + str(stat_list[i]["period-end"])
                print "Period start: " + str(stat_list[i]["period-start"])
                print "Sum: " + str(stat_list[i]["sum"])
                print "Unit: " + str(stat_list[i]["unit"])
                print "Group by: " + str(stat_list[i]["group-by"])
                print '--------------------------------------------------------------------------------------------------------------------------'
            print '--------------------------------------------------------------------------------------------------------------------------'

        print "Query initialization for meter samples function."
        status, sample_list = ceilometer_api.get_meter_samples(
            meter_name, token_data["metering"], pom, True, meter_list, False,
            "")
        if status:
            print '--------------------------------------------------------------------------------------------------------------------------'
            print "The samples for your meter are printed next."
            print '--------------------------------------------------------------------------------------------------------------------------'

            for i in range(len(sample_list)):
                print "Counter name: " + str(sample_list[i]["counter-name"])
                print "Counter unit: " + str(sample_list[i]["counter-unit"])
                print "Counter volume: " + str(
                    sample_list[i]["counter-volume"])
                print "Counter type: " + str(sample_list[i]["counter-type"])
                print "Message id: " + str(sample_list[i]["message-id"])
                print "Project id: " + str(sample_list[i]["project-id"])
                print "Resource id: " + str(sample_list[i]["resource-id"])
                print "Resource metadata: "
                print sample_list[i]["resource-metadata"]
                print "Source: " + str(sample_list[i]["source"])
                print "Timestamp: " + str(sample_list[i]["timestamp"])
                print "User ID: " + str(sample_list[i]["user-id"])
                print '--------------------------------------------------------------------------------------------------------------------------'
            print '--------------------------------------------------------------------------------------------------------------------------'

        print "Query initialization for get resources function."
        status, resources_list = ceilometer_api.get_resources(
            token_data["metering"], pom, True)
        if status:
            print '--------------------------------------------------------------------------------------------------------------------------'
            print "The resources for your meter are printed next."
            print '--------------------------------------------------------------------------------------------------------------------------'

            for i in range(len(resources_list)):
                print "Resource id: " + str(resources_list[i]["resource-id"])
                print "Links: "
                for j in range(len(resources_list[i]["links"])):
                    print "Href: " + str(resources_list[i]["links"][j]["href"])
                    print "Rel: " + str(resources_list[i]["links"][j]["rel"])
                print "Project id: " + str(resources_list[i]["project-id"])

                print "Resource metadata: "
                print resources_list[i]["metadata"]
                #print "Source: " + str(resources_list[i]["source"])

                print "User ID: " + str(resources_list[i]["user-id"])
                print '--------------------------------------------------------------------------------------------------------------------------'

        print "Query initialization for get resources by id function."
        resource_id = raw_input("Enter resource id: ")
        status, resources_list = ceilometer_api.get_resources_by_id(
            token_data["metering"], pom, resource_id)

        if status:
            print '--------------------------------------------------------------------------------------------------------------------------'
            print "The resources for your meter are printed next."
            print '--------------------------------------------------------------------------------------------------------------------------'

            for i in range(len(resources_list)):
                print "Resource id: " + str(resources_list[i]["resource-id"])
                print "Links: "
                for j in range(len(resources_list[i]["links"])):
                    print "Href: " + str(resources_list[i]["links"][j]["href"])
                    print "Rel: " + str(resources_list[i]["links"][j]["rel"])
                print "Project id: " + str(resources_list[i]["project-id"])

                print "Resource metadata: "
                print resources_list[i]["metadata"]
                #print "Source: " + str(resources_list[i]["source"])
                #print "First sample timestamp: " + str(resources_list[i]["first-sample-timestamp"])
                #print "Last sample timestamp: " + str(resources_list[i]["last-sample-timestamp"])

                print "User ID: " + str(resources_list[i]["user-id"])
                print '--------------------------------------------------------------------------------------------------------------------------'

    return True
Example #5
0
def pricing(metering,meter_list,pom,input_p):     
    """

    Method for defining the pricing function.
    
    Args:
        metering(string): The api endpoint for the ceilometer service.
        pom(string): X-Auth-token.
        meter_list: List with the available meters.              
        input_p: Flag indicating whether we want to define the pricing function or use the previous one already defined.
      
    Returns:
        bool: True if successful, False otherwise.
        list: List of the meters used in the pricing function.
        list: List of the meter's ids.
        string: The user input_p for the pricing function.
        float: The price.
      
    """                         
    price=0
    if input_p==None:
        price_def=raw_input("Define the pricing function. Use only the meters from above and numbers as arguments. Use the following signs: '+' for sum, '-' for substraction, '*' for multiplying, '/' for division or '%' for percentage. Use whitespace in between. ")
        price_def=price_def.split(" ")
        if len(price_def)>9:
            print "You can use only 5 parameters"
            logger.warn('More than 5 parameters used')
            price_def=raw_input("Define the pricing function. Use only the meters from above and numbers as arguments. Use the following signs: '+' for sum, '-' for substraction, '*' for multiplying, '/' for division or '%' for percentage. Use whitespace in between. ")
        input_p=price_def[:]
    else:
        price_def=input_p
    meters_used=[]
    meters_ids=[]
            
    for i in range(len(price_def)):
        j=0
        while j<len(meter_list):
            if price_def[i]==meter_list[j]["meter-name"]:
                meters_used.append(price_def[i])
                meters_ids.append(meter_list[j]["meter-id"])
                status,sample_list=ceilometer_api.get_meter_samples(price_def[i],metering,pom,False,meter_list,False,"")
                logger.info('In pricing: Getting meter samples')
                if sample_list==[]:
                    price_def[i]=str(0)

                        
                for n,m in enumerate(price_def):
                    if m==price_def[i]:
                        for k in range(len(sample_list)):
                            price_def[n]=str(sample_list[k]["counter-volume"]) 
                                                                  
                break
            else:
                j=j+1
                       
            
    status_ret=True 
            
    for i in range(len(price_def)):
        if i==0:   
            if is_number(price_def[i]):    
                price=price+float(price_def[i]) 
                                  
            else:
                status_ret=False  
        if i%2!=0:
            if price_def[i] in ["+","-","*","/","%"]:
                if is_number(price_def[i+1]):
                    x=float(price_def[i+1])
                else:
                    status_ret=False
                    break
                if price_def[i]=="+":
                    price=price+x
                if price_def[i]=="-": 
                    price=price-x
                if price_def[i]=="*":
                    price=price*x
                if price_def[i]=="/":
                    if x!=0:
                        price=price/x
                    else:
                        print "Division by zero."
                        logger.warn('Division by zero')
                        status_ret=False
                if price_def[i]=="%":
                    price=price*x/100.0
            else:
                status_ret=False
        else:
            continue
    if status_ret==True:
        print "The price value is: " + str(price)
        logger.info('Price is %s', price)
    else:
        print "Error. Poorly defined pricing function."
        logger.warn('Not properly defined pricing function')
                
    return status_ret,meters_used,meters_ids,input_p,price
def main(argv):
    print "Hello There. This is a simple test application making a test API call to OpenStack"
    auth_uri = 'http://160.85.4.64:5000' #internal test-setup, replace it with your own value
    status, token_data = keystone_api.get_token_v3(auth_uri,False)
    if status:
        print 'The authentication was successful, below are the data we got:'
        print '--------------------------------------------------------------------------------------------------------'
        print '%1s %32s %2s %64s %1s' % ('|', 'key', '|', 'value', '|')
        print '--------------------------------------------------------------------------------------------------------'
        for key, value in token_data.iteritems():
            if key not in {'token_id'}:
                print '%1s %32s %2s %64s %1s' % ('|', key, '|', value, '|')
        print '--------------------------------------------------------------------------------------------------------'
        print 'The authentication token is: ', token_data["token_id"]
        pom=token_data["token_id"]

    else:
        print "Authentication was not successful."
    if status:
        status,tenant_list=keystone_api.get_list_tenants(pom,auth_uri)
        status,user_list=keystone_api.get_users_per_tenant(pom,auth_uri,'4e9c4e1b93124cdba2a930e98eb26ede')
        for i in range(len(user_list)):
            print '%20s %20s' %(user_list[i]["user_id"], user_list[i]["user_name"])
            
        #status, server_list = compute_api.get_server_list(token_data["token-id"], token_data["computev3"])
        #if status:
         #   print "The list of servers are printed next."
         #   print server_list
        status, meter_list = ceilometer_api.get_meter_list(pom, token_data["metering"])
        total_price=periodic.daily_count("2014-02-26",1, "323936522894416b903d3528fa971537")
        if status:
            print "The list of available meters are printed next."
            print '--------------------------------------------------------------------------------------------------------------------------'
            print '%1s %16s %2s %10s %2s %10s %2s %40s %1s %70s' % ('|','meter-name', '|', 'meter-type', '|', 'meter-unit', '|', 'meter-id', '|','resource-id')
            print '--------------------------------------------------------------------------------------------------------------------------'
            for i in range(len(meter_list)):
                print '%1s %16s %2s %10s %2s %10s %2s %40s %1s %70s' % ('|', meter_list[i]["meter-name"], '|', meter_list[i]["meter-type"], '|', meter_list[i]["meter-unit"], '|', meter_list[i]["meter-id"].strip(), '|',meter_list[i]["resource-id"])
            print '--------------------------------------------------------------------------------------------------------------------------'
 
        meter_name=raw_input("Enter meter name: ")

        st,stat_list=ceilometer_api.meter_statistics(meter_name, token_data["metering"],pom,meter_list,False)
        if st:
            print '--------------------------------------------------------------------------------------------------------------------------'
            print "The statistics for your meters is printed next."
            print '--------------------------------------------------------------------------------------------------------------------------'
            
            for i in range(len(stat_list)):
                print "Average: " + str(stat_list[i]["average"]) 
                print "Count: " + str(stat_list[i]["count"])
                print "Duration: "+ str(stat_list[i]["duration"]) 
                print "Duration end: " + str(stat_list[i]["duration-end"]) 
                print "Duration start: "+ str(stat_list[i]["duration-start"]) 
                print "Max: " + str(stat_list[i]["max"])
                print "Min: " + str(stat_list[i]["min"]) 
                print "Period: " + str(stat_list[i]["period"]) 
                print "Period end: " + str(stat_list[i]["period-end"]) 
                print "Period start: " + str(stat_list[i]["period-start"]) 
                print "Sum: " + str(stat_list[i]["sum"]) 
                print "Unit: " + str(stat_list[i]["unit"]) 
                print "Group by: " + str(stat_list[i]["group-by"]) 
                print '--------------------------------------------------------------------------------------------------------------------------'         
            print '--------------------------------------------------------------------------------------------------------------------------'
        
        print "Query initialization for meter samples function."
        status,sample_list=ceilometer_api.get_meter_samples(meter_name,token_data["metering"],pom,True,meter_list,False,"")
        if status:
            print '--------------------------------------------------------------------------------------------------------------------------'
            print "The samples for your meter are printed next."
            print '--------------------------------------------------------------------------------------------------------------------------'
            
            for i in range(len(sample_list)):
                print "Counter name: " + str(sample_list[i]["counter-name"]) 
                print "Counter unit: " + str(sample_list[i]["counter-unit"])
                print "Counter volume: "+ str(sample_list[i]["counter-volume"]) 
                print "Counter type: " + str(sample_list[i]["counter-type"]) 
                print "Message id: "+ str(sample_list[i]["message-id"]) 
                print "Project id: " + str(sample_list[i]["project-id"])
                print "Resource id: " + str(sample_list[i]["resource-id"]) 
                print "Resource metadata: " 
                print sample_list[i]["resource-metadata"]
                print "Source: " + str(sample_list[i]["source"]) 
                print "Timestamp: " + str(sample_list[i]["timestamp"]) 
                print "User ID: " + str(sample_list[i]["user-id"]) 
                print '--------------------------------------------------------------------------------------------------------------------------'         
            print '--------------------------------------------------------------------------------------------------------------------------'
        
        print "Query initialization for get resources function."
        status,resources_list=ceilometer_api.get_resources(token_data["metering"], pom,True)
        if status:
            print '--------------------------------------------------------------------------------------------------------------------------'
            print "The resources for your meter are printed next."
            print '--------------------------------------------------------------------------------------------------------------------------'
            
            for i in range(len(resources_list)):
                print "Resource id: " + str(resources_list[i]["resource-id"])
                print "Links: " 
                for j in range(len(resources_list[i]["links"])):
                    print "Href: " + str(resources_list[i]["links"][j]["href"])
                    print "Rel: " + str(resources_list[i]["links"][j]["rel"])
                print "Project id: " + str(resources_list[i]["project-id"])
                 
                print "Resource metadata: " 
                print resources_list[i]["metadata"]
                #print "Source: " + str(resources_list[i]["source"]) 

                print "User ID: " + str(resources_list[i]["user-id"]) 
                print '--------------------------------------------------------------------------------------------------------------------------'         
        
        print "Query initialization for get resources by id function."    
        resource_id=raw_input("Enter resource id: ")
        status,resources_list=ceilometer_api.get_resources_by_id(token_data["metering"], pom,resource_id)

        if status:
            print '--------------------------------------------------------------------------------------------------------------------------'
            print "The resources for your meter are printed next."
            print '--------------------------------------------------------------------------------------------------------------------------'
            
            for i in range(len(resources_list)):
                print "Resource id: " + str(resources_list[i]["resource-id"])
                print "Links: " 
                for j in range(len(resources_list[i]["links"])):
                    print "Href: " + str(resources_list[i]["links"][j]["href"])
                    print "Rel: " + str(resources_list[i]["links"][j]["rel"])
                print "Project id: " + str(resources_list[i]["project-id"])
                 
                print "Resource metadata: " 
                print resources_list[i]["metadata"]
                #print "Source: " + str(resources_list[i]["source"]) 
                #print "First sample timestamp: " + str(resources_list[i]["first-sample-timestamp"]) 
                #print "Last sample timestamp: " + str(resources_list[i]["last-sample-timestamp"]) 

                print "User ID: " + str(resources_list[i]["user-id"]) 
                print '--------------------------------------------------------------------------------------------------------------------------'         
        
        
    return True
Example #7
0
 def test_sample(self):              
     status,sample_list=ceilometer_api.get_meter_samples("network",self.metering,self.pom.token_id,False,self.meter_list)       
     for i in range(len(sample_list)):
         self.assertEqual(str(sample_list[i]["counter-unit"]),"network")
         self.assertEqual(str(sample_list[i]["counter-type"]),"gauge")
Example #8
0
def main(argv):
    print "Hello There. This is a simple test application making a test API call to OpenStack"
    auth_uri = 'http://160.85.4.64:5000'  #internal test-setup, replace it with your own value
    status, token_data = keystone_api.get_token_v2(auth_uri)
    if status:
        print 'The authentication was successful, below are the data we got:'
        print '--------------------------------------------------------------------------------------------------------'
        print '%1s %32s %2s %64s %1s' % ('|', 'key', '|', 'value', '|')
        print '--------------------------------------------------------------------------------------------------------'
        for key, value in token_data.iteritems():
            if key not in {'token-id'}:
                print '%1s %32s %2s %64s %1s' % ('|', key, '|', value, '|')
        print '--------------------------------------------------------------------------------------------------------'
        print 'The authentication token is: ', token_data["token-id"]

    else:
        print "Authentication was not successful."
    if status:
        status, server_list = compute_api.get_server_list(
            token_data["token-id"], token_data["nova"])

        if status:
            print "The list of servers are printed next."
            print server_list
        status, meter_list = ceilometer_api.get_meter_list(
            token_data["token-id"], token_data["ceilometer"])
        if status:
            print "The list of available meters are printed next."
            print '--------------------------------------------------------------------------------------------------------------------------'
            print '%1s %16s %2s %10s %2s %10s %2s %70s %1s' % (
                '|', 'meter-name', '|', 'meter-type', '|', 'meter-unit', '|',
                'meter-id', '|')
            print '--------------------------------------------------------------------------------------------------------------------------'
            for i in range(len(meter_list)):
                print '%1s %16s %2s %10s %2s %10s %2s %70s %1s' % (
                    '|', meter_list[i]["meter-name"], '|',
                    meter_list[i]["meter-type"], '|',
                    meter_list[i]["meter-unit"], '|',
                    meter_list[i]["meter-id"].strip(), '|')
            print '--------------------------------------------------------------------------------------------------------------------------'

            meter_name = raw_input("Enter meter name: ")
            st, stat_list = ceilometer_api.meter_statistics(
                meter_name, token_data["ceilometer"], token_data["token-id"],
                meter_list)
            if status:
                print "The statistics for your meters is printed next."
                print '--------------------------------------------------------------------------------------------------------------------------'

                for i in range(len(stat_list)):
                    print "Average: " + str(stat_list[i]["average"])
                    print "Count: " + str(stat_list[i]["count"])
                    print "Duration: " + str(stat_list[i]["duration"])
                    print "Duration end: " + str(stat_list[i]["duration-end"])
                    print "Duration start: " + str(
                        stat_list[i]["duration-start"])
                    print "Max: " + str(stat_list[i]["max"])
                    print "Min: " + str(stat_list[i]["min"])
                    print "Period: " + str(stat_list[i]["period"])
                    print "Period end: " + str(stat_list[i]["period-end"])
                    print "Period start: " + str(stat_list[i]["period-start"])
                    print "Sum: " + str(stat_list[i]["sum"])
                    print "Unit: " + str(stat_list[i]["unit"])
                    print "Group by: " + str(stat_list[i]["group-by"])
                print '--------------------------------------------------------------------------------------------------------------------------'

            status, sample_list = ceilometer_api.get_meter_samples(
                meter_name, token_data["ceilometer"], token_data["token-id"],
                True, meter_list, False)
            if status:
                print '--------------------------------------------------------------------------------------------------------------------------'
                print "The samples for your meter are printed next."
                print '--------------------------------------------------------------------------------------------------------------------------'

                for i in range(len(sample_list)):
                    print "Counter name: " + str(
                        sample_list[i]["counter-name"])
                    print "Counter unit: " + str(
                        sample_list[i]["counter-unit"])
                    print "Counter volume: " + str(
                        sample_list[i]["counter-volume"])
                    print "Counter type: " + str(
                        sample_list[i]["counter-type"])
                    print "Message id: " + str(sample_list[i]["message-id"])
                    print "Project id: " + str(sample_list[i]["project-id"])
                    print "Resource id: " + str(sample_list[i]["resource-id"])
                    print "Resource metadata: "

                    print sample_list[i]["resource-metadata"]
                    print "Source: " + str(sample_list[i]["source"])
                    print "Timestamp: " + str(sample_list[i]["timestamp"])
                    print "User ID: " + str(sample_list[i]["user-id"])
                    print '--------------------------------------------------------------------------------------------------------------------------'

            status, resources_list = ceilometer_api.get_resources(
                token_data["ceilometer"], token_data["token-id"], True)
            if status:
                print '--------------------------------------------------------------------------------------------------------------------------'
                print "The resources for your meter are printed next."
                print '--------------------------------------------------------------------------------------------------------------------------'

                for i in range(len(resources_list)):
                    print "Resource id: " + str(
                        resources_list[i]["resource-id"])
                    print "Links: "
                    for j in range(len(resources_list[i]["links"])):
                        print "Href: " + str(
                            resources_list[i]["links"][j]["href"])
                        print "Rel: " + str(
                            resources_list[i]["links"][j]["rel"])
                    print "Project id: " + str(resources_list[i]["project-id"])
                    print "Resource metadata: "
                    print resources_list[i]["metadata"]
                    #print "Source: " + str(resources_list[i]["source"])

                    print "User ID: " + str(resources_list[i]["user-id"])
                    print '--------------------------------------------------------------------------------------------------------------------------'

            resource_id = raw_input("Enter resource id: ")
            status, resources_list = ceilometer_api.get_resources_by_id(
                token_data["ceilometer"], token_data["token-id"], resource_id)
            if status:
                print '--------------------------------------------------------------------------------------------------------------------------'
                print "The resources for your meter are printed next."
                print '--------------------------------------------------------------------------------------------------------------------------'

                for i in range(len(resources_list)):
                    print "Resource id: " + str(
                        resources_list[i]["resource-id"])
                    print "Links: "
                    for j in range(len(resources_list[i]["links"])):
                        print "Href: " + str(
                            resources_list[i]["links"][j]["href"])
                        print "Rel: " + str(
                            resources_list[i]["links"][j]["rel"])
                        print "Project id: " + str(
                            resources_list[i]["project-id"])

                        print "Resource metadata: "
                        print resources_list[i]["metadata"]
                        #print "Source: " + str(resources_list[i]["source"])
                        #print "First sample timestamp: " + str(resources_list[i]["first-sample-timestamp"])
                        #print "Last sample timestamp: " + str(resources_list[i]["last-sample-timestamp"])
                        print "User ID: " + str(resources_list[i]["user-id"])
                        print '--------------------------------------------------------------------------------------------------------------------------'

    return True
Example #9
0
def pricing(metering, meter_list, pom, input_p):
    """

    Method for defining the pricing function.
    
    Args:
        metering(string): The api endpoint for the ceilometer service.
        pom(string): X-Auth-token.
        meter_list: List with the available meters.              
        input_p: Flag indicating whether we want to define the pricing function or use the previous one already defined.
      
    Returns:
        bool: True if successful, False otherwise.
        list: List of the meters used in the pricing function.
        list: List of the meter's ids.
        string: The user input_p for the pricing function.
        float: The price.
      
    """
    price = 0
    if input_p == None:
        price_def = raw_input(
            "Define the pricing function. Use only the meters from above and numbers as arguments. Use the following signs: '+' for sum, '-' for substraction, '*' for multiplying, '/' for division or '%' for percentage. Use whitespace in between. "
        )
        price_def = price_def.split(" ")
        if len(price_def) > 9:
            print "You can use only 5 parameters"
            logger.warn('More than 5 parameters used')
            price_def = raw_input(
                "Define the pricing function. Use only the meters from above and numbers as arguments. Use the following signs: '+' for sum, '-' for substraction, '*' for multiplying, '/' for division or '%' for percentage. Use whitespace in between. "
            )
        input_p = price_def[:]
    else:
        price_def = input_p
    meters_used = []
    meters_ids = []

    for i in range(len(price_def)):
        j = 0
        while j < len(meter_list):
            if price_def[i] == meter_list[j]["meter-name"]:
                meters_used.append(price_def[i])
                meters_ids.append(meter_list[j]["meter-id"])
                status, sample_list = ceilometer_api.get_meter_samples(
                    price_def[i], metering, pom, False, meter_list, False, "")
                logger.info('In pricing: Getting meter samples')
                if sample_list == []:
                    price_def[i] = str(0)

                for n, m in enumerate(price_def):
                    if m == price_def[i]:
                        for k in range(len(sample_list)):
                            price_def[n] = str(
                                sample_list[k]["counter-volume"])

                break
            else:
                j = j + 1

    status_ret = True

    for i in range(len(price_def)):
        if i == 0:
            if is_number(price_def[i]):
                price = price + float(price_def[i])

            else:
                status_ret = False
        if i % 2 != 0:
            if price_def[i] in ["+", "-", "*", "/", "%"]:
                if is_number(price_def[i + 1]):
                    x = float(price_def[i + 1])
                else:
                    status_ret = False
                    break
                if price_def[i] == "+":
                    price = price + x
                if price_def[i] == "-":
                    price = price - x
                if price_def[i] == "*":
                    price = price * x
                if price_def[i] == "/":
                    if x != 0:
                        price = price / x
                    else:
                        print "Division by zero."
                        logger.warn('Division by zero')
                        status_ret = False
                if price_def[i] == "%":
                    price = price * x / 100.0
            else:
                status_ret = False
        else:
            continue
    if status_ret == True:
        print "The price value is: " + str(price)
        logger.info('Price is %s', price)
    else:
        print "Error. Poorly defined pricing function."
        logger.warn('Not properly defined pricing function')

    return status_ret, meters_used, meters_ids, input_p, price
Example #10
0
def get_delta_samples(metering, pom, meter_list, meters_used, periodic_counts,
                      meters_ids, reden_br, id_price, tenant):
    delta_list = {}
    delta_list[reden_br] = [None] * 5
    for i in range(len(meters_used)):
        status, sample_list = ceilometer_api.get_meter_samples(
            str(meters_used[i]), metering, pom, False, meter_list, False, "")
        logger.info('In periodic: Getting meter samples')
        if status:
            print '--------------------------------------------------------------------------------------------------------------------------'
            for j in range(len(sample_list)):
                print "Resource id: " + str(sample_list[j]["resource-id"])
                print "Counter volume: " + str(
                    sample_list[j]["counter-volume"])
                print "Timestamp: " + str(sample_list[j]["timestamp"])

                datetime1 = str(sample_list[j]["timestamp"]).split("T")

                #list with a list of the metered data from every count for each separate meter thats used in the pricing function
                periodic_counts[i].append(sample_list[j]["counter-volume"])

                #calculate the difference between the metered data from each count for every meter used in the pricing function
                delta = periodic_counts[i][reden_br] - periodic_counts[i][
                    reden_br - 1]
                print "Delta: " + str(delta)

                delta_list[reden_br][i] = delta
                user = sample_list[j]["user-id"]

                #get the row count; if its first entry-id=0; else get the last id and increment it by one
                cursor = conn.execute("SELECT max(ID)  from METERS_COUNTER")
                row_count = conn.execute(
                    "SELECT COUNT(*) from METERS_COUNTER ")
                result = row_count.fetchone()
                number_of_rows = result[0]

                if number_of_rows == 0:
                    id_last = 1
                    conn.execute(
                        "INSERT INTO METERS_COUNTER (ID,METER_ID,METER_NAME,USER_ID,RESOURCE_ID,COUNTER_VOLUME,UNIT,TIMESTAMP,TENANT_ID) \
                          VALUES (" + str(id_last) + ", '" +
                        str(meters_ids[i]) + "', '" + str(meters_used[i]) +
                        "','" + str(sample_list[j]["user-id"]) + " ','" +
                        str(sample_list[j]["resource-id"]) + "' ,' " +
                        str(sample_list[j]["counter-volume"]) + "' ,' " +
                        str(sample_list[j]["counter-unit"]) + "' ,' " +
                        str(datetime1[0]) + " " + str(datetime1[1]) + "' ,' " +
                        tenant + " ')")
                else:
                    id_last = cursor.fetchone()[0] + 1
                    conn.execute(
                        "INSERT INTO METERS_COUNTER (ID,METER_ID,METER_NAME,USER_ID,RESOURCE_ID,COUNTER_VOLUME,UNIT,TIMESTAMP,TENANT_ID) \
                            VALUES (" + str(id_last) + ",' " +
                        str(meters_ids[i]) + "', '" + str(meters_used[i]) +
                        "','" + str(sample_list[j]["user-id"]) + " ','" +
                        str(sample_list[j]["resource-id"]) + "' ,' " +
                        str(sample_list[j]["counter-volume"]) + "' ,' " +
                        str(sample_list[j]["counter-unit"]) + "' ,' " +
                        str(datetime1[0]) + " " + str(datetime1[1]) + "' ,' " +
                        tenant + " ')")

                conn.commit()
                logger.info('Insert data in meters_counter ')

    date_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    conn.execute(
        "INSERT INTO UDR(USER_ID,TIMESTAMP,PRICING_FUNC_ID,PARAM1,PARAM2,PARAM3,PARAM4,PARAM5) \
           VALUES ( '" + str(user) + "', '" + str(date_time) + "', '" +
        str(id_price) + "', '" + str(delta_list[reden_br][0]) + "','" +
        str(delta_list[reden_br][1]) + "','" + str(delta_list[reden_br][2]) +
        "','" + str(delta_list[reden_br][3]) + " ','" +
        str(delta_list[reden_br][4]) + " ')")
    reden_br += 1
    conn.commit()
    return status