Exemplo n.º 1
0
 def __init__(self):
     self.default_search_days = 180  # Search usage data for this number
     self.default_search_end = datetime.now(
     )  # Search starts from this date back to days within default_search_days
     self.api = FGMetricAPI()
     self.set_default_options()
Exemplo n.º 2
0
 def activate_metric(self):
     self.cmetrics = FGMetricAPI()
     self.chart = FGCharts()
Exemplo n.º 3
0
class FGMetricCli:
    """

    FGMetricCli
    -----------
    Command Line Interface for fg-metric.

    Usage: fg-metric-cli

    Description
    ===========
    As a cli version of fg-metric, this module provides usage data with search options.

    - Excutable name is fg-metric-cli (defined by setup.py).
    - FG Cloud Mesh would be one of the examples using fg-metric-cli.

    Basic data structure
    ====================

    {
        "start_date"    :   start date of search    (datetime),
        "end_date"      :   end date of search      (datetime),
        "ownerid"       :   portal user id          (str),
        "metric"        :   selected metric name    (str),
        "period"        :   monthly, weekly, daily  (str),
        "clouds"        :   set of clouds           (list)
                            [
                                { "service"     :   cloud service name  (str),
                                 "hostname"     :   hostname (str),
                                 "stats"        :   value (int) }
                                 ...
                                 ]
    }

    Example 1. Get user statistics

    $ fg-metric-cli -u hrlee

    """

    # https://pypi.python.org/pypi?%3Aaction=list_classifiers
    development_status = (2, "Pre-alpha")

    def __init__(self):
        self.default_search_days = 180  # Search usage data for this number
        self.default_search_end = datetime.now(
        )  # Search starts from this date back to days within default_search_days
        self.api = FGMetricAPI()
        self.set_default_options()

    def set_default_options(self):
        self.end_date = self.default_search_end
        self.start_date = self.end_date + timedelta(-self.default_search_days)
        self.metric = 'count runtime cores mem disks'

    def set_argparse(self):
        parser = argparse.ArgumentParser(
            description='Specify search options for usage statistics')
        parser.add_argument(
            '-s', '--s_date', help="start date of search", default=self.start_date)
        parser.add_argument(
            '-e', '--e_date', help="end date of search", default=self.end_date)
        parser.add_argument(
            '-m', '--metric', help="metric name to search", default=self.metric)
        parser.add_argument(
            '-lm', '--listmetrics', help="list of metric possible to search")
        parser.add_argument(
            '-u', '--user', help='owerid (i.e. fg portal id) to search', required=True)
        parser.add_argument('-c', '--cloud', help='cloud name to search')
        parser.add_argument(
            '-lc', '--listclouds', help='list of cloud services possible to search')
        parser.add_argument('-H', '--host', help='host name to search')
        parser.add_argument(
            '-lh', '--listhost', help='list of hostnames possible to search')
        parser.add_argument('-p', '--period', help='search period')
        parser.add_argument(
            '-lp', '--listperiod', help='list of search period')

        args = parser.parse_args()
        self.args = args

        self._set_vars()

    def _set_vars(self):
        self._set_api_vars()
        self._set_dict_vars()

    def _set_api_vars(self):
        args = self.args
        self.api.set_date(args.s_date, args.e_date)
        self.api.set_metric(args.metric)
        self.api.set_user(args.user)
        self.api.set_cloud(args.cloud)
        self.api.set_hostname(args.host)
        self.api.set_period(args.period)

    def _set_dict_vars(self):
        self.result = {
            "start_date":   self.start_date,
            "end_date":   self.end_date,
            "ownerid":   self.args.user,
            "metric":   self.args.metric.split(),
            "period":   self.args.period or "All",
            "clouds":   self.args.cloud or "All",
            "hostname":   self.args.host or "All"
        }

    def get_stats(self):
        self.stats = self.api.get_stats()

    def return_dict(self):
        self.result['stats'] = self.stats
        return json.dumps(self.result, default=json_util.default)
