# Path: pricing/instance_pricing.py
# class InstancePricing(object):
#     def __init__(self):
#         if not os.path.isfile(INSTANCE_PRICES_FILENAME):
#             self.retrieve_pricing_file()
#         with open(INSTANCE_PRICES_FILENAME, 'r') as infile:
#             pricing = json.load(infile)
#         vers = nav(pricing, 'formatVersion')
#         if vers != "v1.0":
#             raise Exception("Expected version v1.0 but got {}".format(vers))
#         self.products = nav(pricing, 'products')
#         self.terms = nav(pricing, 'terms')
# 
#     def retrieve_pricing_file(self):
#         # http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/price-changes.html
#         OFFERS_URL=urlparse.urljoin(INSTANCE_PRICES_URL_PREFIX, "/offers/v1.0/aws/index.json")
#         offers = requests.get(OFFERS_URL).json()
#         AMAZONEC2_URL = urlparse.urljoin(INSTANCE_PRICES_URL_PREFIX, offers['offers']['AmazonEC2']['currentVersionUrl'])
#         ec2_prices = requests.get(AMAZONEC2_URL).json()
#         with open(INSTANCE_PRICES_FILENAME, 'w') as f:
#             print(json.dumps(ec2_prices), file=f)
# 
#     @memoized
#     def get_spot_pricing(self, ec2, spot_instance_request_id):
#         # inefficient
#         spot_instance_requests = ec2.get_all_spot_instance_requests(request_ids=[spot_instance_request_id])
#         return spot_instance_requests[0].price
#         
#     @memoized
#     def get_ondemand_pricing(self, region, instance_type):
#         def pick_one(d):
#             return d.itervalues().next()
# 
#         location = AWS_REGION_LONG_NAMES[region]
# 
#         (sku,product) = [
#             (sku, nav(product, 'attributes'))
#             for sku,product in self.products.items() 
#             if (nav(product, 'attributes.instanceType')==instance_type and 
#                 nav(product, 'attributes.operatingSystem') == OPERATING_SYSTEM and 
#                 nav(product, 'attributes.location') == location and 
#                 nav(product, 'attributes.tenancy') == TENANCY)
#         ][0]
#         price = float(nav(pick_one(nav(pick_one(self.terms['OnDemand'][sku]), "priceDimensions")), 'pricePerUnit.USD'))
#         return price
# 
# Path: pricing/spot_pricing.py
# class SpotPricing(object):
#     def __init__(self):
#         self.ec2 = boto3.client('ec2')
# 
#     # this is an estimate based on recent prices
#     # http://stackoverflow.com/questions/11780262/calculate-running-cumulative-cost-of-ec2-spot-instance 
#     @memoized
#     def get_spot_instance_pricing(self, instance_type, start_time, end_time, availability_zone, spot_instance_request_id=None):
#         # don't fetch any more since this is an approximation of hourly cost anyway
#         # we can only report the accumulated cost for the time period we examine,
#         # not the total time.
# 
#         max_results = 30
#         result = self.ec2.describe_spot_price_history(InstanceTypes=[instance_type], StartTime=start_time, EndTime=end_time,
#                                                       AvailabilityZone=availability_zone, MaxResults = max_results)
#         total_cost = 0.0
#         total_seconds = (end_time - start_time).total_seconds()
#         total_hours = total_seconds / (60*60)
#         computed_seconds = 0
# 
#         last_time = end_time
#         for price in result["SpotPriceHistory"]:
#             price["SpotPrice"] = float(price["SpotPrice"])
# 
#             available_seconds = (last_time - price["Timestamp"]).total_seconds()
#             remaining_seconds = total_seconds - computed_seconds
#             used_seconds = min(available_seconds, remaining_seconds)
# 
#             total_cost += (price["SpotPrice"] / (60 * 60)) * used_seconds
#             computed_seconds += used_seconds
# 
#             last_time = price["Timestamp"]
# 
#         return float("{0:.3f}".format((total_cost / (computed_seconds / (60.0 * 60.0)))))


import argparse
import boto.ec2
import dateutil
import datetime
import json
from pricing.instance_pricing import InstancePricing
from pricing.spot_pricing import SpotPricing
        return "unknown"
    else:
        return value.replace("<", "").replace(">","").replace(" ", "_")

def get_host_name(i):
    # Sometimes instances transiently don't have names
    if 'Name' in i.tags:
        return sanitize(i.tags['Name'])
    else:
        return "unknown"

def get_archdomain(i):
    if 'archdomain' in i.tags:
        return sanitize(i.tags['archdomain'])
    else:
        return "unknown"

def get_env_tag(i):
    if 'env' in i.tags:
        return sanitize(i.tags['env'])
    else:
        return "unknown"

def get_all_instances(ec2):
    try:
        return ec2.get_all_instances()
    except:
        return []

def main(args):

