Esempio n. 1
0
def scene(aDict):
    """Function docstring for scene TBD

 Args:
  - node (required)
  - scene (required)
  - op (optional) - 'run'/'off'
  - status (optional)

 Output:
 """
    try:
        ret = {}
        node = SC['node'][aDict['node']]
        if aDict.get('op'):
            ret['op'] = "RunScene" if aDict.get('op') == "run" else "SceneOff"
            res = rest_call(
                "%s?id=action&serviceId=urn:micasaverde-com:serviceId:HomeAutomationGateway1&action=%s&SceneNum=%s"
                % (node, ret['op'], aDict['scene']))
            ret['info'] = "OK" if (res['code'] == 200) else "FAILED"
        elif aDict.get('status'):
            scenes = rest_call("%s?id=sdata" % node)['data']['scenes']
            for scene in scenes:
                if scene['id'] == aDict['scene']:
                    ret['info'] = scene
                    break
        else:
            ret = rest_call("%s?id=scene&action=list&scene=%s" %
                            (node, aDict['scene']))['data']
    except Exception as e:
        ret = e[0]
    return ret
Esempio n. 2
0
def device_info(aDict):
    """Function docstring for device_info TBD

 Args:
  - node (required)
  - id (required)
  - op (optional)
  - category (optional)
  - service (optional)
  - variable (optional)
  - value (optional)

 Output:
 """
    ret = {'op': None}
    op = aDict.pop("op", None)
    try:
        node = SC['node'][aDict['node']]
        if op == 'update':
            ret['op'] = {}
            if aDict['category'] == '2' and aDict[
                    'service'] == 'urn:upnp-org:serviceId:Dimming1' and aDict[
                        'variable'] == 'LoadLevelTarget':
                ret['op']['response'] = rest_call(
                    "%s?id=action&output_format=json&DeviceNum=%s&serviceId=urn:upnp-org:serviceId:Dimming1&action=SetLoadLevelTarget&newLoadlevelTarget=%s"
                    % (node, aDict['id'], aDict['value']))['data']
                response = ret['op']['response'].get(
                    'u:SetLoadLevelTargetResponse')
                if response:
                    from time import sleep
                    sleep(1)
                    ret['op']['job'] = response.get('JobID')
                    ret['op']['result'] = rest_call(
                        "%s?id=jobstatus&job=%s&plugin=zwave" %
                        (node, response.get('JobID')))['data']

        res = rest_call("%s?id=status&DeviceNum=%s" %
                        (node, aDict['id']))['data']
        info = res['Device_Num_%s' % aDict['id']]['states']
        for x in info:
            try:
                service = x['service'].split(':')
                if service[1] <> 'micasaverde-com':
                    entry = ret.get(x['service'], {})
                    entry[x['variable']] = x['value']
                    ret[x['service']] = entry
            except:
                pass
    except Exception as e:
        ret = e[0]
    return ret
Esempio n. 3
0
def update_server(aDict):
    """Function docstring for update_server:  reload the DHCP server to use updated info

 Args:
  - entries (required). entries is a list of dict objects containing hostname, mac, ip etc

 Output:
 """
    from sdcp.core.common import SC, rest_call
    entries = rest_call("%s?device_list_mac" % SC['system']['master'])['data']
    # Create file
    with open(SC['iscdhcp']['static'], 'w') as leasefile:
        for entry in entries:
            leasefile.write(
                "host {0: <30} {{ hardware ethernet {1}; fixed-address {2}; }} # Subnet {3}, Id: {4}\n"
                .format(entry['fqdn'], entry['mac'], entry['ip'],
                        entry['subnet_id'], entry['id']))

    # Reload
    from subprocess import check_output, CalledProcessError
    ret = {}
    try:
        ret['output'] = check_output(SC['iscdhcp']['reload'].split())
    except CalledProcessError as c:
        ret['code'] = c.returncode
        ret['output'] = c.output

    ret['result'] = 'NOT_OK' if ret['output'] else 'OK'
    return ret
