Exemplo n.º 1
0
def session_log(name, started, length):
    """ Log a session that was tracked outside of the tracker.

        :param name: The identifier of the session.
        :type name: str

        :param started: When was the session started (UTC unix timestamp).
        :type started: int

        :param length: Length of the session in seconds.
        :param started: int
    """

    try:
        af = open_locked(tracker_events_file, 'a')
    except IOError as e:
        logger.error("Error while opening events file: {}".format(e))
    else:
        with af:
            session = {
                'name': name,
                'started': int(started),
                'elapsed': int(length)
            }

            event = get_session_event(session)
            af.write(json.dumps(event) + "\n")
        if 'SUDO_USER' in os.environ:
            chown_path(tracker_events_file)
Exemplo n.º 2
0
def clear_tracker_events(old_only=True):
    """ Truncate the events file, removing all the cached data.

        :param old_only: Don't remove data from the current boot.
        :type old_only: boolean
    """
    try:
        rf = open_locked(tracker_events_file, 'r')
    except IOError as e:
        logger.error("Error opening tracking events file {}".format(e))
    else:
        with rf:
            events = []
            for event_line in rf.readlines():
                try:
                    event = json.loads(event_line)
                    if 'token' in event and event['token'] == TOKEN:
                        events.append(event_line)
                except:
                    logger.warn("Found a corrupted event, skipping.")

            with open(tracker_events_file, 'w') as wf:
                for event_line in events:
                    wf.write(event_line)
            if 'SUDO_USER' in os.environ:
                chown_path(tracker_events_file)
Exemplo n.º 3
0
def clear_tracker_events(old_only=True):
    """ Truncate the events file, removing all the cached data.

        :param old_only: Don't remove data from the current boot.
        :type old_only: boolean
    """
    try:
        rf = open_locked(tracker_events_file, 'r')
    except IOError as e:
        logger.error("Error opening tracking events file {}".format(e))
    else:
        with rf:
            events = []
            for event_line in rf.readlines():
                try:
                    event = json.loads(event_line)
                    if 'token' in event and event['token'] == TOKEN:
                        events.append(event_line)
                except:
                    logger.warn("Found a corrupted event, skipping.")

            with open(tracker_events_file, 'w') as wf:
                for event_line in events:
                    wf.write(event_line)
            if 'SUDO_USER' in os.environ:
                chown_path(tracker_events_file)
Exemplo n.º 4
0
def track_data(name, data):
    """ Track arbitrary data.

        Calling this function will generate a data tracking event.

        :param name: The identifier of the data.
        :type name: str

        :param data: Arbitrary data, must be compatible with JSON.
        :type data: dict, list, str, int, float, None
    """

    event = {
        'type': 'data',
        'time': int(time.time()),
        'timezone_offset': get_utc_offset(),
        'os_version': OS_VERSION,
        'cpu_id': CPU_ID,
        'token': TOKEN,
        'language': LANGUAGE,
        'name': str(name),
        'data': data
    }

    try:
        af = open_locked(tracker_events_file, 'a')
    except IOError as e:
        logger.error("Error opening tracker events file {}".format(e))
    else:
        with af:
            af.write(json.dumps(event) + "\n")
        if 'SUDO_USER' in os.environ:
            chown_path(tracker_events_file)
Exemplo n.º 5
0
def remove_tracking_uuid(key):
    """Remove the uuid object associated with the given key.

    Args:
        key (str): The namespace associated with a uuid, e.g. 'kano-tracker-ctl'.

    Returns:
        bool: Whether the operation was successful or not.
    """

    uuids_file, data = _open_uuids()
    if not uuids_file:
        return False

    with uuids_file:
        if key in data:
            data.pop(key)
            uuids_file.seek(0)
            uuids_file.truncate(0)
            uuids_file.write(json.dumps(data))

    if 'SUDO_USER' in os.environ:
        chown_path(TRACKER_UUIDS_PATH)

    return True
Exemplo n.º 6
0
def session_end(session_file):
    if not os.path.exists(session_file):
        msg = "Someone removed the tracker file, the runtime of this " \
              "app will not be logged"
        logger.warn(msg)
        return

    try:
        rf = open_locked(session_file, 'r')
    except IOError as e:
        logger.error("Error opening the tracker session file {}".format(e))
    else:
        with rf:
            data = json.load(rf)

            data['elapsed'] = int(time.time()) - data['started']
            data['finished'] = True

            try:
                wf = open(session_file, 'w')
            except IOError as e:
                logger.error(
                    "Error opening the tracker session file {}".format(e))
            else:
                with wf:
                    json.dump(data, wf)
        if 'SUDO_USER' in os.environ:
            chown_path(session_file)
