def get_recording(data_dir,
                  filename,
                  exists=False,
                  not_exists=False,
                  ensure_path=False):
    filename = os.path.abspath(os.path.join(data_dir, filename))

    if not filename.startswith(data_dir):
        log.error('Requested recording %s is outside of data root' % filename)
        raise error.ControlPlaneError('No such recording')

    if exists and not os.path.exists(filename):
        log.error('Requested recording %s does not exist' % filename)
        raise error.ControlPlaneError('No such recording')

    if not_exists and os.path.exists(filename):
        log.error('Requested recording %s unexpectedly exists' % filename)
        raise error.ControlPlaneError('No such recording')

    if ensure_path:
        directory = os.path.dirname(filename)
        if not os.path.exists(directory):
            try:
                os.makedirs(directory)

            except OSError as exc:
                log.error('Failed to create %s: %s', directory, exc)
                raise error.ControlPlaneError('No such recording')

        elif not os.path.isdir(directory):
            raise error.ControlPlaneError('No such recording')

    return os.path.dirname(filename), os.path.basename(filename)
def list_recordings(data_dir):

    try:
        files = _traverse_dir(data_dir)

    except Exception as exc:
        raise error.ControlPlaneError('Directory %s traversal failure: %s' %
                                      (data_dir, exc))

    recordings = []

    for filename in files:
        stat = os.stat(filename, follow_symlinks=True)

        recording_type = get_recording_type(filename)
        if not recording_type:
            continue

        recording = {
            'path': filename[len(data_dir) + 1:],
            'size': stat.st_size,
            'type': recording_type
        }

        recordings.append(recording)

    return recordings
Beispiel #3
0
def new_agent(tag_id=None):
    req = flask.request.json

    data_dir = req.get('data_dir')
    if data_dir:
        data_dir = os.path.join(
            app.config['SNMPSIM_MGMT_DATAROOT'],
            data_dir)

        data_dir = os.path.abspath(data_dir)

        if not data_dir.startswith(
                os.path.abspath(app.config['SNMPSIM_MGMT_DATAROOT'])):
            raise error.ControlPlaneError(
                'Data directory outside of data root: %s' % data_dir)

        req.update(data_dir=data_dir)

    agent = models.Agent(**req)
    db.session.add(agent)

    if tag_id:
        db.session.flush()
        tag_agent = models.TagAgent(
            tag_id=tag_id, agent_id=agent.id)
        db.session.add(tag_agent)

    db.session.commit()

    schema = schemas.AgentSchema()
    return schema.jsonify(agent), 201
Beispiel #4
0
    def configure(cls, fmt, *args):
        try:
            reporter = cls.REPORTERS[fmt]

        except KeyError:
            raise error.ControlPlaneError('Unsupported reporting format: %s' %
                                          fmt)

        cls._reporter = reporter(*args)

        log.info('Using "%s" activity reporting method with '
                 'params %s' % (cls._reporter, ', '.join(args)))
Beispiel #5
0
def new_recording(path):
    recording_type = recording.get_recording_type(path)
    if not recording_type:
        raise error.ControlPlaneError('Unknown recording type')

    can_exist = flask.request.method == 'POST'

    try:
        directory, file = recording.get_recording(
            app.config['SNMPSIM_MGMT_DATAROOT'], path,
            not_exists=can_exist, ensure_path=True)

    except error.ControlPlaneError:
        raise exceptions.Conflict('Bad recording path (is it already exists?)')

    # TODO: is it a memory hog when .snmprec file is large?
    with tempfile.NamedTemporaryFile(dir=directory, delete=False) as fl:
        fl.write(flask.request.data)

    os.rename(fl.name, os.path.join(directory, file))

    return flask.Response(status=204)
Beispiel #6
0
    def daemonize(pidfile):
        try:
            pid = os.fork()
            if pid > 0:
                # exit first parent
                os._exit(0)

        except OSError as exc:
            raise error.ControlPlaneError('ERROR: fork #1 failed: %s' % exc)

        # decouple from parent environment
        try:
            os.chdir('/')
            os.setsid()

        except OSError:
            pass

        os.umask(0)

        # do second fork
        try:
            pid = os.fork()
            if pid > 0:
                # exit from second parent
                os._exit(0)

        except OSError as exc:
            raise error.ControlPlaneError('ERROR: fork #2 failed: %s' % exc)

        def signal_cb(s, f):
            raise KeyboardInterrupt

        for s in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP,
                  signal.SIGQUIT):
            signal.signal(s, signal_cb)

        # write pidfile
        def atexit_cb():
            try:
                if pidfile:
                    os.remove(pidfile)

            except OSError:
                pass

        atexit.register(atexit_cb)

        try:
            if pidfile:
                fd, nm = tempfile.mkstemp(dir=os.path.dirname(pidfile))
                os.write(fd, ('%d\n' % os.getpid()).encode('utf-8'))
                os.close(fd)
                os.rename(nm, pidfile)

        except Exception as exc:
            raise error.ControlPlaneError('Failed to create PID file %s: %s' %
                                          (pidfile, exc))

        # redirect standard file descriptors
        sys.stdout.flush()
        sys.stderr.flush()
        si = open(os.devnull, 'r')
        so = open(os.devnull, 'a+')
        se = open(os.devnull, 'a+')

        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())
Beispiel #7
0
 def daemonize(pidfile):
     raise error.ControlPlaneError('Windows is not inhabited with daemons!')