Esempio n. 4
0
def rest(aDict):
    """Function docstring for rest TBD

 Args:
  - token (required)
  - service (optional)
  - call (optional)
  - href (optional)
  - arguments (optional)
  - method (optional)

 Output:
 """
    try:
        if aDict.get('href'):
            ret = rest_call(aDict.get('href'), aDict.get('arguments'),
                            aDict.get('method', 'GET'),
                            {'X-Auth-Token': aDict['token']})
        else:
            with DB() as db:
                db.do(
                    "SELECT node, service_port, service_url FROM openstack_tokens LEFT JOIN openstack_services ON openstack_tokens.id = openstack_services.id WHERE openstack_tokens.token = '%s' AND service = '%s'"
                    % (aDict['token'], aDict.get('service')))
                data = db.get_row()
            controller = Device(data['node'], aDict['token'])
            ret = controller.call(data['service_port'],
                                  data['service_url'] + aDict['call'],
                                  aDict.get('arguments'),
                                  aDict.get('method', 'GET'))
        ret['result'] = 'OK' if not ret.get('result') else ret.get('result')
    except Exception as e:
        ret = e[0]
    return ret
Esempio n. 5
0
def database_backup(aDict):
    """Function docstring for database_backup. Does Database Backup to file

 Args:
  - filename (required)

 Output:
 """
    ret = {'filename': aDict['filename']}
    from sdcp.SettingsContainer import SC
    if SC['system']['id'] == 'master':
        from mysql import dump
        data = dump({'mode': 'database'})['output']
    else:
        from sdcp.core.common import rest_call
        res = rest_call("%s?mysql_dump" % SC['system']['master'],
                        {'mode': 'database'})
        if res['info'].get("x-z-res") == "OK":
            data = res['data']['output']
        else:
            data = []
    try:
        with open(ret['filename'], 'w+') as f:
            f.write("\n".join(data))
        ret['result'] = 'OK'
    except Exception as err:
        ret['error'] = str(err)
        ret['result'] = 'NOT_OK'
    return ret
Esempio n. 6
0
 def href(self, aURL, aArgs=None, aMethod=None, aHeader=None):
     from sdcp.core.common import rest_call
     head = {'X-Auth-Token': self._token, 'X-Auth-Type': 'openstack'}
     try:
         head.update(aHeader)
     except:
         pass
     return rest_call(aURL, aArgs, aMethod, head)
Esempio n. 7
0
def settings_save(aDict):
    """Function docstring for settings_save TBD

 Args:

 Output:
 """
    from sdcp.core.common import rest_call
    ret = {'config_file': SC['system']['config_file']}
    try:
        settings = {}
        with open(ret['config_file']) as sfile:
            temp = loads(sfile.read())
        for section, content in temp.iteritems():
            for key, params in content.iteritems():
                if not settings.get(section):
                    settings[section] = {}
                settings[section][key] = params['value']
        settings['system']['config_file'] = ret['config_file']

        if settings['system']['id'] == 'master':
            with DB() as db:
                db.do(
                    "SELECT section,parameter,value FROM settings WHERE node = 'master'"
                )
                data = db.get_rows()
                db.do(
                    "SELECT 'node' AS section, node AS parameter, url AS value FROM nodes"
                )
                data.extend(db.get_rows())
            for setting in data:
                section = setting.pop('section')
                if not settings.get(section):
                    settings[section] = {}
                settings[section][setting['parameter']] = setting['value']
        else:
            try:
                master = rest_call(
                    "%s?system_settings_fetch" % settings['system']['master'],
                    {'node': settings['system']['id']})['data']
            except:
                pass
            else:
                for section, content in master.iteritems():
                    if settings.get(section): settings[section].update(content)
                    else: settings[section] = content

        container = ospath.abspath(
            ospath.join(ospath.dirname(__file__), '..',
                        'SettingsContainer.py'))
        with open(container, 'w') as f:
            f.write("SC=%s\n" % dumps(settings))
        ret['result'] = 'OK'
    except Exception as e:
        ret['result'] = 'NOT_OK'
        ret['error'] = str(e)
    return ret
Esempio n. 8
0
 def href(self, aURL, aArgs=None, aMethod=None, aHeader=None):
     from sdcp.core.common import rest_call
     head = {'X-Auth-Token': self._token}
     try:
         head.update(aHeader)
     except:
         pass
     try:
         res = rest_call(aURL, aArgs, aMethod, head)
     except Exception as e:
         res = e[0]
     return res
Esempio n. 9
0
def status(aDict):
    """Function docstring for status TBD

 Args:
  - node (required)

 Output:
 """
    try:
        node = SC['node'][aDict['node']]
        ret = rest_call("%s?id=sdata" % node)['data']
    except Exception as e:
        ret = e[0]
    return ret