Exemplo n.º 7
0
def generate_tracker_token():
    """
        Generating the token is a simple md5hash of the current time.

        The token is saved to the `tracker_token_file`.

        :returns: The token.
        :rtype: str
    """

    token = hashlib.md5(str(time.time())).hexdigest()

    ensure_dir(tracker_dir)
    try:
        f = open_locked(tracker_token_file, 'w')
    except IOError as e:
        logger.error(
            "Error opening tracker token file (generate) {}".format(e))
    else:
        with f:
            f.write(token)
        if 'SUDO_USER' in os.environ:
            chown_path(tracker_token_file)

    # Make sure that the events file exist
    try:
        f = open(tracker_events_file, 'a')
    except IOError as e:
        logger.error("Error opening tracker events file {}".format(e))
    else:
        f.close()
        if 'SUDO_USER' in os.environ:
            chown_path(tracker_events_file)

    return token
Exemplo n.º 8
0
def set_setting(variable, value):

    if username == 'root':
        return

    logger.debug(u"config_file / set_setting: {} {}".format(variable, value))

    data = read_json(settings_file)
    if not data:
        data = dict()

    data[variable] = value
    write_json(settings_file, data)
    chown_path(settings_file)
Exemplo n.º 9
0
def set_setting(variable, value):

    if username == 'root':
        return

    logger.debug(u"config_file / set_setting: {} {}".format(variable, value))

    data = read_json(settings_file)
    if not data:
        data = dict()

    data[variable] = value
    write_json(settings_file, data)
    chown_path(settings_file)
Exemplo n.º 10
0
def track_action(name):
    """ Trigger an action tracking event.

        :param name: The identifier of the action.
        :type name: str
    """

    try:
        af = open_locked(tracker_events_file, 'a')
    except IOError as e:
        logger.error("Error opening tracker events file {}".format(e))
    else:
        with af:
            event = get_action_event(name)
            af.write(json.dumps(event) + "\n")
        if 'SUDO_USER' in os.environ:
            chown_path(tracker_events_file)
Exemplo n.º 11
0
def track_action(name):
    """ Trigger an action tracking event.

        :param name: The identifier of the action.
        :type name: str
    """

    try:
        af = open_locked(tracker_events_file, 'a')
    except IOError as e:
        logger.error("Error opening tracker events file {}".format(e))
    else:
        with af:
            event = get_action_event(name)
            af.write(json.dumps(event) + "\n")
        if 'SUDO_USER' in os.environ:
            chown_path(tracker_events_file)
Exemplo n.º 12
0
def session_start(name, pid=None, ignore_pause=False):
    if not pid:
        pid = os.getpid()
    pid = int(pid)

    if not ignore_pause and is_tracking_paused():
        session = TrackingSession(name=name, pid=pid)
        try:
            paused_sessions_f = open_locked(PAUSED_SESSIONS_FILE, 'a')
        except IOError as err:
            logger.error(
                'Error while opening the paused sessions file: {}'.format(err)
            )
        else:
            paused_sessions_f.write(
                '{}\n'.format(session.dumps())
            )

            return session.path

    data = {
        'pid': pid,
        'name': name,
        'started': int(time.time()),
        'elapsed': 0,
        'app_session_id': str(uuid5(uuid1(), name + str(pid))),
        'finished': False,
        'token-system': TOKEN
    }

    path = get_session_file_path(data['name'], data['pid'])

    try:
        f = open_locked(path, 'w')
    except IOError as e:
        logger.error("Error opening tracker session file {}".format(e))
    else:
        with f:
            json.dump(data, f)
        if 'SUDO_USER' in os.environ:
            chown_path(path)

    return path
Exemplo n.º 13
0
def _add_tracking_uuid(key, tracking_uuid):
    """Store a new uuid object.

    Args:
        key (str): The namespace associated with a uuid, e.g. 'kano-tracker-ctl'.
    """

    uuids_file, data = _open_uuids()
    if not uuids_file:
        logger.error('Could not store tracking uuid!')
        return

    with uuids_file:
        data[key] = tracking_uuid
        uuids_file.seek(0)
        uuids_file.truncate(0)
        uuids_file.write(json.dumps(data))

    if 'SUDO_USER' in os.environ:
        chown_path(TRACKER_UUIDS_PATH)
Exemplo n.º 14
0
def track_data(name, data):
    """ Track arbitrary data.

        Calling this function will generate a data tracking event.

        :param name: The identifier of the data.
        :type name: str

        :param data: Arbitrary data, must be compatible with JSON.
        :type data: dict, list, str, int, float, None
    """

    try:
        af = open_locked(tracker_events_file, 'a')
    except IOError as e:
        logger.error("Error opening tracker events file {}".format(e))
    else:
        with af:
            event = get_data_event(name, data)
            af.write(json.dumps(event) + "\n")
        if 'SUDO_USER' in os.environ:
            chown_path(tracker_events_file)
