Esempio n. 1
0
 def _send_hook(self, when):
     msg = OrderedDict()
     msg['execution_type'] = self.history.kind
     msg['when'] = when
     inventory = self.history.inventory
     if isinstance(inventory, Inventory):
         inventory = inventory.get_hook_data(when)
     msg['target'] = OrderedDict()
     msg['target']['name'] = self.history.mode
     msg['target']['inventory'] = inventory
     msg['target']['project'] = self.project.get_hook_data(when)
     msg['history'] = self.history.get_hook_data(when)
     self.project.hook(when, msg)
Esempio n. 2
0
def generate_fileds(ansible_reference: AnsibleArgumentsReference,
                    ansible_type: str) -> OrderedDict:
    if ansible_type is None:
        return OrderedDict()  # nocv

    fields = OrderedDict()

    for ref, settings in ansible_reference.raw_dict[ansible_type].items():
        if ref in [
                'help',
                'version',
        ]:
            continue
        ref_type = settings.get('type', None)
        kwargs = dict(help_text=settings.get('help', ''), required=False)
        field = None
        if ref_type is None:
            field = serializers.BooleanField
            kwargs['default'] = False
        elif ref_type == 'int':
            field = serializers.IntegerField
        elif ref_type == 'string' or 'choice':
            field = vst_fields.VSTCharField
            kwargs['allow_blank'] = True

        if ref == 'verbose':
            field = serializers.IntegerField
            kwargs.update(dict(max_value=4, default=0))
        if ref in models.PeriodicTask.HIDDEN_VARS:
            field = vst_fields.SecretFileInString
        if ref == 'inventory':
            kwargs['autocomplete'] = 'Inventory'
            field = InventoryAutoCompletionField

        if field is None:  # nocv
            continue

        if ansible_type == 'module':
            if ref == 'group':
                kwargs['default'] = 'all'

        field_name = ref.replace('-', '_')
        fields[field_name] = field(**kwargs)

    return fields
Esempio n. 3
0
 def to_representation(self, instance):
     data = OrderedDict()
     if instance.kind in ["Task", "Module"]:
         hidden_vars = models.PeriodicTask.HIDDEN_VARS
         data = super(TemplateSerializer,
                      self).to_representation(instance,
                                              hidden_vars=hidden_vars)
         self.repr_options(instance, data, hidden_vars)
     return data
Esempio n. 4
0
 def stats(self, last):
     qs = self.filter(start_time__gte=now() - timedelta(days=last))
     qs = qs.annotate(
         day=dbfunc.TruncDay('start_time'),
         month=dbfunc.TruncMonth('start_time'),
         year=dbfunc.TruncYear('start_time'),
     )
     result = OrderedDict()
     result['day'] = self._get_history_stats_by(qs, 'day')
     result['month'] = self._get_history_stats_by(qs, 'month')
     result['year'] = self._get_history_stats_by(qs, 'year')
     return result
Esempio n. 5
0
 def list(self, request, *args, **kwargs):
     # pylint: disable=unused-argument
     stats = OrderedDict()
     stats['projects'] = self._get_count_by_user(sers.models.Project)
     stats['templates'] = self._get_count_by_user(sers.models.Template)
     stats['inventories'] = self._get_count_by_user(sers.models.Inventory)
     stats['groups'] = self._get_count_by_user(sers.models.Group)
     stats['hosts'] = self._get_count_by_user(sers.models.Host)
     stats['teams'] = self._get_count_by_user(sers.models.UserGroup)
     stats['users'] = self._get_count_by_user(sers.User)
     stats['jobs'] = self._get_history_stats(request)
     return base.Response(stats, status.HTTP_200_OK).resp
Esempio n. 6
0
 def get_hook_data(self, when):
     data = OrderedDict()
     data['id'] = self.id
     data['start_time'] = self.start_time.isoformat()
     if when == "after_execution":
         data['stop_time'] = self.stop_time.isoformat()
         data['status'] = self.status
     data["initiator"] = dict(
         initiator_type=self.initiator_type,
         initiator_id=self.initiator,
     )
     if self.initiator_type in ["template", "scheduler"]:
         data["initiator"]['name'] = self.initiator_object.name
     return data
Esempio n. 7
0
    def get_data_container(self):
        """
        :return: An OrderedDict ready to use in the fuzzer, which is based
                 on the self._fuzzable_parameters attribute. You'll need to
                 process an XML before accessing this method, else the result
                 will be empty.
        """
        init_val = OrderedDict()

        for name, value in self.fuzzable_parameters:
            value_list = init_val.setdefault(name, [])

            if name == BASE_64:
                value_list.append(base64.b64decode(value))
            else:
                value_list.append(value)

        return init_val
Esempio n. 8
0
def parse_qs(qstr, ignore_exc=True, encoding=DEFAULT_ENCODING):
    """
    Parse a url encoded string (a=b&c=d) into a QueryString object.

    :param qstr: The string to parse
    :return: A QueryString object (a dict wrapper).
    """
    if not isinstance(qstr, basestring):
        raise TypeError('parse_qs requires a basestring as input.')

    qs = QueryString(encoding=encoding)

    if qstr:
        # convert to string if unicode
        if isinstance(qstr, unicode):
            qstr = qstr.encode(encoding, 'ignore')

        try:
            odict = OrderedDict()
            for name, value in parse_qsl(qstr,
                                         keep_blank_values=True,
                                         strict_parsing=False):
                if name in odict:
                    odict[name].append(value)
                else:
                    odict[name] = [value]
        except Exception:
            if not ignore_exc:
                raise BaseFrameworkException('Error while parsing "%r"' % qstr)
        else:

            def decode(item):
                return (item[0].decode(encoding, 'ignore'),
                        [e.decode(encoding, 'ignore') for e in item[1]])

            qs.update((decode(item) for item in odict.items()))

    return qs
