#!/usr/bin/env python
#-*- coding: utf-8 -*-
#update:2014-09-12 by liufeily@163.com

from django.core.urlresolvers import reverse
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response,RequestContext
from django.contrib.auth.decorators import login_required
from mplatform.website.common.CommonPaginator import SelfPaginator
from django.contrib import auth
from django.contrib.auth import get_user_model
import commands
import os

import logging
logger = logging.getLogger(__name__)


#@PermissionVerify()
@login_required
def ListService(request):
    logger.debug('进入函数ListNet')
    servicedictlist = [
                       {'name':'SSH','sname':'sshd','status':''},
                       {'name':'SNMP','sname':'snmpd','status':''},
                       {'name':'NFS','sname':'nfs','status':''},
                       {'name':'massclouds-svmanager','sname':'massclouds-svmanager','status':''},
                       {'name':'massclouds-websocket-proxy','sname':'massclouds-websocket-proxy','status':''}
                      ]
    for servicedict in servicedictlist:
        cmd_service = 'systemctl status %s' % servicedict['sname']
        result=commands.getstatusoutput(cmd_service)
        if result[1].find('Active: active') >= 0:
            servicedict['status'] = '运行'
        else:
            servicedict['status'] = '停止'

    kwvars = {
        'lPage':servicedictlist,
        'request':request,
    }
    logger.debug('退出函数ListNet')
    return render_to_response('ServiceManage/service.list.html',kwvars,RequestContext(request))

@login_required
def StartService(request,sname):
    cmd = 'systemctl start %s ' % (sname)
    print 'cmd='+cmd
    os.system(cmd)
    return HttpResponseRedirect(reverse('listserviceurl'))

@login_required
def StopService(request,sname):
    cmd = 'systemctl stop %s ' % (sname)
    print 'cmd='+cmd
    os.system(cmd)
    return HttpResponseRedirect(reverse('listserviceurl'))
