# -*- coding: utf-8 -*-
# Elisa - Home multimedia server
# Copyright (C) 2006-2008 Fluendo Embedded S.L. (www.fluendo.com).
# All rights reserved.
#
# This file is available under one of two license agreements.
#
# This file is licensed under the GPL version 3.
# See "LICENSE.GPL" in the root of this distribution including a special
# exception to use Elisa with Fluendo's plugins.
#
# The GPL part of Elisa is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Elisa" in the root directory of this distribution package
# for details on that license.


"""
Unix specific resource informations
"""

import os, os.path

# WARNING: this module is Unix specific.

def memory(key='total'):
    """
    Return memory status for the current process.
    Figures are returned in number of pages.

    @param key: which memory type to ask for; possible values are 'total',
                'resident', 'share', 'text', 'lib' and 'data'.
    @type key:  string
    @rtype:     int
    """
    mask = {'total': 0,
            'resident': 1,
            'share': 2,
            'text': 3,
            'lib': 4,
            'data': 5}

    statm_path = '/proc/self/statm'
    f = open(statm_path)
    data = f.read()
    f.close()
    
    data = data.split(' ')

    return int(data[mask[key]])

def file_descriptors():
    """
    Return the list of file descriptors opened by the current process.

    @rtype: list of string
    """
    fd_path = '/proc/self/fd'
    fds = os.listdir(fd_path)

    def get_path_from_fd(fd):
        path = os.path.join(fd_path, fd)
        try:
            path = os.readlink(path)
        except:
            return None
        return path

    fds = map(get_path_from_fd, fds)
    fds = filter(lambda e: e != None, fds)

    return fds

def threads():
    """
    Return the number of threads of the current process.

    @rtype: int
    """
    tasks_path = '/proc/self/task'
    tasks = os.listdir(tasks_path)
    return len(tasks)