Esempio n. 9
0
class Template(ACLModel):
    name = models.CharField(max_length=512)
    kind = models.CharField(max_length=32)
    template_data = models.TextField(default="{}")
    options_data = models.TextField(default="{}")
    inventory = models.CharField(max_length=128,
                                 default=None,
                                 blank=True,
                                 null=True)
    project = ForeignKeyACL(Project,
                            on_delete=models.CASCADE,
                            default=None,
                            blank=True,
                            null=True)

    class Meta:
        default_related_name = 'template'

    template_fields = OrderedDict()
    template_fields["Task"] = ["playbook", "vars", "inventory"]
    template_fields["Module"] = [
        "inventory", "module", "group", "args", "vars"
    ]

    excepted_execution_fields = ['inventory']
    _exec_types = {
        "Task": "playbook",
        "Module": "module",
    }
    kinds = list(template_fields.keys())

    def get_option_data(self, option):
        return self.options.get(option, {})

    def get_options_data(self):
        return json.loads(self.options_data or '{}')

    def get_data(self):
        data = json.loads(self.template_data)
        if "inventory" in self.template_fields[self.kind] and self.inventory:
            try:
                data['inventory'] = int(self.inventory)
            except ValueError:
                data['inventory'] = self.inventory
        return data

    @property
    def inventory_object(self):
        try:
            return self.project.inventories.get(pk=int(self.data['inventory']))
        except (ValueError, Inventory.DoesNotExist):
            self.project.check_path(self.data['inventory'])
            return self.data['inventory']

    def get_data_with_options(self, option, **extra):
        data = self.get_data()
        option_data = self.get_option_data(option)
        option_vars = option_data.pop("vars", {})
        vars = data.pop("vars", {})
        vars.update(option_vars)
        data.update(option_data)
        data.update(vars)
        data.update(extra)
        return data

    def execute(self, serializer, user, option=None, **extra):
        # pylint: disable=protected-access
        tp = self._exec_types.get(self.kind, None)
        if tp is None:
            raise UnsupportedMediaType(media_type=self.kind)  # nocv
        return serializer._execution(tp,
                                     self.get_data_with_options(
                                         option, **extra),
                                     user,
                                     template=self.id,
                                     template_option=option)

    def _convert_to_data(self, value):
        if isinstance(value, (six.string_types, six.text_type)):
            return json.loads(value)  # nocv
        elif isinstance(value, (dict, OrderedDict, list)):
            return value
        else:
            raise ValueError("Unknown data type set.")  # nocv

    def __encrypt(self, new_vars, data_name='data'):
        old_vars = getattr(self, data_name).get('vars', {})
        secrets = filter(lambda key: new_vars[key] == '[~~ENCRYPTED~~]',
                         new_vars.keys())
        for key in secrets:
            new_vars[key] = old_vars.get(key, new_vars[key])
        return new_vars

    def keep_encrypted_data(self, new_vars):
        if self.template_data == '{}':
            return new_vars
        return self.__encrypt(new_vars)

    def _validate_option_data(self, data):
        excepted = self.excepted_execution_fields
        errors = {
            name: ['Disallowed to override {}.'.format(name)]
            for name in data.keys() if name in excepted
        }
        if errors:
            raise ValidationError(errors)

    def set_options_data(self, value):
        options_data = self._convert_to_data(value)
        new = dict()
        for option, data in options_data.items():
            self._validate_option_data(data)
            if data.get('vars', None):
                data['vars'] = self.__encrypt(data['vars'], 'options')
            new[option] = data
        self.options_data = json.dumps(new)

    def set_data(self, value):
        data = self._convert_to_data(value)
        inventory_id = data.pop('inventory', None)
        if "inventory" in self.template_fields[self.kind]:
            try:
                self.inventory = self.project.inventories.get(
                    pk=int(inventory_id)).id
            except (ValueError, TypeError, Inventory.DoesNotExist):
                self.inventory = inventory_id
        data['vars'] = self.keep_encrypted_data(data.get('vars', None))
        self.template_data = json.dumps(data)

    @property
    def data(self):
        return self.get_data()

    @data.setter
    def data(self, value):
        self.set_data(value)

    @data.deleter
    def data(self):  # nocv
        self.template_data = ""
        self.inventory = None
        self.project = None

    @property
    def options(self):
        return self.get_options_data()

    @options.setter
    def options(self, value):
        self.set_options_data(value)

    @options.deleter
    def options(self):  # nocv
        self.options_data = ''

    @property
    def options_list(self):
        return list(self.options.keys())
Esempio n. 10
0
 def get_vars(self):
     qs = self.variables.order_by("key")
     return OrderedDict(qs.values_list('key', 'value'))
Esempio n. 11
0
 def get_vars(self):
     qs = self.variables.all().sort_by_key().values_list('key', 'value')
     return reduce(update_boolean, self.BOOLEAN_VARS, OrderedDict(qs))
Esempio n. 12
0
 def get_hook_data(self, when):
     # pylint: disable=unused-argument
     hook_data = OrderedDict()
     hook_data['id'] = self.id
     hook_data['name'] = self.name
     return hook_data