Exemplo n.º 15
0
def track_data(name, data):
    """ Track arbitrary data.

        Calling this function will generate a data tracking event.

        :param name: The identifier of the data.
        :type name: str

        :param data: Arbitrary data, must be compatible with JSON.
        :type data: dict, list, str, int, float, None
    """

    try:
        af = open_locked(tracker_events_file, 'a')
    except IOError as e:
        logger.error("Error opening tracker events file {}".format(e))
    else:
        with af:
            event = get_data_event(name, data)
            af.write(json.dumps(event) + "\n")
        if 'SUDO_USER' in os.environ:
            chown_path(tracker_events_file)
Exemplo n.º 16
0
from kano.utils.user import get_user_unsudoed
from kano.utils.file_operations import ensure_dir, read_json, write_json, \
    chown_path

from kano_settings.common import settings_dir
from kano_settings.system.boards import get_board_props

USER = None
USER_ID = None

username = get_user_unsudoed()
if username != 'root':
    if os.path.exists(settings_dir) and os.path.isfile(settings_dir):
        os.rename(settings_dir, settings_dir + '.bak')
    ensure_dir(settings_dir)
    chown_path(settings_dir)
    settings_file = os.path.join(settings_dir, 'settings')

def merge_dicts(base, override):
    for key, value in override.iteritems():
        base[key] = value

    return base

DEFAULT_CONFIG = {
    'Keyboard-continent-index': 1,
    'Keyboard-country-index': 21,
    'Keyboard-variant-index': 0,
    'Keyboard-continent-human': "america",
    'Keyboard-country-human': _("United States"),
    'Keyboard-variant-human': _("Generic"),
Exemplo n.º 17
0
from kano.utils.user import get_user_unsudoed
from kano.utils.file_operations import ensure_dir, read_json, write_json, \
    chown_path

from kano_settings.common import settings_dir
from kano_settings.system.boards import get_board_props

USER = None
USER_ID = None

username = get_user_unsudoed()
if username != 'root':
    if os.path.exists(settings_dir) and os.path.isfile(settings_dir):
        os.rename(settings_dir, settings_dir + '.bak')
    ensure_dir(settings_dir)
    chown_path(settings_dir)
    settings_file = os.path.join(settings_dir, 'settings')

def merge_dicts(base, override):
    for key, value in override.iteritems():
        base[key] = value

    return base

DEFAULT_CONFIG = {
    'Keyboard-continent-index': 1,
    'Keyboard-country-index': 21,
    'Keyboard-variant-index': 0,
    'Keyboard-continent-human': "america",
    'Keyboard-country-human': _("United States"),
    'Keyboard-variant-human': _("Generic"),
Exemplo n.º 18
0
def update_folder_from_skel(user_name):
    logger.warn("Updating home folder of user: {}".format(user_name))
    src_dir = '/etc/skel'
    dst_dir = os.path.join('/home', user_name)

    dirlinks = []
    filelinks = []
    files = []

    for root, dirs, filenames in os.walk(src_dir):
        for d in dirs:
            path_full = os.path.join(root, d)
            if os.path.islink(path_full):
                dirlinks.append(path_full)

        for f in filenames:
            path_full = os.path.join(root, f)
            if os.path.islink(path_full):
                filelinks.append(path_full)
            else:
                files.append(path_full)

    for path_full in dirlinks + filelinks + files:
        path_rel = os.path.relpath(path_full, src_dir)
        dir_path_rel = os.path.dirname(path_rel)

        dst_path = os.path.join(dst_dir, path_rel)
        dir_dst_path = os.path.join(dst_dir, dir_path_rel)

        # print 'path_full', path_full
        # print 'path_rel', path_rel
        # print 'dir_path_rel', dir_path_rel
        # print 'dst_path', dst_path
        # print 'dir_dst_path', dir_dst_path
        # print

        if os.path.exists(dst_path):
            if os.path.islink(dst_path):
                logger.info("removing link: {}".format(dst_path))
                os.unlink(dst_path)

            elif os.path.isdir(dst_path):
                logger.info("removing dir: {}".format(dst_path))
                shutil.rmtree(dst_path)

            elif os.path.isfile(dst_path):
                logger.info("removing file: {}".format(dst_path))
                os.remove(dst_path)

        # make sure that destination directory exists
        if os.path.exists(dir_dst_path):
            if not os.path.isdir(dir_dst_path):
                os.remove(dir_dst_path)
        else:
            logger.info("making needed dir: {}".format(dir_dst_path))
            os.makedirs(dir_dst_path)
            chown_path(dir_dst_path, user=user_name, group=user_name)

        # creating links
        if os.path.islink(path_full):
            linkto = os.readlink(path_full)
            msg = "creating link {} -> {}".format(dst_path, linkto)
            logger.info(msg)
            os.symlink(linkto, dst_path)
            chown_path(dst_path, user=user_name, group=user_name)

        elif os.path.isfile(path_full):
            msg = "copying file {} -> {}".format(path_full, dst_path)
            logger.info(msg)
            shutil.copy(path_full, dst_path)
            chown_path(dst_path, user=user_name, group=user_name)