예제 #1
0
    def handle(self, args):
        """
        Handle the destroy command
        """
        # Load the managed instances
        manager = ManagedInstances.load()

        # Validate instances and create a new manager
        if args.instances:
            n_unmanaged = 0
            for instance in args.instances:
                if instance not in manager:
                    n_unmanaged += 1

            # Cannot destroy any unmanaged instances
            if n_unmanaged > 0:
                raise ValueError(
                    "cannot destroy {} unmanaged instances".format(n_unmanaged)
                )

            # Filter the manager to the instances we'll be destroying
            manager = manager.filter(args.instances, instances=True)

        # Return if no instances are managed
        if len(manager) == 0:
            return color.format(
                "no instances under management", color.LIGHT_YELLOW
            )

        # Prompt to confirm
        if not args.force:
            prompt = color.format("destroy {}?", color.LIGHT_YELLOW, manager)
            if not self.prompt(prompt):
                print(color.format("stopping instance termination", color.LIGHT_CYAN))
                return
            print(color.format(u"destroying {} instances …\n", color.LIGHT_RED, len(manager)))

        # Destroy instances
        reports = manager.terminate()

        # Report destruction
        table = [['Region', 'Instance', 'State']]
        table.extend([
            [
                report.region.name, report["InstanceId"], unicode(report),
            ]
            for report in reports
        ])
        print(tabulate(table, tablefmt="simple", headers='firstrow'))

        # Remove instances from management
        # Ensure we reload the full manager list and not use the filtered one.
        manager = ManagedInstances.load()
        for report in reports:
            manager.discard(report["InstanceId"])
        manager.dump()
예제 #2
0
파일: launch.py 프로젝트: bbengfort/geonet
    def handle(self, args):
        """
        Handle the launch command
        """

        # Load the regions for the launch command
        regions = Regions(region for region in Regions.load()
                          if str(region) in args.regions)

        # Get the templates associated with each region
        self.templates = regions.launch_templates()

        # Launch the instances with the specified template
        instances = Instances.collect(
            wait(
                (partial(self.launch_in_region, region) for region in regions),
                args=(args, )))

        # Rename the instances given
        wait((partial(self.tag_instance, instance, idx)
              for idx, instance in enumerate(instances)),
             args=(args, ))

        # Update the instances under management
        manager = ManagedInstances.load()
        for instance in instances:
            manager.add(str(instance), instance.region)
        manager.dump()

        # Report what went down
        print(
            color.format("created {} instances in {} regions",
                         color.LIGHT_GREEN, len(instances), len(regions)))
예제 #3
0
파일: start.py 프로젝트: bbengfort/geonet
    def handle(self, args):
        """
        Start all instances currently being managed.
        """
        manager = ManagedInstances.load()

        # Filter by regions
        manager = manager.filter(args.regions, regions=True)

        # Filter by instance ids
        if args.instances:
            manager = manager.filter(args.instances, instances=True)

        # Return if no instances are managed
        if len(manager) == 0:
            return color.format("no instances under management",
                                color.LIGHT_YELLOW)

        table = [['Region', 'Instance', 'State']]
        table.extend([[
            report.region.name,
            report["InstanceId"],
            unicode(report),
        ] for report in manager.start()])
        print(tabulate(table, tablefmt="simple", headers='firstrow'))
예제 #4
0
    def handle(self, args):
        """
        Handle the hosts commands and command line arguments
        """
        # Load the instance manager and get instance information
        manager = ManagedInstances.load()

        # Default host data
        defaults = {
            'user': args.user,
            'port': args.port,
            'forward_agent': False if args.no_forward_agent else True
        }

        # Get the SSH information for each instance
        hosts = defaultdict(lambda: defaults.copy())
        for instance in manager.status():
            host = hosts[instance.name]
            host["hostname"] = instance.ipaddr if args.ipaddr else instance.hostname
            host["key"] = os.path.join(args.ssh_dir, "{}.pem".format(instance["KeyName"]))

        # Write out the data to the outpath
        if args.format == 'json':
            self.write_json(hosts, args.outpath)

        elif args.format == 'config':
            self.write_config(hosts, args.outpath)

        else:
            raise ValueError("unknown hosts format '{}'".format(args.format))
예제 #5
0
파일: status.py 프로젝트: bbengfort/geonet
    def handle(self, args):
        """
        Handles the config command with arguments from the command line.
        """
        # Load the instance manager
        manager = ManagedInstances.load()

        # Filter by regions
        manager = manager.filter(args.regions, regions=True)

        # Filter by instance ids
        if args.instances:
            manager = manager.filter(args.instances, instances=True)

        # Return if no instances are managed
        if len(manager) == 0:
            return color.format("no instances under management",
                                color.LIGHT_YELLOW)

        # Load the instances
        instances = manager.status()

        # Create the region table
        table = [[
            instance.state_light(), instance.region.name, instance.name,
            str(instance),
            instance.uptime()
        ] for instance in instances]

        print(tabulate(table, tablefmt="plain"))
예제 #6
0
    def handle(self, args):
        self.instances = ManagedInstances.load()
        instance_ids = list(self.instances) if args.all else args.instance_id

        if len(instance_ids) == 0:
            print(color.format("no instances to create", color.YELLOW))

        results = [self.handle_instance_id(iid, args) for iid in instance_ids]

        print(tabulate(results, tablefmt="simple", headers="keys"))
예제 #7
0
 def handle(self, args):
     """
     Handles the config command with arguments from the command line.
     """
     if args.edit: self.edit()
     instances = ManagedInstances.load()
     for region, instances in instances.regions():
         table = [[region.name]]
         table.extend([[instance] for instance in instances])
         print(tabulate(table, tablefmt='simple', headers='firstrow'))
         print("")
예제 #8
0
    def edit(self):
        """
        Touch the instances file to ensure that it exists.
        """
        # Create the default configuration if none exists
        if not os.path.exists(INSTANCES):

            # Ensure the directory exists
            dirname = os.path.dirname(USERCONFIG)
            if not os.path.exists(dirname):
                os.makedirs(dirname)

            # Create and dump an empty instances file
            ManagedInstances().dump()

        # Run the editor
        edit_file(INSTANCES)