summaryrefslogtreecommitdiffstats
path: root/src/lib/Bcfg2/Server/Plugin/interfaces.py
blob: da39ac77a7316c434b65858f21be02f5cffc9c3c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
""" Interface definitions for Bcfg2 server plugins """

import os
import sys
import copy
import threading
import lxml.etree
import Bcfg2.Server
import Bcfg2.Options
from Bcfg2.Compat import Queue, Empty, Full, cPickle
from Bcfg2.Server.Plugin.base import Plugin
from Bcfg2.Server.Plugin.exceptions import PluginInitError, \
    MetadataRuntimeError, MetadataConsistencyError

# Since this file basically just contains abstract interface
# descriptions, just about every function declaration has unused
# arguments.  Disable this pylint warning for the whole file.
# pylint: disable=W0613


class Generator(object):
    """ Generator plugins contribute to literal client configurations.
    That is, they generate entry contents.

    An entry is generated in one of two ways:

    #. The Bcfg2 core looks in the ``Entries`` dict attribute of the
       plugin object.  ``Entries`` is expected to be a dict whose keys
       are entry tags (e.g., ``"Path"``, ``"Service"``, etc.) and
       whose values are dicts; those dicts should map the ``name``
       attribute of an entry to a callable that will be called to
       generate the content.  The callable will receive two arguments:
       the abstract entry (as an lxml.etree._Element object), and the
       client metadata object the entry is being generated for.
    #. If the entry is not listed in ``Entries``, the Bcfg2 core calls
       :func:`HandlesEntry`; if that returns True, then it calls
       :func:`HandleEntry`.
    """

    def HandlesEntry(self, entry, metadata):
        """ HandlesEntry is the slow path method for routing
        configuration binding requests.  It is called if the
        ``Entries`` dict does not contain a method for binding the
        entry.

        :param entry: The entry to bind
        :type entry: lxml.etree._Element
        :param metadata: The client metadata
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :return: bool - Whether or not this plugin can handle the entry
        :raises: :class:`Bcfg2.Server.Plugin.exceptions.PluginExecutionError`
        """
        return False

    def HandleEntry(self, entry, metadata):
        """ HandleEntry is the slow path method for binding
        configuration binding requests.  It is called if the
        ``Entries`` dict does not contain a method for binding the
        entry, and :func:`HandlesEntry`
        returns True.

        :param entry: The entry to bind
        :type entry: lxml.etree._Element
        :param metadata: The client metadata
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :return: lxml.etree._Element - The fully bound entry
        :raises: :class:`Bcfg2.Server.Plugin.exceptions.PluginExecutionError`
        """
        return entry


class Structure(object):
    """ Structure Plugins contribute to abstract client
    configurations.  That is, they produce lists of entries that will
    be generated for a client. """

    def BuildStructures(self, metadata):
        """ Build a list of lxml.etree._Element objects that will be
        added to the top-level ``<Configuration>`` tag of the client
        configuration.  Consequently, each object in the list returned
        by ``BuildStructures()`` must consist of a container tag
        (e.g., ``<Bundle>`` or ``<Independent>``) which contains the
        entry tags.  It must not return a list of entry tags.

        :param metadata: The client metadata
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :return: list of lxml.etree._Element objects
        """
        raise NotImplementedError


