Exemple #1
0
 def Run(self, args):
     """Returns the results for one completion."""
     with cache_util.GetCache(args.cache, create=True) as cache:
         log.info('cache name {}'.format(cache.name))
         if not args.kwargs:
             args.kwargs = {}
         completer = _GetCompleter(args.module_path,
                                   cache=cache,
                                   qualify=args.qualify,
                                   **args.kwargs)
         parameter_info = completer.ParameterInfo(
             args, args.GetPositionalArgument('resource_to_complete'))
         if args.resource_to_complete is not None:
             matches = completer.Complete(args.resource_to_complete,
                                          parameter_info)
             return [matches]
         while True:
             name = console_io.PromptResponse('COMPLETE> ')
             if name is None:
                 break
             try:
                 completions = completer.Complete(name, parameter_info)
             except (Exception, SystemExit) as e:  # pylint: disable=broad-except
                 if args.stack_trace:
                     raise Exception(e), None, sys.exc_info()[2]
                 else:
                     log.error(unicode(e))
                 continue
             if completions:
                 print '\n'.join(completions)
         sys.stderr.write('\n')
         return None
Exemple #2
0
  def Run(self, args):
    with cache_util.GetCache(args.cache) as cache:
      log.info('cache name {}'.format(cache.name))

      if args.tables:
        names = [name for pattern in args.tables
                 for name in cache.Select(pattern)]
        if not names:
          raise cache_util.NoTablesMatched('No tables matched [{}].'.format(
              ','.join(args.tables)))
        if not args.IsSpecified('format'):
          args.format = 'json'
        results = []
        for name in names:
          try:
            table = cache.Table(name, create=False)
            results.append({
                'name': table.name,
                'data': table.Select(ignore_expiration=False)
            })
          except cache_exceptions.Error as e:
            log.warning(e)
        return results

      if not args.IsSpecified('format'):
        args.format = ('table[box](name, columns:label=COL, keys:label=KEY, '
                       'timeout, is_expired:label=EXPIRED)')
      names = cache.Select()
      return [cache.Table(name=name, create=False) for name in sorted(names)]
Exemple #3
0
def GetDefaultPolicy():
    """Gets the default policy for the current account."""
    account = properties.VALUES.core.account.Get()
    if not account:
        log.info(
            'Unable to automatically resolve policy since account property '
            'is not set.')
        return None

    domain = _GetDomain(account)
    if not domain:
        log.info('Unable to resolve domain for account [%s]', account)
        return None

    with meta_cache_util.GetCache('resource://') as cache:
        try:
            # pylint: disable=too-many-function-args
            organization_ref = _GetOrganization(cache, domain)
            policy_ref = _GetPolicy(cache, organization_ref.RelativeName(),
                                    (organization_ref, ))
        except DefaultPolicyResolutionError as err:
            log.info('Unable to automatically resolve policy: %s', err)
            return None

    return policy_ref.RelativeName()
Exemple #4
0
  def Run(self, args):

    def _RequireConfirmation(name):
      """Prompt for cache deletion and return confirmation."""
      console_io.PromptContinue(
          message='The entire [{}] cache will be deleted.'.format(name),
          cancel_on_no=True,
          default=True)

    if not args.tables and not args.IsSpecified('cache'):
      _RequireConfirmation(args.cache)
      cache_util.Delete()
      return None

    with cache_util.GetCache(args.cache) as cache:
      log.info('cache name {}'.format(cache.name))
      if args.tables:
        names = [name for pattern in args.tables
                 for name in cache.Select(pattern)]
        if not names:
          raise cache_util.NoTablesMatched('No tables matched [{}].'.format(
              ','.join(args.tables)))
        console_io.PromptContinue(
            message='[{}] will be deleted.'.format(','.join(names)),
            default=True,
            cancel_on_no=True)
        for name in names:
          table = cache.Table(name)
          table.Delete()
        return None

      _RequireConfirmation(cache.name)
      cache.Delete()

    return None