Esempio n. 10
0
 def auth(self, aAuth):
     from sdcp.core.common import rest_call
     try:
         auth = {
             'auth': {
                 'scope': {
                     'project': {
                         "name": aAuth.get('project', "admin"),
                         "domain": {
                             'name': 'Default'
                         }
                     }
                 },
                 'identity': {
                     'methods': ['password'],
                     "password": {
                         "user": {
                             "name": aAuth['username'],
                             "domain": {
                                 "name": "Default"
                             },
                             "password": aAuth['password']
                         }
                     }
                 }
             }
         }
         url = "%s:5000/v3/auth/tokens" % (self._node)
         res = rest_call(url, auth)
         # If sock code is created (201), not ok (200) - we can expect to find a token
         if res['code'] == 201:
             token = res.pop('data', {})['token']
             self._token = res['info'].get('x-subject-token')
             self._expire = token['expires_at']
             self._project = token['project']['name']
             self._project_id = token['project']['id']
             catalog = {}
             for svc in token['catalog']:
                 catalog[svc['name']] = svc
             self._catalog = catalog
             res['auth'] = 'OK'
         else:
             res['auth'] = 'NOT_OK'
     except Exception as e:
         res = e[0]
         res['auth'] = 'NOT_OK'
     return res
Esempio n. 11
0
def href(aDict):
    """Function docstring for call. Basically creates a controller instance and send a (nested) rest_call

 Args:
  - href (required)
  - token (required)
  - arguments (optional)
  - method (optional)

 Output:
 """
    try:
        ret = rest_call(aDict.get('href'), aDict.get('arguments'),
                        aDict.get('method', 'GET'),
                        {'X-Auth-Token': aDict['token']})
    except Exception as e:
        ret = e[0]
    return ret
Esempio n. 12
0
def infra(aDict):
    """Function docstring for infra TBD

 Args:
  - node (required)

 Output:
 """
    try:
        ret = {}
        node = SC['node'][aDict['node']]
        info = rest_call("%s?id=sdata" % node)['data']
        ret['sections'] = {d['id']: d['name'] for d in info['sections']}
        ret['rooms'] = {d['id']: d for d in info['rooms']}
        ret['categories'] = {d['id']: d['name'] for d in info['categories']}
        ret['scenes'] = {d['id']: d for d in info['scenes']}
    except Exception as e:
        ret = e[0]
    return ret
Esempio n. 13
0
def devices(aDict):
    """Function docstring for devices TBD

 Args:
  - node (required)
  - room (optional)

 Output:
 """
    try:
        ret = {}
        node = SC['node'][aDict['node']]
        info = rest_call("%s?id=sdata" % node)['data']
        ret['devices'] = info['devices'] if not aDict.get('room') else [
            x for x in info['devices'] if x['room'] == int(aDict.get('room'))
        ]
        ret['categories'] = {d['id']: d['name'] for d in info['categories']}
        ret['rooms'] = {d['id']: d['name'] for d in info['rooms']}
    except Exception as e:
        ret = e[0]
    return ret
Esempio n. 14
0
 def auth(self, aAuth):
     from sdcp.core.common import rest_call
     try:
         auth = {
             'UserName': aAuth.get('username'),
             'Password': aAuth.get('password'),
             'AuthType': 'openstack'
         }
         url = "%s:7000/appformix/controller/v2.0/%s" % (self._node,
                                                         "auth_credentials")
         print url
         res = rest_call(url, auth)
         # If sock code is ok (200) - we can expect to find a token
         if res['code'] == 200:
             token = res.pop('data', {})['Token']
             self._token = token['tokenId']
             self._expire = token['expiresAt']
             res['auth'] = 'OK'
         else:
             res['auth'] = 'NOT_OK'
     except Exception as e:
         res = e[0]
     return res
Esempio n. 15
0
            (settings['system']['db_name'], settings['system']['db_user']))
        stdout.write("FLUSH PRIVILEGES;\n\n")
        stdout.flush()
        raise Exception("DB past error (%s)" % str(e))

else:
    ########################################## NON-MASTER REST ########################################
    #
    # Fetch and update settings from central repo
    #
    from sdcp.core.common import rest_call
    try:
        res['register'] = rest_call(
            "%s?system_node_register" % settings['system']['master'], {
                'node': settings['system']['id'],
                'url': settings['system']['rest'],
                'system': modes.get('rest', '0'),
                'www': modes.get('front', '0')
            })['data']
    except Exception as e:
        res['register'] = str(e)
    try:
        master = rest_call(
            "%s?system_settings_fetch" % settings['system']['master'],
            {'node': settings['system']['id']})['data']
    except:
        pass
    else:
        for section, content in master.iteritems():
            if settings.get(section): settings[section].update(content)
            else: settings[section] = content