class Metadata(object):
    """ Metadata plugins handle initial metadata construction,
    accumulating data from :class:`Connector` plugins, and producing
    :class:`Bcfg2.Server.Plugins.Metadata.ClientMetadata` objects. """

    def viz(self, hosts, bundles, key, only_client, colors):
        """ Return a string containing a graphviz document that maps
        out the Metadata for :ref:`bcfg2-admin viz <server-admin-viz>`

        :param hosts: Include hosts in the graph
        :type hosts: bool
        :param bundles: Include bundles in the graph
        :type bundles: bool
        :param key: Include a key in the graph
        :type key: bool
        :param only_client: Only include data for the specified client
        :type only_client: string
        :param colors: Use the specified graphviz colors
        :type colors: list of strings
        :return: string
        """
        raise NotImplementedError

    def set_version(self, client, version):
        """ Set the version for the named client to the specified
        version string.

        :param client: Hostname of the client
        :type client: string
        :param profile: Client Bcfg2 version
        :type profile: string
        :return: None
        :raises: :class:`Bcfg2.Server.Plugin.exceptions.MetadataRuntimeError`,
                 :class:`Bcfg2.Server.Plugin.exceptions.MetadataConsistencyError`
        """
        pass

    def set_profile(self, client, profile, address):
        """ Set the profile for the named client to the named profile
        group.

        :param client: Hostname of the client
        :type client: string
        :param profile: Name of the profile group
        :type profile: string
        :param address: Address pair of ``(<ip address>, <hostname>)``
        :type address: tuple
        :return: None
        :raises: :class:`Bcfg2.Server.Plugin.exceptions.MetadataRuntimeError`,
                 :class:`Bcfg2.Server.Plugin.exceptions.MetadataConsistencyError`
        """
        pass

    def resolve_client(self, address, cleanup_cache=False):
        """ Resolve the canonical name of this client.  If this method
        is not implemented, the hostname claimed by the client is
        used.  (This may be a security risk; it's highly recommended
        that you implement ``resolve_client`` if you are writing a
        Metadata plugin.)

        :param address: Address pair of ``(<ip address>, <hostname>)``
        :type address: tuple
        :param cleanup_cache: Whether or not to remove expire the
                              entire client hostname resolution class
        :type cleanup_cache: bool
        :return: string - canonical client hostname
        :raises: :class:`Bcfg2.Server.Plugin.exceptions.MetadataRuntimeError`,
                 :class:`Bcfg2.Server.Plugin.exceptions.MetadataConsistencyError`
        """
        return address[1]

    def AuthenticateConnection(self, cert, user, password, address):
        """ Authenticate the given client.

        :param cert: an x509 certificate
        :type cert: dict
        :param user: The username of the user trying to authenticate
        :type user: string
        :param password: The password supplied by the client
        :type password: string
        :param addresspair: An address pair of ``(<ip address>,
                            <hostname>)``
        :type addresspair: tuple
        :return: bool - True if the authenticate succeeds, False otherwise
        """
        raise NotImplementedError

    def get_initial_metadata(self, client_name):
        """ Return a
        :class:`Bcfg2.Server.Plugins.Metadata.ClientMetadata` object
        that fully describes everything the Metadata plugin knows
        about the named client.

        :param client_name: The hostname of the client
        :type client_name: string
        :return: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        """
        raise NotImplementedError

    def merge_additional_data(self, imd, source, data):
        """ Add arbitrary data from a
        :class:`Connector` plugin to the given
        metadata object.

        :param imd: An initial metadata object
        :type imd: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :param source: The name of the plugin providing this data
        :type source: string
        :param data: The data to add
        :type data: any
        :return: None
        """
        raise NotImplementedError

    def merge_additional_groups(self, imd, groups):
        """ Add groups from a
        :class:`Connector` plugin to the given
        metadata object.

        :param imd: An initial metadata object
        :type imd: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :param groups: The groups to add
        :type groups: list of strings
        :return: None
        """
        raise NotImplementedError

    def update_client_list(self):
        """ Re-read the cached list of clients """
        raise NotImplementedError


class Connector(object):
    """ Connector plugins augment client metadata instances with
    additional data, additional groups, or both. """

    def get_additional_groups(self, metadata):
        """ Return a list of additional groups for the given client.
        Each group can be either the name of a group (a string), or a
        :class:`Bcfg2.Server.Plugins.Metadata.MetadataGroup` object
        that defines other data besides just the name.  Note that you
        cannot return a
        :class:`Bcfg2.Server.Plugins.Metadata.MetadataGroup` object
        that clobbers a group defined by another plugin; the original
        group will be used instead.  For instance, assume the
        following in ``Metadata/groups.xml``:

        .. code-block:: xml

            <Groups>
              ...
              <Group name="foo" public="false"/>
            </Groups>

        You could not subsequently return a
        :class:`Bcfg2.Server.Plugins.Metadata.MetadataGroup` object
        with ``public=True``; a warning would be issued, and the
        original (non-public) ``foo`` group would be used.

        :param metadata: The client metadata
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :return: list of strings or
                 :class:`Bcfg2.Server.Plugins.Metadata.MetadataGroup`
                 objects.
        """
        return list()

    def get_additional_data(self, metadata):
        """ Return arbitrary additional data for the given
        ClientMetadata object.  By convention this is usually a dict
        object, but doesn't need to be.

        :param metadata: The client metadata
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :return: dict
        """
        return dict()