Exemple #5
0
    def Run(self, args):
        """Returns the results for one completion."""
        presentation_kwargs = args.resource_presentation_kwargs or {}
        with cache_util.GetCache(args.cache, create=True) as cache:
            log.info('cache name {}'.format(cache.name))
            if not args.kwargs:
                args.kwargs = {}
            # Create the ResourceInfo object that is used to hook up the parameter
            # info to the argparse namespace for resource argument completers.
            if args.resource_spec_path:
                spec = _GetPresentationSpec(args.resource_spec_path,
                                            **presentation_kwargs)
                spec.required = False
                resource_info = concept_parsers.ConceptParser([spec]).GetInfo(
                    spec.name)

                # Since the argument being completed doesn't have the correct
                # dest, make sure the handler always gives the same ResourceInfo
                # object.
                def ResourceInfoMonkeyPatch(*args, **kwargs):
                    del args, kwargs
                    return resource_info

                args.CONCEPTS.ArgNameToConceptInfo = ResourceInfoMonkeyPatch

            completer = _GetCompleter(args.module_path,
                                      cache=cache,
                                      qualify=args.qualify,
                                      resource_spec=args.resource_spec_path,
                                      presentation_kwargs=presentation_kwargs,
                                      attribute=args.attribute,
                                      **args.kwargs)
            parameter_info = completer.ParameterInfo(
                args, args.GetPositionalArgument('resource_to_complete'))
            if args.resource_to_complete is not None:
                matches = completer.Complete(args.resource_to_complete,
                                             parameter_info)
                return [matches]
            while True:
                name = console_io.PromptResponse('COMPLETE> ')
                if name is None:
                    break
                try:
                    completions = completer.Complete(name, parameter_info)
                except (Exception, SystemExit) as e:  # pylint: disable=broad-except
                    if args.stack_trace:
                        exceptions.reraise(Exception(e))
                    else:
                        log.error(six.text_type(e))
                    continue
                if completions:
                    print('\n'.join(completions))
            sys.stderr.write('\n')
            return None
Exemple #6
0
  def Run(self, args):
    with cache_util.GetCache(args.cache) as cache:
      log.info('cache name {}'.format(cache.name))
      if args.tables:
        names = [name for pattern in args.tables
                 for name in cache.Select(pattern)]
        if not names:
          raise cache_util.NoTablesMatched('No tables matched [{}].'.format(
              ','.join(args.tables)))
        console_io.PromptContinue(
            message=u'[{}] will be deleted.'.format(','.join(names)),
            default=True,
            cancel_on_no=True)
        for name in names:
          table = cache.Table(name)
          table.Delete()
        return None
      console_io.PromptContinue(
          message='The entire [{}] cache will be deleted.'.format(cache.name),
          default=True,
          cancel_on_no=True)

    cache_util.GetCache(args.cache).Delete()
    return None
    def testCacheResource(self):
        refs = {
            'a': [
                resources.REGISTRY.Create('compute.zones',
                                          project='p',
                                          zone='a')
            ],
            'b': [
                resources.REGISTRY.Create('compute.zones',
                                          project='p',
                                          zone='b1'),
                resources.REGISTRY.Create('compute.zones',
                                          project='p',
                                          zone='b2'),
            ]
        }
        cache = fake.Cache('fake://dummy', create=True)
        self.StartObjectPatch(meta_cache_util.GetCache,
                              '_OpenCache',
                              return_value=cache)

        @cache_util.CacheResource('my resource')
        def GetResource(key):
            return refs[key].pop(0)

        # pylint: disable=too-many-function-args,unexpected-keyword-arg
        with meta_cache_util.GetCache('resource://') as cache:
            # No args set; uses key as argument
            self.assertTrue(refs['a'])
            self.assertEqual(
                GetResource(cache, 'a').RelativeName(), 'projects/p/zones/a')
            self.assertFalse(refs['a'])
            self.assertEqual(
                GetResource(cache, 'a').RelativeName(), 'projects/p/zones/a')
            # Args set
            self.assertEqual(
                GetResource(cache, 'c', args=('b', )).RelativeName(),
                'projects/p/zones/b1')
            self.assertEqual(
                GetResource(cache, 'c').RelativeName(), 'projects/p/zones/b1')
            cache.Invalidate()  # After invalidating, call the function again
            self.assertEqual(
                GetResource(cache, 'c', args=('b', )).RelativeName(),
                'projects/p/zones/b2')