Exemplo n.º 4
0
class metric:

    def activate_metric(self):
        self.cmetrics = FGMetricAPI()
        self.chart = FGCharts()

    @command
    def do_set(self, line, args):
        """
        Usage:
                set date    START_DATE END_DATE
                set metric  (runtime|count|countusers)
                set (node|nodename|hostname) NODE_NAME
                set (cloud|platform) CLOUD_NAME
                set period  (monthly|quarterly|weekly|daily)

        Set value for analysis

        Arguments:
            START_DATE  start date to analyze 
            END_DATE    end date to analyze
            NODE_NAME   set hostname
            CLOUD_NAME  set cloud service [openstack|eucalyptus|nimbus]

        """
        print(args)
        #print(vars(self.cmetrics))
        #print(vars(self.cmetrics.search))
        if args["date"]:
            self.cmetrics.set_date(args["START_DATE"], args["END_DATE"])
        elif args["metric"]:
            self.cmetrics.set_metric(self._get_keyname(args, "runtime|count|countusers"))
        elif args["cloud"] or args["platform"]:
            self.cmetrics.set_cloud(args["CLOUD_NAME"])
        elif args["node"] or args["nodename"] or args["hostname"]:
            self.cmetrics.set_hostname(args["NODE_NAME"])
        elif args["period"]:
            self.cmetrics.set_period(self._get_keyname(args, "monthly|quarterly|weekly|daily"))

    def _get_keyname(self, args, slist):
        for i in slist.split("|"):
            if args[i]:
                return i
        return None

    ######################################################################
    # analyze commands
    ######################################################################

    @command
    def do_analyze(self, args, arguments):
        """
        Usage:
               analyze OWNERID METRIC --start START --end END 
               analyze METRIC --period [monthly|quarterly|weekly|daily]
               analyze METRIC --month MONTH
               analyze METRIC --year YEAR
               analyze

        Analyze the metric data

        Arguments:
            OWNERID    The portal id of cloud users
            METRIC     The metric to be analyzed ... what values does it have? ...
            START      The start time n the format YYYY-MM-DDThh:mm:ss
            END        The end time n the format YYYY-MM-DDThh:mm:ss
            MONTH      The month in 01,02, ..., 12
            YEAR       The year to analyze

        Options:
          --start     specifies the time when to start the analysis
          --end       specified the time when to end the analysis
          --year      the year
          --month     the month
          --period    the period

        """
        #print(arguments)
        #TEST ONLY
        if arguments["OWNERID"]:
            self.cmetrics.set_user(arguments['OWNERID'])
        if arguments["START"] and arguments["END"]:
            self.cmetrics.set_date(arguments["START"], arguments["END"])
        if arguments["METRIC"]:
            self.cmetrics.set_metric(arguments["METRIC"])
        if arguments["--period"]:
            self.cmetrics.set_period(self._get_keyname(arguments, "monthly|quarterly|weekly|daily")) #TEST arguments["
        res = self.cmetrics.get_stats()
        print res

    ######################################################################
    # CVS commands
    ######################################################################

    @command
    def do_table(self, args, arguments):
        """
        Usage:
               table FILENAME
               table --file FILENAME

        Export the data in cvs format to a file. Former cvs command

        Arguments:
            FILENAME   The filename

        Options:
          --filet     specifies the filename

        """
        print(arguments)

    ######################################################################
    # chart
    ######################################################################

    @command
    def do_chart(self, line, args):
        """
        Create a chart of a given type

        Usage:
            chart -t (bar|line|column|pie|motion|line-time-series) [-d DIR | --directory=DIR]
            chart --type (bar|line|column|pie|motion|line-time-series) [-d DIR | --directory=DIR]
	    chart --api (highcharts|google|jquery|sparkline)

        Options:
          -d DIR --directory=DIR  The directory [default: ./]
	  
        """
        print(args)
        if args["--api"]:
            api = self._get_keyname(args, "highcharts|google|jquery|sparkline")
        else:
            api = "highcharts"
        self.chart.set_chart_api(api)
        if args["-t"] or args["--type"]:
           self.chart.set_type(self._get_keyname(args, "bar|line|column|pie|motion|line-time-series"))
        if args["--directory"]:
           self.chart.set_output_path(args["--directory"])
        self.chart.set_filename( "TEST." + self.chart.output_type)
        self.chart.set_series(self.cmetrics.get_series())
        self.chart.set_title("TEST")
        self.chart.display()
        #self.chart.set_title_beta(', '.join(self.search.metric), self.search.period, self.search.groupby)
        #self.chart.set_subtitle("source: " + str(self.search.get_platform_names()) + " on " + str(self.search.get_node_names()))
        #self.chart.set_yaxis(self.search.timetype or "")

    ######################################################################
    # count images
    ######################################################################

    @command
    def do_count_images(self, line, opts=None):
        """
        Usage:
               count_images [--detail | --summary] --user USER 

	Count bucket images per user (development level). It is
        virtual machine image counts grouped by users or accounts
        based on euca2ools.  It shows that which user or account
        currently owns how many virtual machine images on the system.
        This metric is based on the euca2ool command.
	euca-describe-images. that a eucalyptus user can see a list
        of machine images.

        Arguments:
            USER       The user
	    
        Options:
          --user       Show only images from the specified userid.
	  --detail     Show details of the image (What would that be?)
	  --summary    show summary about the image (default)    
	  
        """
        print(arguments)