class Probing(object):
    """ Probing plugins can collect data from clients and process it.
    """

    def GetProbes(self, metadata):
        """ Return a list of probes for the given client.  Each probe
        should be an lxml.etree._Element object that adheres to
        the following specification.  Each probe must the following
        attributes:

        * ``name``: The unique name of the probe.
        * ``source``: The origin of the probe; probably the name of
          the plugin that supplies the probe.
        * ``interpreter``: The command that will be run on the client
          to interpret the probe script.  Compiled (i.e.,
          non-interpreted) probes are not supported.

        The text of the XML tag should be the contents of the probe,
        i.e., the code that will be run on the client.

        :param metadata: The client metadata
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :return: list of lxml.etree._Element objects
        """
        raise NotImplementedError

    def ReceiveData(self, metadata, datalist):
        """ Process data returned from the probes for the given
        client.  ``datalist`` is a list of lxml.etree._Element
        objects, each of which is a single tag; the ``name`` attribute
        holds the unique name of the probe that was run, and the text
        contents of the tag hold the results of the probe.

        :param metadata: The client metadata
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :param datalist: The probe data
        :type datalist: list of lxml.etree._Element objects
        :return: None
        """
        raise NotImplementedError


class Statistics(Plugin):
    """ Statistics plugins handle statistics for clients.  In general,
    you should avoid using Statistics and use
    :class:`ThreadedStatistics` instead."""

    create = False

    def process_statistics(self, client, xdata):
        """ Process the given XML statistics data for the specified
        client.

        :param metadata: The client metadata
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :param data: The statistics data
        :type data: lxml.etree._Element
        :return: None
        """
        raise NotImplementedError


class Threaded(object):
    """ Threaded plugins use threads in any way.  The thread must be
    started after daemonization, so this class implements a single
    method, :func:`start_threads`, that can be used to start threads
    after daemonization of the server core. """

    def start_threads(self):
        """ Start this plugin's threads after daemonization.

        :return: None
        :raises: :class:`Bcfg2.Server.Plugin.exceptions.PluginInitError`
        """
        raise NotImplementedError


