def set(self, name, data, **xattrs):
        # Ignore password shadow file
        # Update editor with latest change
        if name == 'shadow':
            return

        logger.debug('WPC File Manager: Write configuration')
        cStore = ConfigStore()

        # Only capture the config portion of the diff (don't include state branch)
        # Config Diff: {'config': {...}}, Removals: [['config', 'lan', 1]]
        cfg_diff, removals = cStore.diffTree()
        cfg_diff = cfg_diff.get('config', {})
        removals = [x[1:] for x in removals if x[0] == 'config']

        url = WPC_SERVER + self.editorUri
        try:
            logger.debug('Config Diff: %s, Removals: %s' %
                         (cfg_diff, removals))
            cfg_diff = ConfigJsonEncoder().encode(cfg_diff)
            removals = ConfigJsonEncoder().encode(removals)
            body = '{"diff_from_default": [' + cfg_diff + ', ' + removals + ']}'
            body = body.encode('utf-8')
            req = urllib.request.Request(url, body)

            # Django uses csrf protection
            for k, v in self.headers.items():
                req.add_header(k, v)
            req.get_method = lambda: 'PUT'
            try:
                resp = urllib.request.urlopen(req)
            except urllib.error.HTTPError as exc:
                if exc.code == 404:
                    # This can happen if the user deletes the config editor
                    # while the service manager is running and should not be
                    # logged as an error.
                    logger.warn(
                        "Can't set config: {} returned 404".format(url))
                else:
                    logger.exception(exc)
            else:
                data = json.loads(str(resp.read(), 'utf-8'))
                if not data['success']:
                    logger.error('Unable to update config to %s: %d: %s' %
                                 (url, data['status_code'], data['message']))
        except Exception as e:
            logger.exception('Unable to update config to %s', url)
DEFAULT_AGENT_CONFIG = {
    'lustre_client_root':
    "/mnt/lustre_clients",
    'copytool_fifo_directory':
    "/var/spool",
    'copytool_template':
    "--quiet --update-interval %(report_interval)s --event-fifo %(event_fifo)s --archive %(archive_number)s %(hsm_arguments)s %(mountpoint)s"
}

PRODUCTION_CONFIG_STORE = "/var/lib/chroma"
DEVEL_CONFIG_STORE = os.path.join(os.path.dirname(__file__),
                                  ".dev_config_store")
from config_store import ConfigStore
try:
    config = ConfigStore(PRODUCTION_CONFIG_STORE)
except OSError as e:
    if e.errno == errno.EACCES:
        config = ConfigStore(DEVEL_CONFIG_STORE)
    else:
        raise

try:
    from scm_version import VERSION, PACKAGE_VERSION, IS_RELEASE, BUILD
    __version__ = VERSION
    __package_version__ = PACKAGE_VERSION
    __build__ = BUILD
    __is_release__ = IS_RELEASE
except ImportError:
    # These are defaults, should loosely track latest dev tag, won't
    # work with packaging but will allow non-packaged installs to work
示例#3
0
from config_store import ConfigStore
from modules import heating

config = ConfigStore()

config.register_module(heating, "heating", "Central Heating", "heating",
        fontawesome_icon_class="thermometer-half")

config.set_mqtt_broker("localhost", 1883)

config.set_redis_config("localhost", 6379, 0)
示例#4
0
def main():
    import sys
    import argparse
    import colorama
    from config_store import ConfigStore, ConfigLoadError
    from mininote import Mininote
    from texteditor import TextEditor, TextEditorError

    class NotLoggedInError(Exception):
        """Error for user not logged in."""

    def get_mn(config_store):
        """
        :param ConfigStore config_store: User configuration
        :returns: Mininote instance
        """
        try:
            auth_token = config_store.auth_token
        except ConfigLoadError:
            raise NotLoggedInError()

        try:
            notebook_guid = config_store.notebook_guid
        except ConfigLoadError:
            notebook_guid = None

        login_time0 = time.time()
        mn = Mininote(auth_token, notebook_guid)
        logger.debug('Login time: {}'.format(time.time() - login_time0))
        return mn

    colorama.init()

    root_logger = logging.getLogger()
    root_logger.setLevel('WARNING')
    root_logger.addHandler(logging.StreamHandler())

    config_store = ConfigStore()
    parser = argparse.ArgumentParser()
    parser.add_argument('-v',
                        '--verbose',
                        default=False,
                        action='store_true',
                        help=argparse.SUPPRESS)

    if len(sys.argv) > 1:
        subparsers = parser.add_subparsers()

        addnote = subparsers.add_parser('add')
        addnote.add_argument('note', help='Note text')
        addnote.set_defaults(handler=add_note, authorized=True)

        searchnote = subparsers.add_parser('search')
        searchnote.add_argument('note', help='Note search filter')
        searchnote.set_defaults(handler=query_notes, authorized=True)

        loginopt = subparsers.add_parser('login')
        loginopt.set_defaults(handler=login, authorized=False)

        editnote = subparsers.add_parser('edit')
        editnote.add_argument('note', help='Note search filter')
        editnote.set_defaults(handler=edit_notes,
                              authorized=True,
                              text_editor=TextEditor(config_store.text_editor))

        editor = subparsers.add_parser('set-editor')
        editor.add_argument('text_editor', help='Name of text editor')
        editor.set_defaults(handler=set_editor, authorized=False)
    else:
        # default is add note
        parser.set_defaults(handler=add_note, authorized=True, note=None)

    args = parser.parse_args()

    if args.verbose:
        root_logger.setLevel('DEBUG')

    try:
        mn = get_mn(config_store) if args.authorized else None
        args.handler(mn, config_store, args)
    except NotLoggedInError:
        logger.error('Please login using \'mn login\'')
    except TextEditorError:
        logger.error(
            'Error opening text editor\n' +
            'Please specify an editor with \'mn set-editor "<path-to-editor>"\''
        )
    except KeyboardInterrupt:
        pass