# -*- coding: utf-8 -*-
# Moovida - Home multimedia server
# Copyright (C) 2006-2009 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 Moovida with Fluendo's plugins.
#
# The GPL part of Moovida is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Moovida" in the root directory of this distribution package
# for details on that license.


"""
Unix specific resource informations
"""

import os, os.path
import resource

# WARNING: this module is Unix specific.

def memory(key='total', unit='pages'):
    """
    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(' ')
    value = int(data[mask[key]])

    pagesize = resource.getpagesize()
    if unit in ['b', 'B']:
        value = value * pagesize
    elif unit in ['k', 'K']:
        value = (value * pagesize) / (1024.0)
    elif unit in ['m', 'M']:
        value = (value * pagesize) / (1024.0 * 1024.0)

    return value

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)