class ThreadedStatistics(Statistics, Threaded, threading.Thread):
    """ ThreadedStatistics plugins process client statistics in a
    separate thread. """

    def __init__(self, core):
        Statistics.__init__(self, core)
        Threaded.__init__(self)
        threading.Thread.__init__(self)
        # Event from the core signaling an exit
        self.terminate = core.terminate
        self.work_queue = Queue(100000)
        self.pending_file = os.path.join(Bcfg2.Options.setup.repository, "etc",
                                         "%s.pending" % self.name)
        self.daemon = False

    def start_threads(self):
        self.start()

    def _save(self):
        """Save any pending data to a file."""
        pending_data = []
        try:
            while not self.work_queue.empty():
                (metadata, xdata) = self.work_queue.get_nowait()
                data = \
                    lxml.etree.tostring(xdata,
                                        xml_declaration=False).decode("UTF-8")
                pending_data.append((metadata.hostname, data))
        except Empty:
            pass

        try:
            savefile = open(self.pending_file, 'w')
            cPickle.dump(pending_data, savefile)
            savefile.close()
            self.logger.info("Saved pending %s data" % self.name)
        except (IOError, TypeError):
            err = sys.exc_info()[1]
            self.logger.warning("Failed to save pending data: %s" % err)

    def _load(self):
        """Load any pending data from a file."""
        if not os.path.exists(self.pending_file):
            return True
        pending_data = []
        try:
            savefile = open(self.pending_file, 'r')
            pending_data = cPickle.load(savefile)
            savefile.close()
        except (IOError, cPickle.UnpicklingError):
            err = sys.exc_info()[1]
            self.logger.warning("Failed to load pending data: %s" % err)
            return False
        for (pmetadata, pdata) in pending_data:
            # check that shutdown wasnt called early
            if self.terminate.isSet():
                return False

            try:
                while True:
                    try:
                        metadata = self.core.build_metadata(pmetadata)
                        break
                    except MetadataRuntimeError:
                        pass

                    self.terminate.wait(5)
                    if self.terminate.isSet():
                        return False

                self.work_queue.put_nowait(
                    (metadata,
                     lxml.etree.XML(pdata, parser=Bcfg2.Server.XMLParser)))
            except Full:
                self.logger.warning("Queue.Full: Failed to load queue data")
                break
            except lxml.etree.LxmlError:
                lxml_error = sys.exc_info()[1]
                self.logger.error("Unable to load saved interaction: %s" %
                                  lxml_error)
            except MetadataConsistencyError:
                self.logger.error("Unable to load metadata for save "
                                  "interaction: %s" % pmetadata)
        try:
            os.unlink(self.pending_file)
        except OSError:
            self.logger.error("Failed to unlink save file: %s" %
                              self.pending_file)
        self.logger.info("Loaded pending %s data" % self.name)
        return True

    def run(self):
        if not self._load():
            return
        while not self.terminate.isSet() and self.work_queue is not None:
            try:
                (client, xdata) = self.work_queue.get(block=True, timeout=2)
            except Empty:
                continue
            except:
                # we want to catch all exceptions here so that a stray
                # error doesn't kill the entire statistics thread. For
                # instance, if a bad value gets pushed onto the queue
                # and the assignment above raises TypeError, we want
                # to report the error, ignore the bad value, and
                # continue processing statistics.
                self.logger.error("Unknown error processing statistics: %s" %
                                  sys.exc_info()[1])
                continue
            self.handle_statistic(client, xdata)
        if self.work_queue is not None and not self.work_queue.empty():
            self._save()

    def process_statistics(self, metadata, data):
        try:
            self.work_queue.put_nowait((metadata, copy.copy(data)))
        except Full:
            self.logger.warning("%s: Queue is full.  Dropping interactions." %
                                self.name)

    def handle_statistic(self, metadata, data):
        """ Process the given XML statistics data for the specified
        client object.  This differs from the
        :func:`Statistics.process_statistics` method only in that
        ThreadedStatistics first adds the data to a queue, and then
        processes them in a separate thread.

        :param metadata: The client metadata
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :param data: The statistics data
        :type data: lxml.etree._Element
        :return: None
        """
        raise NotImplementedError


# pylint: disable=C0111
# Someone who understands these interfaces better needs to write docs
# for PullSource and PullTarget
class PullSource(object):
    def GetExtra(self, client):
        return []

    def GetCurrentEntry(self, client, e_type, e_name):
        raise NotImplementedError


class PullTarget(object):
    def AcceptChoices(self, entry, metadata):
        raise NotImplementedError

    def AcceptPullData(self, specific, new_entry, verbose):
        raise NotImplementedError
# pylint: enable=C0111


class Decision(object):
    """ Decision plugins produce decision lists for affecting which
    entries are actually installed on clients. """

    def GetDecisions(self, metadata, mode):
        """ Return a list of tuples of ``(<entry type>, <entry
        name>)`` to be used as the decision list for the given
        client in the specified mode.

        :param metadata: The client metadata
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :param mode: The decision mode ("whitelist" or "blacklist")
        :type mode: string
        :return: list of tuples
        """
        raise NotImplementedError


class StructureValidator(object):
    """ StructureValidator plugins can modify the list of structures
    after it has been created but before the entries have been
    concretely bound. """

    def validate_structures(self, metadata, structures):
        """ Given a list of structures (i.e., of tags that contain
        entry tags), modify that list or the structures in it
        in-place.

        :param metadata: The client metadata
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :param config: A list of lxml.etree._Element objects
                       describing the structures (i.e., bundles) for
                       this client.  This can be modified in place.
        :type config: list of lxml.etree._Element
        :returns: None
        :raises: :class:`Bcfg2.Server.Plugin.exceptions.ValidationError`
        """
        raise NotImplementedError