# Path: pricing/instance_pricing.py
# class InstancePricing(object):
#     def __init__(self):
#         if not os.path.isfile(INSTANCE_PRICES_FILENAME):
#             self.retrieve_pricing_file()
#         with open(INSTANCE_PRICES_FILENAME, 'r') as infile:
#             pricing = json.load(infile)
#         vers = nav(pricing, 'formatVersion')
#         if vers != "v1.0":
#             raise Exception("Expected version v1.0 but got {}".format(vers))
#         self.products = nav(pricing, 'products')
#         self.terms = nav(pricing, 'terms')
# 
#     def retrieve_pricing_file(self):
#         # http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/price-changes.html
#         OFFERS_URL=urlparse.urljoin(INSTANCE_PRICES_URL_PREFIX, "/offers/v1.0/aws/index.json")
#         offers = requests.get(OFFERS_URL).json()
#         AMAZONEC2_URL = urlparse.urljoin(INSTANCE_PRICES_URL_PREFIX, offers['offers']['AmazonEC2']['currentVersionUrl'])
#         ec2_prices = requests.get(AMAZONEC2_URL).json()
#         with open(INSTANCE_PRICES_FILENAME, 'w') as f:
#             print(json.dumps(ec2_prices), file=f)
# 
#     @memoized
#     def get_spot_pricing(self, ec2, spot_instance_request_id):
#         # inefficient
#         spot_instance_requests = ec2.get_all_spot_instance_requests(request_ids=[spot_instance_request_id])
#         return spot_instance_requests[0].price
#         
#     @memoized
#     def get_ondemand_pricing(self, region, instance_type):
#         def pick_one(d):
#             return d.itervalues().next()
# 
#         location = AWS_REGION_LONG_NAMES[region]
# 
#         (sku,product) = [
#             (sku, nav(product, 'attributes'))
#             for sku,product in self.products.items() 
#             if (nav(product, 'attributes.instanceType')==instance_type and 
#                 nav(product, 'attributes.operatingSystem') == OPERATING_SYSTEM and 
#                 nav(product, 'attributes.location') == location and 
#                 nav(product, 'attributes.tenancy') == TENANCY)
#         ][0]
#         price = float(nav(pick_one(nav(pick_one(self.terms['OnDemand'][sku]), "priceDimensions")), 'pricePerUnit.USD'))
#         return price
# 
# Path: pricing/spot_pricing.py
# class SpotPricing(object):
#     def __init__(self):
#         self.ec2 = boto3.client('ec2')
# 
#     # this is an estimate based on recent prices
#     # http://stackoverflow.com/questions/11780262/calculate-running-cumulative-cost-of-ec2-spot-instance 
#     @memoized
#     def get_spot_instance_pricing(self, instance_type, start_time, end_time, availability_zone, spot_instance_request_id=None):
#         # don't fetch any more since this is an approximation of hourly cost anyway
#         # we can only report the accumulated cost for the time period we examine,
#         # not the total time.
# 
#         max_results = 30
#         result = self.ec2.describe_spot_price_history(InstanceTypes=[instance_type], StartTime=start_time, EndTime=end_time,
#                                                       AvailabilityZone=availability_zone, MaxResults = max_results)
#         total_cost = 0.0
#         total_seconds = (end_time - start_time).total_seconds()
#         total_hours = total_seconds / (60*60)
#         computed_seconds = 0
# 
#         last_time = end_time
#         for price in result["SpotPriceHistory"]:
#             price["SpotPrice"] = float(price["SpotPrice"])
# 
#             available_seconds = (last_time - price["Timestamp"]).total_seconds()
#             remaining_seconds = total_seconds - computed_seconds
#             used_seconds = min(available_seconds, remaining_seconds)
# 
#             total_cost += (price["SpotPrice"] / (60 * 60)) * used_seconds
#             computed_seconds += used_seconds
# 
#             last_time = price["Timestamp"]
# 
#         return float("{0:.3f}".format((total_cost / (computed_seconds / (60.0 * 60.0)))))


# Path: list/list-ec2-hosts-table.py
import argparse
import boto.ec2
import dateutil
import datetime
import json
from pricing.instance_pricing import InstancePricing
from pricing.spot_pricing import SpotPricing

        return "unknown"
    else:
        return value.replace("<", "").replace(">","").replace(" ", "_")

def get_host_name(i):
    # Sometimes instances transiently don't have names
    if 'Name' in i.tags:
        return sanitize(i.tags['Name'])
    else:
        return "unknown"

def get_archdomain(i):
    if 'archdomain' in i.tags:
        return sanitize(i.tags['archdomain'])
    else:
        return "unknown"

def get_env_tag(i):
    if 'env' in i.tags:
        return sanitize(i.tags['env'])
    else:
        return "unknown"

def get_all_instances(ec2):
    try:
        return ec2.get_all_instances()
    except:
        return []

def main(args):

    instance_pricer = InstancePricing()