class GoalValidator(object):
    """ GoalValidator plugins can modify the concretely-bound configuration of
    a client as a last stage before the configuration is sent to the
    client. """

    def validate_goals(self, metadata, config):
        """ Given a monolithic XML document of the full configuration,
        modify the document in-place.

        :param metadata: The client metadata
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :param config: The full configuration for the client
        :type config: lxml.etree._Element
        :returns: None
        :raises: :class:`Bcfg2.Server.Plugin.exceptions:ValidationError`
        """
        raise NotImplementedError


class Version(Plugin):
    """ Version plugins interact with various version control systems. """

    create = False

    options = Plugin.options + [
        Bcfg2.Options.PathOption(cf=('server', 'vcs_root'),
                                 default='<repository>',
                                 help='Server VCS repository root')]

    #: The path to the VCS metadata file or directory, relative to the
    #: base of the Bcfg2 repository.  E.g., for Subversion this would
    #: be ".svn"
    __vcs_metadata_path__ = None

    __rmi__ = Plugin.__rmi__ + ['get_revision']

    def __init__(self, core):
        Plugin.__init__(self, core)

        if self.__vcs_metadata_path__:
            self.vcs_path = os.path.join(Bcfg2.Options.setup.vcs_root,
                                         self.__vcs_metadata_path__)

            if not os.path.exists(self.vcs_path):
                raise PluginInitError("%s is not present" % self.vcs_path)
        else:
            self.vcs_path = None
    __init__.__doc__ = Plugin.__init__.__doc__ + """
.. autoattribute:: __vcs_metadata_path__ """

    def get_revision(self):
        """ Return the current revision of the Bcfg2 specification.
        This will be included in the ``revision`` attribute of the
        top-level tag of the XML configuration sent to the client.

        :returns: string - the current version
        """
        raise NotImplementedError


class ClientRunHooks(object):
    """ ClientRunHooks can hook into various parts of a client run to
    perform actions at various times without needing to pretend to be
    a different plugin type. """

    def start_client_run(self, metadata):
        """ Invoked at the start of a client run, after all probe data
        has been received and decision lists have been queried (if
        applicable), but before the configuration is generated.

        :param metadata: The client metadata object
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :returns: None
        """
        pass

    def end_client_run(self, metadata):
        """ Invoked at the end of a client run, immediately after
        :class:`GoalValidator` plugins have been run and just before
        the configuration is returned to the client.

        :param metadata: The client metadata object
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :returns: None
        """
        pass

    def end_statistics(self, metadata):
        """ Invoked after statistics are processed for a client.

        :param metadata: The client metadata object
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :returns: None
        """
        pass


class ClientACLs(object):
    """ ClientACLs are used to grant or deny access to different
    XML-RPC calls based on client IP or metadata. """

    def check_acl_ip(self, address, rmi):
        """ Check if the given IP address is authorized to make the
        named XML-RPC call.

        :param address: The address pair of the client to check ACLs for
        :type address: tuple of (<ip address>, <port>)
        :param rmi: The fully-qualified name of the RPC call
        :param rmi: string
        :returns: bool or None - True to allow, False to deny, None to
                  defer to metadata ACLs
        """
        return True

    def check_acl_metadata(self, metadata, rmi):
        """ Check if the given client is authorized to make the named
        XML-RPC call.

        :param metadata: The client metadata
        :type metadata: Bcfg2.Server.Plugins.Metadata.ClientMetadata
        :param rmi: The fully-qualified name of the RPC call
        :param rmi: string
        :returns: bool
        """
        return True


class TemplateDataProvider(object):
    """ TemplateDataProvider plugins provide variables to templates
    for use in rendering. """

    def get_template_data(self, entry, metadata, template):
        """ Get a dict of variables that will be supplied to a Cfg
        template for rendering """
        return dict()

    def get_xml_template_data(self, structfile, metadata):
        """ Get a dict of variables that will be supplied to an XML
        template (e.g., a bundle) for rendering """
        return dict()