code
stringlengths
1
5.19M
package
stringlengths
1
81
path
stringlengths
9
304
filename
stringlengths
4
145
from datetime import timedelta import time from ac_flask.hipchat.db import mongo import jwt import logging import requests from requests.auth import HTTPBasicAuth from werkzeug.exceptions import abort from urlparse import urlparse _log = logging.getLogger(__name__) ACCESS_TOKEN_CACHE = "hipchat-tokens:{oauth_id}" def base_url(url): if not url: return None result = urlparse(url) return "{scheme}://{netloc}".format(scheme=result.scheme, netloc=result.netloc) class Tenant: def __init__(self, id, secret=None, homepage=None, capabilities_url=None, room_id=None, token_url=None, group_id=None, group_name=None, capdoc=None): self.id = id self.room_id = room_id self.secret = secret self.group_id = group_id self.group_name = None if not group_name else group_name self.homepage = homepage or None if not capdoc else capdoc['links']['homepage'] self.token_url = token_url or None if not capdoc else capdoc['capabilities']['oauth2Provider']['tokenUrl'] self.capabilities_url = capabilities_url or None if not capdoc else capdoc['links']['self'] self.api_base_url = capdoc['capabilities']['hipchatApiProvider']['url'] if capdoc \ else self.capabilities_url[0:self.capabilities_url.rfind('/')] if self.capabilities_url else None self.installed_from = base_url(self.token_url) def to_map(self): return { "id": self.id, "secret": self.secret, "room_id": self.room_id, "group_id": self.group_id, "group_name": self.group_name, "homepage": self.homepage, "token_url": self.token_url, "capabilities_url": self.capabilities_url } @staticmethod def from_map(data): filtered = {key: val for key, val in data.items() if not key.startswith('_')} return Tenant(**filtered) @staticmethod def load(client_id): client_data = mongo.clients.find_one(Tenant(client_id).id_query) if client_data: return Tenant.from_map(client_data) else: _log.warn("Cannot find client: %s" % client_id) abort(400) @property def id_query(self): return {"id": self.id} def get_token(self, cache, token_only=True, scopes=None): if scopes is None: scopes = ["send_notification"] cache_key = ACCESS_TOKEN_CACHE.format(oauth_id=self.id) cache_key += ":" + ",".join(scopes) def gen_token(): resp = requests.post(self.token_url, data={"grant_type": "client_credentials", "scope": " ".join(scopes)}, auth=HTTPBasicAuth(self.id, self.secret), timeout=10) if resp.status_code == 200: _log.debug("Token request response: " + resp.text) return resp.json() elif resp.status_code == 401: _log.error("Client %s is invalid but we weren't notified. Uninstalling" % self.id) raise OauthClientInvalidError(self) else: raise Exception("Invalid token: %s" % resp.text) if token_only: token = cache.get(cache_key) if not token: data = gen_token() token = data['access_token'] cache.setex(cache_key, token, data['expires_in'] - 20) return token else: return gen_token() def sign_jwt(self, user_id, data=None): if data is None: data = {} now = int(time.time()) exp = now + timedelta(hours=1).total_seconds() jwt_data = {"iss": self.id, "iat": now, "exp": exp} if user_id: jwt_data['sub'] = user_id data.update(jwt_data) return jwt.encode(data, self.secret) class OauthClientInvalidError(Exception): def __init__(self, client, *args, **kwargs): super(OauthClientInvalidError, self).__init__(*args, **kwargs) self.client = client
AC-Flask-HipChat
/AC-Flask-HipChat-0.2.12.tar.gz/AC-Flask-HipChat-0.2.12/ac_flask/hipchat/tenant.py
tenant.py
from functools import wraps import httplib import logging from ac_flask.hipchat import installable from ac_flask.hipchat.auth import require_tenant, tenant import os from flask import jsonify, request from urlparse import urlparse _log = logging.getLogger(__name__) def _not_none(app, name, default): val = app.config.get(name, default) if val is not None: return val else: raise ValueError("Missing '{key}' configuration property".format(key=name)) class Addon(object): def __init__(self, app, key=None, name=None, description=None, config=None, env_prefix="AC_", allow_room=True, allow_global=False, scopes=None, vendor_name=None, vendor_url=None, avatar=None): if scopes is None: scopes = ['send_notification'] if avatar is None: avatar_url = "https://abotars.hipch.at/bot/" + _not_none(app, 'ADDON_KEY', key) + ".png" avatar = { "url": avatar_url, "url@2x": avatar_url } self.app = app self._init_app(app, config, env_prefix) self.descriptor = { "key": _not_none(app, 'ADDON_KEY', key), "name": _not_none(app, 'ADDON_NAME', name), "description": app.config.get('ADDON_DESCRIPTION', description) or "", "links": { "self": self._relative_to_base("/addon/descriptor") }, "capabilities": { "installable": { "allowRoom": allow_room, "allowGlobal": allow_global }, "hipchatApiConsumer": { "scopes": scopes, "avatar": avatar } }, "vendor": { "url": app.config.get('ADDON_VENDOR_URL', vendor_url) or "", "name": app.config.get('ADDON_VENDOR_NAME', vendor_name) or "" } } if app.config.get('BASE_URL') is not None and app.config.get('AVATAR_URL') is not None: self.descriptor['capabilities']['hipchatApiConsumer']['avatar'] = { 'url': app.config.get('BASE_URL') + app.config.get('AVATAR_URL') } installable.init(addon=self, allow_global=allow_global, allow_room=allow_room) @self.app.route("/addon/descriptor") def descriptor(): return jsonify(self.descriptor) self.app.route("/")(descriptor) @staticmethod def _init_app(app, config, env_prefix): app.config.from_object('ac_flask.hipchat.default_settings') if config is not None: app.config.from_object(config) if env_prefix is not None: env_vars = {key[len(env_prefix):]: val for key, val in os.environ.items()} app.config.update(env_vars) if app.config['DEBUG']: # These two lines enable debugging at httplib level (requests->urllib3->httplib) # You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA. # The only thing missing will be the response.body which is not logged. httplib.HTTPConnection.debuglevel = 1 # You must initialize logging, otherwise you'll not see debug output. logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True else: logging.basicConfig() logging.getLogger().setLevel(logging.WARN) app.events = {} def configure_page(self, path="/configure", **kwargs): self.descriptor['capabilities'].setdefault('configurable', {})['url'] = self._relative_to_base(path) def inner(func): return self.app.route(rule=path, **kwargs)(require_tenant(func)) return inner def webhook(self, event, name=None, pattern=None, path=None, auth="jwt", **kwargs): if path is None: path = "/event/" + event wh = { "event": event, "url": self._relative_to_base(path), "authentication": auth } if name is not None: wh['name'] = name if pattern is not None: wh['pattern'] = pattern self.descriptor['capabilities'].setdefault('webhook', []).append(wh) def inner(func): return self.app.route(rule=path, methods=['POST'], **kwargs)(require_tenant(func)) return inner def route(self, anonymous=False, *args, **kwargs): """ Decorator for routes with defaulted required authenticated tenants """ def inner(func): if not anonymous: func = require_tenant(func) func = self.app.route(*args, **kwargs)(func) return func return inner def glance(self, key, name, target, icon, icon2x=None, conditions=None, anonymous=False, path=None, **kwargs): if path is None: path = "/glance/" + key if icon2x is None: icon2x = icon glance_capability = { "key": key, "name": { "value": name }, "queryUrl": self._relative_to_base(path), "target": target, "icon": { "url": self._relative_to_base(icon), "url@2x": self._relative_to_base(icon2x) }, "conditions": conditions or [] } self.descriptor['capabilities'].setdefault('glance', []).append(glance_capability) def inner(func): return self.route(anonymous, rule=path, **kwargs)(self.cors(self.json_output(func))) return inner def webpanel(self, key, name, location="hipchat.sidebar.right", anonymous=False, path=None, **kwargs): if path is None: path = "/webpanel/" + key webpanel_capability = { "key": key, "name": { "value": name }, "url": self._relative_to_base(path), "location": location } self.descriptor['capabilities'].setdefault('webPanel', []).append(webpanel_capability) def inner(func): return self.route(anonymous, rule=path, **kwargs)(func) return inner def cors(self, func): @wraps(func) def inner(*args, **kwargs): whitelisted_origin = self._get_white_listed_origin() installed_from = tenant.installed_from if tenant else None response = self.app.make_response(func(*args, **kwargs)) response.headers['Access-Control-Allow-Origin'] = whitelisted_origin or installed_from or '*' return response return inner def json_output(self, func): @wraps(func) def inner(*args, **kwargs): res = func(*args, **kwargs) return jsonify(res) if isinstance(res, dict) else res return inner def _relative_to_base(self, path): base = self.app.config['BASE_URL'] path = '/' + path if not path.startswith('/') else path return base + path def _get_white_listed_origin(self): try: origin = request.headers['origin'] if origin: origin_url = urlparse(origin) if origin_url and origin_url.hostname.endswith(self.app.config['CORS_WHITELIST']): return origin return None except KeyError: return None def run(self, *args, **kwargs): if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': print("") print("--------------------------------------") print("Public descriptor base URL: %s" % self.app.config['BASE_URL']) print("--------------------------------------") print("") self.app.run(*args, **kwargs)
AC-Flask-HipChat
/AC-Flask-HipChat-0.2.12.tar.gz/AC-Flask-HipChat-0.2.12/ac_flask/hipchat/addon.py
addon.py
class Glance(object): def __init__(self): self.data = {} def with_label(self, value, glance_type="html"): self.data["label"] = { "value": value, "type": glance_type } return self def with_lozenge(self, label, lozenge_type): self.data["status"] = { "type": "lozenge", "value": { "label": label, "type": lozenge_type } } return self def with_icon(self, url, url2x): self.data["status"] = { "type": "icon", "value": { "url": url, "url@2x": url2x } } return self
AC-Flask-HipChat
/AC-Flask-HipChat-0.2.12.tar.gz/AC-Flask-HipChat-0.2.12/ac_flask/hipchat/glance.py
glance.py
from .addon import Addon from .events import events from .auth import * from .clients import *
AC-Flask-HipChat
/AC-Flask-HipChat-0.2.12.tar.gz/AC-Flask-HipChat-0.2.12/ac_flask/hipchat/__init__.py
__init__.py
# About ACAutomaton Python Package High-performance multi-string lookup data structure # Notice 1. If you want to insert unicode string, please encode them to byte string first. 2. Once you insert a new word to ACAutomaton, please remember call build method. You can call build method multiple times. # Install pip install ACAutomaton # Usage >>> from ACAutomaton import ACAutomaton >>> a = ACAutomaton() >>> a.insert('11') >>> a.insert('22') >>> a.insert('33') >>> a.build() >>> a.matchOne('0011222333') (2, '11') >>> a.matchOne('00') (-1, None) >>> a.matchAll('0011222333') [(2, '11'), (4, '22'), (5, '22'), (7, '33'), (7, '33'), (8, '33'), (8, '33')] example for unicode string >>> from ACAutomaton import ACAutomaton >>> a = ACAutomaton() >>> a.insert('你好') >>> a.insert('你坏') >>> a.insert('你') >>> a.build() >>> a.matchOne('你好你坏你') (0, '\xe4\xbd\xa0') >>> a.matchAll('你好你坏你不存在') [(0, '\xe4\xbd\xa0'), (0, '\xe4\xbd\xa0\xe5\xa5\xbd'), (6, '\xe4\xbd\xa0'), (6, '\xe4\xbd\xa0\xe5\x9d\x8f'), (12, '\xe4\xbd\xa0')] >>> a.matchAll('不存在') [] >>> a.insert('不存在') >>> a.build() >>> a.matchAll('不存在') [(0, '\xe4\xb8\x8d\xe5\xad\x98\xe5\x9c\xa8')]
ACAutomaton
/ACAutomaton-1.0.3.tar.gz/ACAutomaton-1.0.3/README.md
README.md
__author__ = 'ding' from distutils.core import setup, Extension with open("README.md", "r") as fh: long_description = fh.read() setup( name="ACAutomaton", description="ACAutomaton python wrapper,support unicode", author="Yaguang Ding", author_email="dingyaguang117@gmail.com", long_description=long_description, long_description_content_type="text/markdown", url="http://github.com/dingyaguang117/ACAutomaton", packages=['ACAutomaton'], ext_modules = [ Extension("_ACAutomaton", sources=['ACAutomaton/wrapper.cpp', 'ACAutomaton/_ACAutomaton.cpp'], include_dirs=['./ACAutomaton'], ) ], classifiers=[ "Programming Language :: Python", ], keywords='ac-automation ac automation', python_requires='>=2.6', version='1.0.3' )
ACAutomaton
/ACAutomaton-1.0.3.tar.gz/ACAutomaton-1.0.3/setup.py
setup.py
# Always Correct Correctness Compiler Python implementation of a very basic langage compiler that never throw errors while compiling. (almost) Its not a big and complex compiler, and its implementation is something like awful. Some links are given below. ## Errors The only errors releved by the compiler is : - source code contains characters not present in provided alphabet; - provided vocabulary don't follow conventions of writing; If these conditions are respected, whatever you give to the __ACCC__, it will always return something valid. (but it can be an empty code) ## Bias If compiled source code is too short, or made of lots of repetitions, some bias can appear: - always same values in object code - lots of neutral values The bigger is the vocabulary and bigger is the list of lexems, the less bias will appear. ## Interests A compilable source code is a string of characters. Valid characters are provided at Compiler instanciation. For example, if you have the alphabet *'01'*, any string exclusively composed of *'0'* and *'1'* is compilable and will produce something. Any little modification of the string can lead to heavy or no modification of object code. In fact, with ACCC you can generate mutation of a source code without problem of compilation error. Write a code with lots of parameters is another way to do almost the same thing. ## Object code Currently, current object langage is __very simple__: you can compare things, and do things. That's all. No loops, variables, functions, objects,… Just conditions and actions. This is an example of code, not totally illogic, created one time with a source code size of 60 and the alphabet '01': (indentation can miss) if parameter1 == parameter2 and haveThat: do_that if have_that: say_this do_that if know_that and have_many_things: do_that say_this do_that if have_many_things: say_this Please have a look to docstring of *Compiler* class for more details about that. (notabily used vocabulary) ## I/O speaking Inputs: - iterable of characters (doublons are unexpected) that compose the source code - vocabulary used for compiling Outputs: - a python compilable code, according to vocabulary ## Next improvements In random-priority order: - [ ] allow lexems to have arguments; - [ ] create before convert in any langage; - [ ] allow configuration of output langage; - [ ] unit tests; - [ ] usage example; - [ ] base tables on source code instead of only vocabulary; - [X] upload on pypi and github (see links below); ## Why don't you use… Someone do the same thing ? Or better ? Give me the link, i want to see that ! ## Why do that ? 1. It's fun 2. I need it for test something in another project (an Evolution simulation named [EvolAcc](http://www.github.com/Aluriak/EvolAcc) ; no surprise) ## Links - ACCC on [github](http://www.github.com/Aluriak/ACCC); - ACCC on [pypi](https://pypi.python.org/pypi/ACCC);
ACCC
/ACCC-0.0.3.tar.gz/ACCC-0.0.3/README.mkd
README.mkd
# -*- coding: utf-8 -*- __name__ = "ACCC" __version__ = "0.0.3"
ACCC
/ACCC-0.0.3.tar.gz/ACCC-0.0.3/info.py
info.py
# -*- coding: utf-8 -*- ######################### # SETUP.PY # ######################### ######################### # IMPORTS # ######################### from setuptools import setup, find_packages from info import __version__, __name__ ######################### # SETUP # ######################### setup( name = __name__, version = __version__, py_modules = ['info'], packages = find_packages(exclude=['accc/']), package_data = { __name__ : ['README.mkd', 'LICENSE.txt'] }, include_package_data = True, zip_safe=False, # needed for avoided marshalling error author = "aluriak", author_email = "lucas.bourneuf@laposte.net", description = "Always Correct Correctness Compilator", long_description = open('README.mkd').read(), keywords = "compilation compiler correctness", url = "https://github.com/Aluriak/ACCC", classifiers = [ "License :: OSI Approved :: GNU General Public License (GPL)", "Natural Language :: English", "Operating System :: Unix", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Software Development :: Code Generators", "Topic :: Software Development :: Compilers", ] )
ACCC
/ACCC-0.0.3.tar.gz/ACCC-0.0.3/setup.py
setup.py
# -*- coding: utf-8 -*- ######################### # IMPORTS # ######################### from accc.compiler import Compiler from accc.langspec import python_spec import random, time ######################### # PRE-DECLARATIONS # ######################### ######################### # MAIN # ######################### if __name__ == '__main__': def mutated(source_code, alphabet): """return an imperfect copy of source_code, modified at a random index""" source_code = list(source_code) index = random.randrange(0, len(source_code)) old = source_code[index] while source_code[index] is old: source_code[index] = random.choice(alphabet) return ''.join(source_code) # create compiler alphabet = '01' cc = Compiler(alphabet, python_spec, ('parameter1', 'parameter2', 'parameter3', 'parameter4', 'int_value'), ('have_that', 'is_this', 'have_many_things', 'know_that'), ('do_that', 'say_this', 'do_it'), ('>', '==', '<', 'is', '!='), ) # print source code, compile it, modify it, and loop ad vitam eternam source_code_size = 60 source = ''.join((random.choice(alphabet) for _ in range(source_code_size))) while True: print(source) msource = mutated(source, alphabet) print(''.join([' ' if n == m else m for n, m in zip(source, msource)])) print(cc.compile(msource)) print(source_code_size*'-') source = msource time.sleep(0.1)
ACCC
/ACCC-0.0.3.tar.gz/ACCC-0.0.3/accc/__main__.py
__main__.py
from accc.compiler import * from accc.dnacompiler import *
ACCC
/ACCC-0.0.3.tar.gz/ACCC-0.0.3/accc/__init__.py
__init__.py
from accc.langspec.langspec import *
ACCC
/ACCC-0.0.3.tar.gz/ACCC-0.0.3/accc/langspec/__init__.py
__init__.py
# -*- coding: utf-8 -*- ######################### # LANGUAGE # ######################### """ This module describes languages specifications for ACCC. """ ######################### # IMPORTS # ######################### from accc.lexems import * ######################### # PRE-DECLARATIONS # ######################### # keys of INDENTATION = 'indent' BEG_BLOCK = 'begin_block' END_BLOCK = 'end_block' BEG_LINE = 'begin line' END_LINE = 'end line' BEG_ACTION = 'begin action' END_ACTION = 'end action' BEG_CONDITION = 'begin condition' END_CONDITION = 'end condition' LOGICAL_AND = 'logical and' LOGICAL_OR = 'logical or' ######################### # CONSTRUCTION FUNCTION # ######################### def constructSpec(indentation, begin_block, end_block, begin_line, end_line, begin_action, end_action, begin_condition, end_condition, logical_and, logical_or): """Return a language specification based on parameters.""" return { INDENTATION : indentation, BEG_BLOCK : begin_block, END_BLOCK : end_block, BEG_LINE : begin_line, END_LINE : end_line, BEG_ACTION : begin_action, END_ACTION : end_action, BEG_CONDITION : begin_condition, END_CONDITION : end_condition, LOGICAL_AND : logical_and, LOGICAL_OR : logical_or } ######################### # TRANSLATED FUNCTION # ######################### def translated(structure, values, lang_spec): """Return code associated to given structure and values, translate with given language specification.""" # LANGUAGE SPECS indentation = '\t' endline = '\n' object_code = "" stack = [] # define shortcuts to behavior push = lambda x: stack.append(x) pop = lambda : stack.pop() last = lambda : stack[-1] if len(stack) > 0 else ' ' def indented_code(s, level, end): return lang_spec[INDENTATION]*level + s + end # recreate python structure, and replace type by value level = 0 CONDITIONS = [LEXEM_TYPE_PREDICAT, LEXEM_TYPE_CONDITION] ACTION = LEXEM_TYPE_ACTION DOWNLEVEL = LEXEM_TYPE_DOWNLEVEL for lexem_type in structure: if lexem_type is ACTION: # place previous conditions if necessary if last() in CONDITIONS: # construct conditions lines value, values = values[0:len(stack)], values[len(stack):] object_code += (indented_code(lang_spec[BEG_CONDITION] + lang_spec[LOGICAL_AND].join(value) + lang_spec[END_CONDITION], level, lang_spec[END_LINE] )) # if provided, print the begin block token on a new line if len(lang_spec[BEG_BLOCK]) > 0: object_code += indented_code( lang_spec[BEG_BLOCK], level, lang_spec[END_LINE] ) stack = [] level += 1 # and place the action object_code += indented_code( lang_spec[BEG_ACTION] + values[0], level, lang_spec[END_ACTION]+lang_spec[END_LINE] ) values = values[1:] elif lexem_type in CONDITIONS: push(lexem_type) elif lexem_type is DOWNLEVEL: if last() not in CONDITIONS: # down level, and add a END_BLOCK only if needed level -= 1 if level >= 0: object_code += indented_code( lang_spec[END_BLOCK], level, lang_spec[END_LINE] ) else: level = 0 # add END_BLOCK while needed for reach level 0 while level > 0: level -= 1 if level >= 0: object_code += indented_code( lang_spec[END_BLOCK], level, lang_spec[END_LINE] ) else: level = 0 # Finished ! return object_code ######################### # C++ # ######################### def cpp_spec(): """C++ specification, provided for example, and java compatible.""" return { INDENTATION : '\t', BEG_BLOCK : '{', END_BLOCK : '}', BEG_LINE : '', END_LINE : '\n', BEG_ACTION : '', END_ACTION : ';', BEG_CONDITION : 'if(', END_CONDITION : ')', LOGICAL_AND : ' && ', LOGICAL_OR : ' || ' } ######################### # ADA # ######################### def ada_spec(): """Ada specification, provided for example""" return { INDENTATION : '\t', BEG_BLOCK : '', END_BLOCK : 'end if;', BEG_LINE : '', END_LINE : '\n', BEG_ACTION : '', END_ACTION : ';', BEG_CONDITION : 'if ', END_CONDITION : ' then', LOGICAL_AND : ' and ', LOGICAL_OR : ' or ' } ######################### # PYTHON # ######################### def python_spec(): """Python specification, provided for use""" return { INDENTATION : '\t', BEG_BLOCK : '', END_BLOCK : '', BEG_LINE : '', END_LINE : '\n', BEG_ACTION : '', END_ACTION : '', BEG_CONDITION : 'if ', END_CONDITION : ':', LOGICAL_AND : ' and ', LOGICAL_OR : ' or ' }
ACCC
/ACCC-0.0.3.tar.gz/ACCC-0.0.3/accc/langspec/langspec.py
langspec.py
from accc.compiler.compiler import *
ACCC
/ACCC-0.0.3.tar.gz/ACCC-0.0.3/accc/compiler/__init__.py
__init__.py
# -*- coding: utf-8 -*- ######################### # IMPORTS # ######################### from math import log, ceil from itertools import zip_longest from functools import partial, lru_cache import itertools import accc.langspec as langspec ######################### # PRE-DECLARATIONS # ######################### # lexems seens in structure from accc.lexems import LEXEM_TYPE_CONDITION, LEXEM_TYPE_ACTION from accc.lexems import LEXEM_TYPE_PREDICAT, LEXEM_TYPE_DOWNLEVEL # lexems only seen in values from accc.lexems import LEXEM_TYPE_COMPARISON, LEXEM_TYPE_OPERATOR from accc.lexems import LEXEM_TYPE_UINTEGER # all lexems from accc.lexems import ALL as ALL_LEXEMS ######################### # COMPILER CLASS # ######################### class Compiler(): """ Compiler of code writed with any vocabulary. ('01', 'ATGC', 'whatevr',…) A source code is an ordered list of vocabulary elements ('10011010000101', 'AGGATGATCAGATA', 'wtrvwhttera'…). Whatever the given source_code, it's always compilable. (but can return empty object code) Also, it can be totally illogic (do many times the same test, do nothing,…) The source code is readed entirely for determine STRUCTURE, and then re-readed for determines effectives VALUES. The STRUCTURE defines: - logic of the code - lexems type that will be used The VALUES defines: - what are the exact value of each lexem - values of integers used as function parameters Example of prettified STRUCTURE: if C: A if C: A A if P and P: A A A if P: A VALUES will describes which is the lexem effectively used for each word, C, A or P. (condition, action, predicat) NB: D is the char that indicate a indent level decrease The dictionnary values vocabulary, given at compiler creation, define lexems : vocabulary_values = { LEXEM_TYPE_COMPARISON: ('parameter1', 'parameter2', 'parameter3', 'parameter4'), LEXEM_TYPE_PREDICAT : ('have_that', 'is_this', 'have_many_things', 'know_that'), LEXEM_TYPE_ACTION : ('do_that', 'say_this'), LEXEM_TYPE_OPERATOR : ('>', '==', '<', 'is', '!='), } Then, compiled code can be something like: if parameter1 == parameter2 and have_that: do_that if have_that: say_this do_that if know_that and have_many_things: do_that say_this do_that if have_many_things: say_this Modification of provided lexems types is not supported at this time. """ # CONSTRUCTOR ################################################################# def __init__(self, alphabet, target_language_spec, comparables, predicats, actions, operators, neutral_value_condition='True', neutral_value_action='pass'): """ Wait for alphabet ('01', 'ATGC',…), language specification and vocabularies of structure and values parts. Neutral value is used when no value is finded. Set it to something that pass in all cases. NB: a little source code lead to lots of neutral values. """ self.alphabet = alphabet self.voc_structure = ALL_LEXEMS self.target_lang_spec = target_language_spec() self.voc_values = { LEXEM_TYPE_COMPARISON: comparables, LEXEM_TYPE_PREDICAT : predicats, LEXEM_TYPE_ACTION : actions, LEXEM_TYPE_OPERATOR : operators, } self.neutral_value_action = neutral_value_action self.neutral_value_condition = neutral_value_condition # verifications assert(issubclass(neutral_value_action.__class__, str) and issubclass(neutral_value_condition.__class__, str) ) # prepare tables of words->lexems self._initialize_tables() # PUBLIC METHODS ############################################################### def compile(self, source_code, post_treatment=''.join): """Compile given source code. Return object code, modified by given post treatment. """ # read structure structure = self._structure(source_code) values = self._struct_to_values(structure, source_code) # create object code, translated in targeted language obj_code = langspec.translated( structure, values, self.target_lang_spec ) # apply post treatment and return return obj_code if post_treatment is None else post_treatment(obj_code) # PRIVATE METHODS ############################################################## def _initialize_tables(self): """Create tables for structure and values, word->vocabulary""" # structure table self.table_struct, self.idnt_struct_size = self._create_struct_table() # values table self.table_values, self.idnt_values_size = self._create_values_table() # debug print #print(self.table_struct) #print(self.idnt_struct_size) #print(self.table_values) #print(self.idnt_values_size) def _structure(self, source_code): """return structure in ACDP format.""" # define cutter as a per block reader def cutter(seq, block_size): for index in range(0, len(seq), block_size): lexem = seq[index:index+block_size] if len(lexem) == block_size: yield self.table_struct[seq[index:index+block_size]] return tuple(cutter(source_code, self.idnt_struct_size)) def _next_lexem(self, lexem_type, source_code, source_code_size): """Return next readable lexem of given type in source_code. If no value can be found, the neutral_value will be used""" # define reader as a lexem extractor def reader(seq, block_size): identificator = '' for char in source_code: if len(identificator) == self.idnt_values_size[lexem_type]: yield self.table_values[lexem_type][identificator] identificator = '' identificator += char lexem_reader = reader(source_code, self.idnt_values_size) lexem = None time_out = 0 while lexem == None and time_out < 2*source_code_size: lexem = next(lexem_reader) time_out += 1 # here we have found a lexem return lexem def _next_condition_lexems(self, source_code, source_code_size): """Return condition lexem readed in source_code""" # find three lexems lexems = tuple(( self._next_lexem(LEXEM_TYPE_COMPARISON, source_code, source_code_size), self._next_lexem(LEXEM_TYPE_OPERATOR , source_code, source_code_size), self._next_lexem(LEXEM_TYPE_COMPARISON, source_code, source_code_size) )) # verify integrity if None in lexems: # one of the condition lexem was not found in source code return None else: # all lexems are valid return ' '.join(lexems) @lru_cache(maxsize = 100) def _string_to_int(self, s): """Read an integer in s, in Little Indian. """ base = len(self.alphabet) return sum((self._letter_to_int(l) * base**lsb for lsb, l in enumerate(s) )) @lru_cache(maxsize = None) def _letter_to_int(self, l): return self.alphabet.index(l) @lru_cache(maxsize = 127) # source code is potentially largely variable on length def _integer_size_for(self, source_code_size): """Find and return the optimal integer size. A perfect integer can address all indexes of a string of size source_code_size. """ return ceil(log(source_code_size, len(self.alphabet))) def _struct_to_values(self, structure, source_code): """Return list of values readed in source_code, according to given structure. """ # iterate on source code until all values are finded # if a value is not foundable, # (ie its identificator is not in source code) # it will be replaced by associated neutral value iter_source_code = itertools.cycle(source_code) values = [] for lexem_type in (l for l in structure if l is not 'D'): if lexem_type is LEXEM_TYPE_CONDITION: new_value = self._next_condition_lexems( iter_source_code, len(source_code) ) else: new_value = self._next_lexem( lexem_type, iter_source_code, len(source_code) ) # if values is unvalid: # association with the right neutral value if new_value is None: if lexem_type in (LEXEM_TYPE_PREDICAT, LEXEM_TYPE_CONDITION): new_value = self.neutral_value_condition else: new_value = self.neutral_value_action values.append(new_value) return values # TABLE METHODS ################################################################ def _create_struct_table(self): """Create table identificator->vocabulary, and return it with size of an identificator""" len_alph = len(self.alphabet) len_vocb = len(self.voc_structure) identificator_size = ceil(log(len_vocb, len_alph)) # create list of lexems num2alph = lambda x, n: self.alphabet[(x // len_alph**n) % len_alph] identificators = [[str(num2alph(x, n)) for n in range(identificator_size) ] for x in range(len_vocb) ] # initialize table and iterable identificators_table = {} zip_id_voc = zip_longest( identificators, self.voc_structure, fillvalue=None ) # create dict identificator:word for idt, word in zip_id_voc: identificators_table[''.join(idt)] = word return identificators_table, identificator_size def _create_values_table(self): """Create table lexem_type->{identificator->vocabulary}, and return it with sizes of an identificator as lexem_type->identificator_size""" # number of existing character, and returned dicts len_alph = len(self.alphabet) identificators_table = {k:{} for k in self.voc_values.keys()} identificators_sizes = {k:-1 for k in self.voc_values.keys()} for lexem_type, vocabulary in self.voc_values.items(): # find number of different values that can be found, # and size of an identificator. len_vocb = len(vocabulary) identificators_sizes[lexem_type] = ceil(log(len_vocb, len_alph)) # create list of possible identificators num2alph = lambda x, n: self.alphabet[(x // len_alph**n) % len_alph] identificators = [[str(num2alph(x, n)) for n in range(identificators_sizes[lexem_type]) ] # this list is an identificator for x in range(len_alph**identificators_sizes[lexem_type]) ] # this one is a list of identificator # initialize iterable zip_id_voc = zip_longest( identificators, vocabulary, fillvalue=None ) # create dict {identificator:word} for idt, voc in zip_id_voc: identificators_table[lexem_type][''.join(idt)] = voc # return all return identificators_table, identificators_sizes # PREDICATS ################################################################### # ACCESSORS ################################################################### # CONVERSION ################################################################## # OPERATORS ###################################################################
ACCC
/ACCC-0.0.3.tar.gz/ACCC-0.0.3/accc/compiler/compiler.py
compiler.py
# -*- coding: utf-8 -*- ######################### # DNACOMPILER # ######################### ######################### # IMPORTS # ######################### from accc.compiler import Compiler ######################### # PRE-DECLARATIONS # ######################### ######################### # DNACOMPILER CLASS # ######################### class DNACompiler(Compiler): """ Compiler specialized in DNA: vocabulary is 'ATGC'. """ def __init__(self, target_language_spec, comparables, predicats, actions, operators): """""" super().__init__('ATGC', target_language_spec, comparables, predicats, actions, operators) ######################### # FUNCTIONS # ######################### if __name__ == '__main__': import random, time from accc.langspec import python as python_spec def mutated(dna, mutation_rate=0.1): new_dna = '' for nuc in dna: if random.random() < mutation_rate: new_dna += random.choice(dc.alphabet) else: new_dna += nuc return new_dna dc = DNACompiler(python_spec, ('temperature',), ('haveNeighbors',), ('die', 'duplicate'), ('>', '==', '<') ) # print source code, compile it, modify it, and loop ad vitam eternam dna = ''.join((random.choice(dc.alphabet) for _ in range(40))) while True: print(dna) mdna = mutated(dna) print(''.join([' ' if n == m else '!' for n, m in zip(dna, mdna)])) print(dc.compile(mdna)) print(dc.header(dna), dc.structure(dna), dc.values(dna), sep='|', end='\n------------\n\n\n\n') time.sleep(0.4)
ACCC
/ACCC-0.0.3.tar.gz/ACCC-0.0.3/accc/dnacompiler/dnacompiler.py
dnacompiler.py
from accc.dnacompiler.dnacompiler import *
ACCC
/ACCC-0.0.3.tar.gz/ACCC-0.0.3/accc/dnacompiler/__init__.py
__init__.py
from accc.lexems.lexems import *
ACCC
/ACCC-0.0.3.tar.gz/ACCC-0.0.3/accc/lexems/__init__.py
__init__.py
# -*- coding: utf-8 -*- ######################### # ACCC LEXEMS # ######################### ######################### # IMPORTS # ######################### ######################### # PRE-DECLARATIONS # ######################### # lexems seens in structure LEXEM_TYPE_CONDITION = 'C' LEXEM_TYPE_ACTION = 'A' LEXEM_TYPE_PREDICAT = 'P' LEXEM_TYPE_DOWNLEVEL = 'D' # lexems only seen in values LEXEM_TYPE_COMPARISON = 'C' LEXEM_TYPE_OPERATOR = 'O' LEXEM_TYPE_UINTEGER = 'U' # unsigned integer # shortcuts ALL = [ LEXEM_TYPE_CONDITION, LEXEM_TYPE_ACTION, LEXEM_TYPE_PREDICAT, LEXEM_TYPE_DOWNLEVEL, ] ######################### # FUNCTIONS # #########################
ACCC
/ACCC-0.0.3.tar.gz/ACCC-0.0.3/accc/lexems/lexems.py
lexems.py
import yaml import warnings import getpass import pandas as pd import sys import re import pickle def ask_user_password(prompt): return getpass.getpass(prompt + ": ") def create_mssql_connection(username='cranedra', host='clarityprod.uphs.upenn.edu', database='clarity_snapshot_db', domain='UPHS', port='1433', timeout=600, password=None): from sqlalchemy import create_engine if password is None: password = ask_user_password("PW") user = domain + '\\' + username return create_engine('mssql+pymssql://{}:{}@{}:{}/{}?timeout={}'. \ format(user, password, host, port, database, timeout)) def get_clarity_conn(path_to_clarity_creds=None): if path_to_clarity_creds is None: print("put your creds in a yaml file somewhere safeish and then rerun this function with the path as argument") return with open(path_to_clarity_creds) as f: creds = yaml.safe_load(f) return create_mssql_connection(password=creds['pass']) def get_res_dict(q, conn, params = None): res = conn.execute(q, params) data = res.fetchall() data_d = [dict(zip(res.keys(), r)) for r in data] return data_d def SQLquery2df(q, conn, params=None): return pd.DataFrame(get_res_dict(q, conn, params)) # function to get data def get_from_clarity_then_save(query=None, clar_conn=None, save_path=None): """function to get data from clarity and then save it, or to pull saved data """ # make sure that you're not accidentally saving to the cloud if save_path is not None: # make sure you're not saving it to box or dropbox assert ("Dropbox" or "Box") not in save_path, "don't save PHI to the cloud, you goofus" # now get the data try: db_out = get_res_dict(query, clar_conn) except Exception as e: print(e) # print("error: problem with query or connection") return # move it to a df df = pd.DataFrame(db_out) # save it if save_path is not None: try: df.to_json(save_path) except Exception: print("error: problem saving the file") return df def get_res_with_values(q, values, conn): res = conn.execute(q, values) data = res.fetchall() data_d = [dict(r.items()) for r in data] return data_d def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] def chunk_res_with_values(query, ids, conn, chunk_size=10000, params=None): if params is None: params = {} res = [] for sub_ids in chunks(ids, chunk_size): print('.', end='') params.update({'ids': sub_ids}) res.append(pd.DataFrame(get_res_with_values(query, params, conn))) print('') return pd.concat(res, ignore_index=True) def combine_notes(df, grouper="PAT_ENC_CSN_ID"): full_notes = [] for g, dfi in df.groupby(grouper): full_note = '\n'.join( ' '.join(list(dfi.sort_values(['NOTE_ENTRY_TIME', 'NOTE_LINE'])['NOTE_TEXT'])).split(' ')) row = dfi.iloc[0].to_dict() _ = row.pop('NOTE_TEXT') _ = row.pop('NOTE_LINE') row['NOTE_TEXT'] = full_note full_notes.append(row) return pd.DataFrame(full_notes) def combine_notes_by_type(df, CSN="PAT_ENC_CSN_ID", note_type="IP_NOTE_TYPE"): full_notes = [] for g, dfi in df.groupby(CSN): dfis = dfi.sort_values(['NOTE_ENTRY_TIME', 'NOTE_LINE'])[['NOTE_TEXT', note_type, 'NOTE_ENTRY_TIME', 'NOTE_ID', 'NOTE_STATUS']] full_note = "" current_type = "YARR, HERE BE ERRORS IF YE SCRY THIS IN ANY OUTPUT, MATEY" for i in range(nrow(dfis)): if current_type != dfis[note_type].iloc[i]: # prepend separator full_note += f"\n\n#### {dfis[note_type].iloc[i]}, {dfis['NOTE_ENTRY_TIME'].iloc[i]}, " \ f"ID: {dfis['NOTE_ID'].iloc[i]}, " \ f"Status: {note_status_mapper(dfis['NOTE_STATUS'].iloc[i])} ####\n" current_type = dfis[note_type].iloc[i] full_note += '\n'.join(dfis['NOTE_TEXT'].iloc[i].split(' ')) row = dfi.iloc[0].to_dict() _ = row.pop('NOTE_TEXT') _ = row.pop('NOTE_LINE') _ = row.pop(note_type) row['NOTE_TEXT'] = full_note full_notes.append(row) return pd.DataFrame(full_notes) def combine_all_notes(df, cohort): d = df.sort_values(['NOTE_ID', 'CONTACT_NUM']).drop_duplicates(['NOTE_ID', 'NOTE_LINE'], keep='last') d = d.merge(cohort, on='PAT_ENC_CSN_ID', how='left') f = combine_notes(d) del d return f def make_sql_string(lst, dtype="str", mode="wherelist"): assert dtype in ["str", 'int'] assert mode in ["wherelist", 'vallist'] if dtype == "int": lst = [str(i) for i in lst] if mode == "wherelist": if dtype == "str": out = "('" + "','".join(lst) + "')" elif dtype == "int": out = "(" + ",".join(lst) + ")" elif mode == "vallist": if dtype == "str": out = "('" + "'),('".join(lst) + "')" elif dtype == "int": out = "(" + "),(".join(lst) + ")" return out def write_txt(str, path): text_file = open(path, "w") text_file.write(str) text_file.close() def write_pickle(x, path): with open(path, 'wb') as handle: pickle.dump(x, handle, protocol=pickle.HIGHEST_PROTOCOL) def query_filtered_with_temp_tables(q, fdict, rstring=""): """ The q is the query the fdict contains the info on how to filter, and what the foreign table is the rstring is some random crap to append to the filter table when making lots of temp tables through multiprocessing """ base_temptab = """ IF OBJECT_ID('tempdb..#filter_n') IS NOT NULL BEGIN DROP TABLE #filter_n END CREATE TABLE #filter_n ( :idname :type NOT NULL, PRIMARY KEY (:idname) ); INSERT INTO #filter_n (:idname) VALUES :ids; """ # added Aug 10: if the foreign_key isn't in each fdict dict entry, input the name of the base fdict key by default: for k in fdict.keys(): try: _ = fdict[k]['foreign_key'] except: fdict[k]['foreign_key'] = k # tally ho: base_footer = "join #filter_n on #filter_n.:idname = :ftab.:fkey \n" filter_header = "" filter_footer = "" for i in range(len(fdict)): tti = re.sub(":idname", list(fdict.keys())[i], base_temptab) dtype = list(set(type(j).__name__ for j in fdict[list(fdict.keys())[i]]['vals'])) assert len(dtype) == 1 dtype = dtype[0] valstring = make_sql_string(fdict[list(fdict.keys())[i]]['vals'], dtype=dtype, mode='vallist') tti = re.sub(":ids", valstring, tti) if dtype == "str": tti = re.sub(":type", "VARCHAR(255)", tti) elif dtype == "int": tti = re.sub(":type", "INT", tti) tti = re.sub("filter_n", f"filter_{i}_{rstring}", tti) filter_header += tti fi = re.sub(":idname", list(fdict.keys())[i], base_footer) fi = re.sub(":fkey", fdict[list(fdict.keys())[i]]['foreign_key'], fi) fi = re.sub("filter_n", f"filter_{i}_{rstring}", fi) fi = re.sub(":ftab", fdict[list(fdict.keys())[i]]['foreign_table'], fi) filter_footer += fi outq = filter_header + "\n" + q + "\n" + filter_footer return outq def read_txt(path): f = open(path, 'r') out = f.read() f.close() return out def nrow(x): return x.shape[0] def ncol(x): return x.shape[1] def note_status_mapper(x): d = { 1: "Incomplete", 2: "Signed", 3: "Addendum", 4: "Deleted", 5: "Revised", 6: "Cosigned", 7: "Finalized", 8: "Unsigned", 9: "Cosign Needed", 10: "Incomplete Revision", 11: "Cosign Needed Addendum", 12: "Shared" } if type(x).__name__ == "str": return d[int(x)] elif x is None: return "None" elif type(x).__name__ == "int": return d[x] else: raise Exception("feeding note mapper something it didn't like") def get_csn_from_har(csns, clar_conn): '''input is a list of csns''' csnstring = ','.join(["'" + str(i) + "'" for i in csns]) q = ''' with HAR as ( select peh.HSP_ACCOUNT_ID from PAT_ENC_HSP as peh where peh.PAT_ENC_CSN_ID in (:csns) ) select peh.PAT_ENC_CSN_ID from PAT_ENC_HSP as peh inner join HAR on peh.HSP_ACCOUNT_ID = HAR.HSP_ACCOUNT_ID ''' q = re.sub(":csns", csnstring, q) newcsns = get_from_clarity_then_save(q, clar_conn = clar_conn) return newcsns.PAT_ENC_CSN_ID.astype(str).tolist() def sheepish_mkdir(path): import os try: os.mkdir(path) except FileExistsError: pass if __name__ == "__main__": print("Special message from the department of redundant verbosity department:")
ACD-helpers
/ACD_helpers-0.1.2-py3-none-any.whl/ACD_helpers/ACD_shared_functions.py
ACD_shared_functions.py
Collection of simple utilities used when building bioinformatics tools * cmd_exe - simple wrapper around subprocess. * math_utils - math and statistics utils * multiprocess_utils - tools for making Consumer/Producer multithreading Pools * pedigree - handles pedigree files in a friendly datastructure * setup_logging - standardized setup of python logging * vcf_utils - little methods for editing vcf format/info -------- Install -------- pip install ACEBinf
ACEBinf
/ACEBinf-1.0.2.tar.gz/ACEBinf-1.0.2/README.txt
README.txt
from setuptools import setup #from Cython.Build import cythonize setup( name='ACEBinf', version='1.0.2', author="ACEnglish", author_email="acenglish@gmail.com", url="https://github.com/ACEnglish/acebinf", packages=['acebinf',], license='Unlicense', description=open('README.txt').readline().strip(), long_description=open('README.txt').read(), long_description_content_type='text/markdown', install_requires=[ "pyvcf>=0.6.8" ], ) #setup( #ext_modules = cythonize("fast_vcf.pyx") #)
ACEBinf
/ACEBinf-1.0.2.tar.gz/ACEBinf-1.0.2/setup.py
setup.py
""" Simplified command running """ import os import time import signal import logging import datetime import subprocess from collections import namedtuple class Alarm(Exception): """ Alarm Class for command timeouts """ pass def alarm_handler(signum, frame=None): # pylint: disable=unused-argument """ Alarm handler for command timeouts """ raise Alarm cmd_result = namedtuple("cmd_result", "ret_code stdout stderr run_time") def cmd_exe(cmd, timeout=-1): """ Executes a command through the shell. timeout in minutes! so 1440 mean is 24 hours. -1 means never returns namedtuple(ret_code, stdout, stderr, datetime) where ret_code is the exit code for the command executed stdout/err is the Standard Output Error from the command and datetime is a datetime object of the execution time """ t_start = time.time() proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, preexec_fn=os.setsid) signal.signal(signal.SIGALRM, alarm_handler) if timeout > 0: signal.alarm(int(timeout * 60)) try: stdoutVal, stderrVal = proc.communicate() signal.alarm(0) # reset the alarm except Alarm: logging.error(("Command was taking too long. " "Automatic Timeout Initiated after %d"), timeout) os.killpg(proc.pid, signal.SIGTERM) proc.kill() return 214, None, None, datetime.timedelta(seconds=int(time.time() - t_start)) t_end = time.time() stdoutVal = bytes.decode(stdoutVal) retCode = proc.returncode ret = cmd_result(retCode, stdoutVal, stderrVal, datetime.timedelta(seconds=int(t_end - t_start))) return ret
ACEBinf
/ACEBinf-1.0.2.tar.gz/ACEBinf-1.0.2/acebinf/cmd_exe.py
cmd_exe.py
""" File for handling pedigree information Family ID Individual ID Paternal ID Maternal ID Sex (1=male; 2=female; other=unknown) Phenotype - See more at: http://gatkforums.broadinstitute.org/gatk/discussion/7696/pedigree-ped-files """ from collections import defaultdict # pylint: disable=too-few-public-methods class Pedigree(dict): """ Parses a pedigree file and allows different views """ def __init__(self, file_name): super(Pedigree, self).__init__() self.samples = self.keys self.families = defaultdict(list) with open(file_name, 'r') as fh: for line in fh: if line.startswith("#"): continue data = line.strip().split('\t') # check the data length n_ped = _PedSample(*data[:5], phenotype=data[5:]) self.families[n_ped.fam_id].append(n_ped) if n_ped.ind_id in self: raise KeyError("Duplicate Individual Id %s" % n_ped.ind_id) self[n_ped.ind_id] = n_ped # Give parents a presence in the ped, even if they didn't have a line for ind in self.values(): if ind.pat_id not in self and ind.pat_id != "0": self[ind.pat_id] = _PedSample(ind.fam_id, ind.pat_id, "0", "0", "1", "0") if ind.mat_id not in self and ind.mat_id != "0": self[ind.mat_id] = _PedSample(ind.fam_id, ind.mat_id, "0", "0", "2", "0") # Set parent's offspring for n_ped in self.values(): if n_ped.pat_id in self: self[n_ped.pat_id].offspring.append(n_ped) n_ped.father = self[n_ped.pat_id] if n_ped.mat_id in self: self[n_ped.mat_id].offspring.append(n_ped) n_ped.mother = self[n_ped.mat_id] def filter(self, inc_fam=None, exc_fam=None, inc_indiv=None, exc_indiv=None): """ Exclude anything that's exc in the pedigree. Include only anything that's inc in the pedigree. """ if inc_fam is not None: for i in self.keys(): if self[i].fam_id not in inc_fam: del self[i] if inc_indiv is not None: for i in self.keys(): if self[i].ind_id not in inc_indiv: del self[i] if exc_fam is not None: for i in self.keys(): if self[i].fam_id in exc_fam: del self[i] if exc_indiv is not None: for i in self.keys(): if self[i].ind_id in exc_indiv: del self[i] def all_male(self): """ Returns all male individuals """ for i in self: if self[i].sex == "1": yield self[i] def all_female(self): """ Returns all female individuals """ for i in self: if self[i].sex == "2": yield self[i] def all_affected(self): """ Returns all affected individuals """ for i in self: if self[i].phenotype == "2": yield self[i] def all_unaffected(self): """ Returns all unaffected individuals """ for i in self: if self[i].phenotype == "1": yield self[i] def get_siblings(self, indiv): """ Returns the siblings of an individual """ for i in self: if self[i].pat_id == self[indiv].pat_id or self[i].mat_id == self[indiv].mat_id: yield self[i] def get_trio_probands(self): """ Yields _PedSample probands that are part of a trio i.e. niether parent is 0 """ for indiv in self.values(): if indiv.mat_id != '0'and indiv.pat_id != '0': yield indiv def get_quad_probands(self): """ Yields _PedSample proband tuples that are part of an exact quad. """ for fam in self.families: already_yielded = {} for indiv in self.families[fam]: if indiv.ind_id in already_yielded: continue if indiv.mat_id != "0" and indiv.pat_id != "0": siblings = set(self[indiv.mat_id].offspring).intersection(set(self[indiv.pat_id].offspring)) if len(siblings) == 2: yield list(siblings) for sib in siblings: if indiv != sib: already_yielded[sib.ind_id] = 1 yield (indiv, sib) class _PedSample(object): """ An individual in a pedigree Family ID Individual ID Paternal ID Maternal ID Sex (1=male; 2=female; other=unknown) Phenotype """ def __init__(self, fam_id, ind_id, pat_id, mat_id, sex, phenotype): self.fam_id = fam_id self.ind_id = ind_id self.pat_id = pat_id self.mat_id = mat_id self.sex = sex self.phenotype = phenotype self.father = None self.mother = None self.offspring = [] def __hash__(self): return hash(self.ind_id) def __repr__(self): return "PedigreeSample<%s:%s %s>" % (self.fam_id, self.ind_id, self.sex) def __str__(self): return "\t".join([self.fam_id, self.ind_id, self.pat_id, self.mat_id, self.pat_id, self.sex, "\t".join(self.phenotype)])
ACEBinf
/ACEBinf-1.0.2.tar.gz/ACEBinf-1.0.2/acebinf/pedigree.py
pedigree.py
""" Simple wrappers around swalign package to help tie assemblies to biograph.Reference and convert the results into a vcf """ from __future__ import print_function from io import BytesIO import swalign def aligner(reference, assembly, s_anchor, e_anchor, match=2, mismatch=-1, gap_penalty=-2, gap_extension_decay=0.5): """ Given two anchor reference ranges map a query sequence align using swalign returns the alignment """ positions = [s_anchor.start, s_anchor.end, e_anchor.start, e_anchor.end] start = min(positions) end = max(positions) # We're assuming non tloc chrom = s_anchor.chromosome scoring = swalign.NucleotideScoringMatrix(match, mismatch) sw = swalign.LocalAlignment(scoring, gap_penalty=gap_penalty, gap_extension_decay=gap_extension_decay) aln = sw.align(str(reference.make_range(chrom, start, end).sequence), str(assembly)) return aln def aln_to_vcf(anchor, aln, header=True): """ Turns an swalign into a vcf written to a StringIO this can be parsed by pyvcf directly or written to a file It currently has no INFO and a fake FORMAT of GT=0/1 if header is true, turn write a vcf header """ ret = BytesIO() if header: ret.write(('##INFO=<ID=NS,Number=1,Type=Integer,Description="Number of smaples">\n' '##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">\n' '#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tSAMPLE\n')) tovcf = lambda chrom, pos, ref, alt: ret.write("{chrom}\t{pos}\t.\t{ref}\t{alt}\t.\tPASS\tNS=1\tGT\t0/1\n".format( chrom=chrom, pos=pos, ref=ref, alt=alt)) # Position in the ref/query sequence # this will be off if the assembly maps to a sub-sequence of the anchor region base_position = anchor.start + 1 rpos = 0 qpos = 0 chrom = anchor.chromosome query = aln.query reference = aln.ref for size, code in aln.cigar: if code == "M": for _ in range(size): if query[qpos] != reference[rpos]: # SNP. Can't handle MNPs yet tovcf(chrom, base_position, reference[rpos], query[qpos]) rpos += 1 qpos += 1 base_position += 1 elif code == 'I': # ins tovcf(chrom, base_position - 1, reference[rpos - 1], reference[rpos - 1] + query[qpos:qpos + size]) qpos += size elif code == 'D': # del tovcf(chrom, base_position - 1, reference[rpos - 1:rpos + size], reference[rpos - 1]) rpos += size base_position += size ret.seek(0) return ret
ACEBinf
/ACEBinf-1.0.2.tar.gz/ACEBinf-1.0.2/acebinf/aligner.py
aligner.py
""" little methods for editing pyvcf format/info fields """ import vcf def add_format(vcf_file, nid, num, ntype, desc): """ In-place addition of a new FORMAT into the vcf_file """ # pylint: disable=protected-access vcf_file.formats[nid] = vcf.parser._Format(id=nid, num=num, type=ntype, desc=desc) def add_info(vcf_file, nid, num, ntype, desc, source=None, version=None): """ In-place addition of a new INFO into the vcf_file """ # pylint: disable=protected-access vcf_file.infos[nid] = vcf.parser._Info( id=nid, num=num, type=ntype, desc=desc, source=source, version=version) def edit_format(vcf_entry, sample, **kwargs): """ Given a sample and FORMAT=value kwargs, edit an entry's information in-place """ fmt_data = vcf_entry.FORMAT.split(':') for key in kwargs: if key not in fmt_data: vcf_entry.add_format(key) n_call_data = vcf.model.make_calldata_tuple(sample.data._fields + tuple(kwargs.keys())) n_data = tuple(kwargs.values()) sample.data += n_data sample.data = n_call_data(*sample.data)
ACEBinf
/ACEBinf-1.0.2.tar.gz/ACEBinf-1.0.2/acebinf/vcf_utils.py
vcf_utils.py
""" Sets up package """ from acebinf.cmd_exe import ( cmd_exe ) from acebinf.log import ( setup_logging ) from acebinf.math_utils import ( percentile, phi, p_obs ) from acebinf.multiprocess_utils import ( Consumer, ConsumerPool ) from acebinf.pedigree import ( Pedigree ) from acebinf.vcf_utils import ( add_format, add_info, edit_format )
ACEBinf
/ACEBinf-1.0.2.tar.gz/ACEBinf-1.0.2/acebinf/__init__.py
__init__.py
""" Python Logging Setup """ import sys import logging import warnings def setup_logging(debug=False, stream=sys.stderr, log_format=None): """ Default logger """ logLevel = logging.DEBUG if debug else logging.INFO if log_format is None: log_format = "%(asctime)s [%(levelname)s] %(message)s" logging.basicConfig(stream=stream, level=logLevel, format=log_format) logging.info("Running %s", " ".join(sys.argv)) # pylint:disable=unused-argument def sendWarningsToLog(message, category, filename, lineno, *args, **kwargs): """ Put warnings into logger """ logging.warning('%s:%s: %s:%s', filename, lineno, category.__name__, message) return warnings.showwarning = sendWarningsToLog
ACEBinf
/ACEBinf-1.0.2.tar.gz/ACEBinf-1.0.2/acebinf/log.py
log.py
""" Convience objects to start a multi processed consumer/producer strategy """ import sys import traceback import multiprocessing import logging class Consumer(multiprocessing.Process): """ Basic Consumer. Follow the two queues with your *args and **kwargs that should be sent to the task when __call__ 'd NOTE! args can't hold anything that isn't pickle-able for the subprocess task_queue, result_queue Should add timeout functionality - I know I have it somewhere """ def __init__(self, task_queue, result_queue): multiprocessing.Process.__init__(self) self.task_queue = task_queue self.result_queue = result_queue def run(self): try: while True: next_task = self.task_queue.get() if next_task is None: # Poison pill means shutdown self.task_queue.task_done() break try: next_task() except Exception as e: # pylint: disable=broad-except logging.error("Exception raised in task - %s", str(e)) exc_type, exc_value, exc_traceback = sys.exc_info() logging.error("Dumping Traceback:") traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stderr) next_task.failed = True next_task.errMessage = str(e) self.result_queue.put(next_task) self.task_queue.task_done() return except Exception as e: # pylint: disable=broad-except logging.error("Consumer %s Died\nERROR: %s", self.name, e) return class ConsumerPool(object): """ A resource for making a pool of consumer multiprocesses The tasks passed in via put must be callable (__call__) finished tasks are then yielded back. Usage: >>> procs = ConsumerPool(THREADS) >>> procs.start_pool() >>> for stuff in things: >>> procs.put_task(MyTask(stuff, Param1, Param2)) >>> procs.put_poison() >>> >>> for pcmp_result in procs.get_tasks(): >>> pass # Do work on your MyTasks """ def __init__(self, threads=1): """ Does all the work """ self.threads = threads self.input_queue = multiprocessing.JoinableQueue() self.output_queue = multiprocessing.Queue() self.processes = [Consumer(self.input_queue, self.output_queue) for i in range(self.threads)] # pylint: disable=unused-variable self.task_count = 0 def start_pool(self): """ run start on all processes """ for proc in self.processes: proc.start() def put_task(self, task): """ Add a callable task to the input_queue """ self.task_count += 1 self.input_queue.put(task) def put_poison(self): """ For each process, add a poison pill so that it will close once the input_queue is depleted """ for i in range(self.threads): logging.debug("Putting poison %d", i) self.input_queue.put(None) def get_tasks(self): """ Yields the finished tasks """ remaining = self.task_count while remaining: ret_task = self.output_queue.get() remaining -= 1 yield ret_task
ACEBinf
/ACEBinf-1.0.2.tar.gz/ACEBinf-1.0.2/acebinf/multiprocess_utils.py
multiprocess_utils.py
""" Math/Stats helpers """ import math #{{{ http://code.activestate.com/recipes/511478/ (r1) # pylint: disable=invalid-name def percentile(N, percent): """ Find the percentile of a list of values. @parameter N - is a list of values. @parameter percent - a float value from 0.0 to 1.0. @return - the percentile of the values """ N.sort() if not N: return None k = (len(N) - 1) * percent f = math.floor(k) c = math.ceil(k) if f == c: return N[int(k)] d0 = N[int(f)] * (c - k) d1 = N[int(c)] * (k - f) return d0 + d1 # median is 50th percentile. # end of http://code.activestate.com/recipes/511478/ }}} def phi(x): """ phi functino is the cumulative density function (CDF) of a standard normal (Gaussian) random variable. It is closely related to the error function erf(x). https://www.johndcook.com/erf_and_normal_cdf.pdf From: https://www.johndcook.com/blog/python_phi/ """ # constants a1 = 0.254829592 a2 = -0.284496736 a3 = 1.421413741 a4 = -1.453152027 a5 = 1.061405429 p = 0.3275911 # Save the sign of x sign = 1 if x < 0: sign = -1 x = abs(x) / math.sqrt(2.0) # A&S formula 7.1.26 t = 1.0 / (1.0 + p * x) y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * math.exp(-x * x) return 0.5 * (1.0 + sign * y) def p_obs(obs, mean, sd, two_tailed=True): """ Calculate p-value of an observation given an estmated mean and std """ x = (obs - mean) / sd if two_tailed: return 2 * (1 - phi(abs(x))) return 1 - phi(abs(x))
ACEBinf
/ACEBinf-1.0.2.tar.gz/ACEBinf-1.0.2/acebinf/math_utils.py
math_utils.py
This is not complete yet
ACETH
/ACETH-0.0.13.tar.gz/ACETH-0.0.13/README.md
README.md
from setuptools import setup, find_packages setup( name = 'ACETH', version = '0.0.13', author = 'Karim Galal, Walid Chatt', author_email = 'karim.galal@analytics-club.org, walid.chatt@analytics-club.org', license = 'MIT', url='https://github.com/kimo26/ACE', description = 'Analytics Club ETHZ helper package', packages=find_packages(), package_data={'ACETH': ['data/emoji_model.h5','data/encoder_emoji.pkl','data/token_emoji.pkl']}, include_package_data=True, keywords = ['ETHZ', 'Analytics Club','AI','Artificial intelligence', 'Machine Learning', 'Data processing','Chatbot', 'Education','ML'], install_requires = [ 'numpy','pandas','torch', 'tensorflow','transformers','sklearn', 'emoji','accelerate','bitsandbytes','scikit-learn', ], classifiers=[ 'Programming Language :: Python :: 3' ] )
ACETH
/ACETH-0.0.13.tar.gz/ACETH-0.0.13/setup.py
setup.py
# A python wrapper for the Answer Constraint Engine This package is a wrapper for [ACE](http://sweaglesw.org/linguistics/ace) ## Installation ```bash pip install ACEngine ``` ## Quick Start ### English Grammar Resource ```python from ace.paraphrase import generate_paraphrase text = "The quick brown fox that jumped over the lazy dog took a nap." paraphrase_list = generate_paraphrase(text) for paraphrase in paraphrase_list: print(paraphrase) # The brown quick fox which jumped over the lazy dog took a nap. # The brown quick fox that jumped over the lazy dog took a nap. # A nap was taken by the brown quick fox which jumped over the lazy dog. # The brown quick fox who jumped over the lazy dog took a nap. # A nap was taken by the brown quick fox that jumped over the lazy dog. # A nap was taken by the brown quick fox, which jumped over the lazy dog. # A nap was taken by the quick brown fox, which jumped over the lazy dog. # The brown quick fox, which jumped over the lazy dog, took a nap. # The quick brown fox which jumped over the lazy dog took a nap. # The quick brown fox, which jumped over the lazy dog, took a nap. # A nap was taken by the brown quick fox who jumped over the lazy dog. # A nap was taken by the brown quick fox, who jumped over the lazy dog. # The quick brown fox that jumped over the lazy dog took a nap. # A nap was taken by the quick brown fox, who jumped over the lazy dog. # The brown quick fox, who jumped over the lazy dog, took a nap. # The quick brown fox, who jumped over the lazy dog, took a nap. # A nap was taken by the brown quick fox, that jumped over the lazy dog. # A nap was taken by the quick brown fox, that jumped over the lazy dog. # The brown quick fox, that jumped over the lazy dog, took a nap. # The quick brown fox, that jumped over the lazy dog, took a nap. # A nap was taken by the quick brown fox which jumped over the lazy dog. # The quick brown fox who jumped over the lazy dog took a nap. # A nap was taken by the quick brown fox that jumped over the lazy dog. # A nap was taken by the quick brown fox who jumped over the lazy dog. ``` ### The Jacy Japanese Grammar ```python from ace.paraphrase import generate_paraphrase text = "太郎 が 次郎 に 本 を 渡し た" paraphrase_list = generate_paraphrase(text, grammar='jacy') for paraphrase in paraphrase_list: print(paraphrase) # 太郎 が 次郎 に 本 を 渡し た # 次郎 に 太郎 が 本 を 渡し た # 次郎 に 本 を 太郎 が 渡し た ```
ACEngine
/ACEngine-0.0.5.tar.gz/ACEngine-0.0.5/README.md
README.md
from __future__ import print_function import distutils.spawn import shlex import subprocess import sys from setuptools import find_packages from setuptools import setup version = "0.0.5" if sys.argv[-1] == "release": if not distutils.spawn.find_executable("twine"): print( "Please install twine:\n\n\tpip install twine\n", file=sys.stderr, ) sys.exit(1) commands = [ "git tag v{:s}".format(version), "git push origin master --tag", "python setup.py sdist", "twine upload dist/ACEngine-{:s}.tar.gz".format(version), ] for cmd in commands: print("+ {}".format(cmd)) subprocess.check_call(shlex.split(cmd)) sys.exit(0) setup_requires = [] install_requires = [ 'gdown', ] setup( name="ACEngine", version=version, description="A python wrapper for the Answer Constraint Engine", author="iory", author_email="ab.ioryz@gmail.com", url="https://github.com/iory/ACEngine", long_description=open("README.md").read(), long_description_content_type="text/markdown", license="MIT", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", ], packages=find_packages(), zip_safe=False, setup_requires=setup_requires, install_requires=install_requires, )
ACEngine
/ACEngine-0.0.5.tar.gz/ACEngine-0.0.5/setup.py
setup.py
import subprocess from ace.data import get_ace from ace.data import get_english_resource_grammar from ace.data import get_jacy_grammar def generate_paraphrase(text, grammar='english', verbose=False): if grammar == 'english' or grammar == 'erg': grammar = get_english_resource_grammar() elif grammar == 'japanese' or grammar == 'jacy': grammar = get_jacy_grammar() else: raise RuntimeError ace_binary = get_ace() cmd = 'echo "{}" | {} -g {} -1T 2>/dev/null | {} -g {} -e'\ .format(text, ace_binary, grammar, ace_binary, grammar) if verbose: print(cmd) proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, ) proc.wait() stdout_data, _ = proc.communicate() paraphrase_list = stdout_data.decode('utf8').splitlines() paraphrase_list = [paraphrase for paraphrase in paraphrase_list if len(paraphrase) > 0] if verbose: for s in proc.communicate(): print(s.decode('utf8')) return paraphrase_list
ACEngine
/ACEngine-0.0.5.tar.gz/ACEngine-0.0.5/ace/paraphrase.py
paraphrase.py
# flake8: noqa import pkg_resources __version__ = pkg_resources.get_distribution("ACEngine").version import ace.data import ace.paraphrase
ACEngine
/ACEngine-0.0.5.tar.gz/ACEngine-0.0.5/ace/__init__.py
__init__.py
import bz2 import os import os.path as osp import platform import gdown download_base_dir = osp.expanduser('~/.ace') download_bin_dir = osp.join(download_base_dir, 'bin') download_grammar_dir = osp.join(download_base_dir, 'grammar') ace_versions = ( '0.9.31', ) default_ace_version = '0.9.31' english_resource_grammar_versions = ( '1214', '2018', ) default_english_resource_grammar_version = '2018' jacy_urls = { '2017': { 'osx': 'https://drive.google.com/uc?id=1YdHii_0NNpi_e-Xi_Oa3vL4MQ3yS-b2f', 'x86-64': 'https://drive.google.com/uc?id=1-vG00-IsTX1RxJaCcQSKVLK-7wAzEqEe', }, } default_jacy_version = '2017' def get_ace(ace_version=default_ace_version): if ace_version not in ace_versions: raise RuntimeError('Could not find a version {} (from versions: {})' .format(ace_version, ", ".join(ace_versions))) pf = platform.system() base_url = 'http://sweaglesw.org/linguistics/ace/download/ace-{}-{}.tar.gz' if pf == 'Windows': raise NotImplementedError('Not supported in Windows.') elif pf == 'Darwin': url = base_url.format(ace_version, 'osx') bin_filename = 'ace-{}-{}'.format(ace_version, 'osx') else: url = base_url.format(ace_version, 'x86-64') bin_filename = 'ace-{}-{}'.format(ace_version, 'x86-64') bin_filename = osp.join(download_bin_dir, bin_filename) name = osp.splitext(osp.basename(url))[0] if not osp.exists(bin_filename): gdown.cached_download( url=url, path=osp.join(download_bin_dir, name), postprocess=gdown.extractall, quiet=True, ) os.rename( osp.join(download_bin_dir, 'ace-{}'.format(ace_version), 'ace'), bin_filename) return bin_filename def get_english_resource_grammar( ace_version=default_ace_version, erg_version=default_english_resource_grammar_version): """Get Precompiled grammar images. """ if ace_version not in ace_versions: raise RuntimeError( 'Could not find an ACE version {} (from versions: {})' .format(ace_version, ", ".join(ace_versions))) if erg_version not in english_resource_grammar_versions: raise RuntimeError( 'Could not find an ERG version {} (from versions: {})' .format(erg_version, ", ".join(english_resource_grammar_versions))) pf = platform.system() base_url = 'http://sweaglesw.org/linguistics/ace/download/' \ 'erg-{}-{}-{}.dat.bz2' if pf == 'Windows': raise NotImplementedError('Not supported in Windows.') elif pf == 'Darwin': url = base_url.format(erg_version, 'osx', ace_version) name = 'erg-{}-{}-{}.dat'.format(erg_version, 'osx', ace_version) else: url = base_url.format(erg_version, 'x86-64', ace_version) name = 'erg-{}-{}-{}.dat'.format(erg_version, 'x86-64', ace_version) dat_filename = osp.join(download_grammar_dir, name) bz2_file = osp.join(download_grammar_dir, name + '.bz2') if not osp.exists(dat_filename): gdown.cached_download( url=url, path=bz2_file, quiet=True, ) with open(bz2_file, 'rb') as f: data = f.read() with open(dat_filename, 'wb') as fw: fw.write(bz2.decompress(data)) return dat_filename def get_jacy_grammar(ace_version=default_ace_version, jacy_version=default_jacy_version): """Get Precompiled grammar images. https://github.com/delph-in/jacy """ if ace_version not in ace_versions: raise RuntimeError( 'Could not find an ACE version {} (from versions: {})' .format(ace_version, ", ".join(ace_versions))) if jacy_version not in jacy_urls.keys(): raise RuntimeError( 'Could not find a jacy version {} (from versions: {})' .format(jacy_version, ", ".join(jacy_urls.keys()))) pf = platform.system() if pf == 'Windows': raise NotImplementedError('Not supported in Windows.') elif pf == 'Darwin': url = jacy_urls[jacy_version]['osx'] name = 'jacy-{}-{}-{}.dat'.format(jacy_version, 'osx', ace_version) else: url = jacy_urls[jacy_version]['x86-64'] name = 'jacy-{}-{}-{}.dat'.format(jacy_version, 'x86-64', ace_version) dat_filename = osp.join(download_grammar_dir, name) bz2_file = osp.join(download_grammar_dir, name + '.bz2') if not osp.exists(dat_filename): gdown.cached_download( url=url, path=bz2_file, quiet=True, ) with open(bz2_file, 'rb') as f: data = f.read() with open(dat_filename, 'wb') as fw: fw.write(bz2.decompress(data)) return dat_filename
ACEngine
/ACEngine-0.0.5.tar.gz/ACEngine-0.0.5/ace/data/ace_utils.py
ace_utils.py
# flake8: noqa from .ace_utils import get_ace from .ace_utils import get_english_resource_grammar from .ace_utils import get_jacy_grammar
ACEngine
/ACEngine-0.0.5.tar.gz/ACEngine-0.0.5/ace/data/__init__.py
__init__.py
ACIOps ============== Description -------------- ACIOps is a collection of my personal method/functions used in my programs. The module will return all the the requested information for you unformatted. Within this module you will find the following tools: + APIC Login + Subnet Finder + View Tenants + Vlans Pools + Encapsulation Finder + Access Policy Mappings + Tenant vrfs + Application Profiles + Endpoint Groups + Bridge Domains + Endpoint Finder **Version 2.0 additions + Create Tenant + Create App Profile + Create EPG + Create BD (l3/l2) + Routing Scope + Create VRF + Enable Unicast Depedency Modules __________ + xml.etree.ElementTree + ipaddress + collections + json + warnings + request + re Usage _____ **Import** >>>import ACIOperations.ACIOps as ops Examples --- Some method can be run without any argument and some dont. The seed method is always the login() which produces the session **Example 1 (Authentication: )** >>> call_class = ops.AciOps() >>> login = call_class.login(apic="192.168.1.1", username="JoeSmo", password="helpme!") >>> print(call_class.session) <requests.sessions.Session object at 0x00000253743CFB48> >>> **Example 2 (Fetch VLAN Pools: )** >>>call_class.vlan_pools() defaultdict(<class 'list'>, {'Pool1': 'vlan-10-vlan-20', 'Pool2': 'vlan-1000-vlan-2000'} >>> pools = call_class.vlan_pools() >>> for k, v in pools.items(): print("Pool: {} Range: {}".format(k, v)) Pool: Pool1 Range: vlan-10-vlan-20 Pool: Pool2 Range: vlan-1000-vlan-2000 **Example 3 (Find Encap: )** >>>find_encap = call_class.find_encap(vlan="2000") * Output omitted due to length This will produce all access policies associated with an external fabric encapsulation **Example 4 (Policy Mappings:)** >>> policy_maps = call_class.policy_mappings() * Output omitted due to length This will map vlan pools, AAEP, phydoms, routeddoms, vmmdoms and return to user. **Example 5 (Infrastructure Info: )** >>> infra = call_class.infr(pod=1) >>> print(infra) ['Leaf101', 'N9K-C93180YC-EX', 'FDO21eddfrr', 'Leaf102', 'N9K-C93108TC-EX', 'FDO21rfeff', 'Spine101', 'N9K-C9336PQ', 'FDO2rffere'] **Example 6 (Find Subnet: )** >>> find_subnet = call_class.subnet_finder(subnet="10.1.1.1/24") >>> print(find_subnet) ('10.1.1.1/24', 'Customer1', 'BD-VL100', 'Customer1-VRF', 'Customer1-l3out', 'yes', 'public,shared', 'flood', ['ANP-Web'], ['EPG-WebServer']) **Example 7 (View Tenants: )** >>> tenants = call_class.view_tenants() >>> print(tenants) ['infra', 'Customer-1', 'common', 'Customer-2'] >>> **Example 8 (View Vrf: )** >>> vrf = call_class.tenant_vrf(tenant="Customer-1") >>> print(vrf) defaultdict(<class 'list'>, {'vrf': ['Customer-1']}) >>> **Example 9 (View Bridge Domains: )** >>>call_class.view_bd(tenant="Example") ['L3BD', 'BDL3'] >>> **Example 9 (View App Profiles: )** >>>call_class.view_app_profiles(tenant="Example") ['Web', 'None'] **Example 10 (View EPG: )** >>>call_class.view_epgs(tenant="Example", app="Web") ['Servers'] >>> **Example 11 (Endpoint Tracker: )** >>> endpoint = call_class.enpoint_tracker(endpoint="10.1.1.10") >>> print(endpoint) Name: 00:50:56:A0:77:88 EP: 00:50:56:A0:77:88 Encapsulation: vlan-200 Location: uni/tn-Customer-1/ap-ANP-WEB/epg-EPG-WEB/cep-00:50:56:A0:77:88 IP: 10.1.1.10 >>> Send Operations ===== Description ---- **The AciOpsSend class enables you to send configurations to ACI. You can run it from you own program or just use** **the python console. Simple and easy methods inherited from our parent class in v1.0.0** **Example 1 (Create Tenant: )** >>> call_class = ops.AciOpsSend(apic="192.168.1.1", username="JoeSmo", password="Help!") >>> create_tenant = call_class.create_tenant(tenant="Example") >>> call_class.view_tenants() ['Example'] >>> **Example 2 (Create App Profile: )** >>> create_app = call_class.create_app_profile(tenant="Example", app="Web") >>> call_class.create_app_profile() >>> call_class.create_app_profile(tenant="Example") (<Response [200]>, defaultdict(<class 'list'>, {'name': ['Web', 'None']})) >>> **Example 3 (Create EPG: )** >>> call_class.create_epg(tenant="Example", app="Web", epg="Servers") (<Response [200]>, defaultdict(<class 'list'>, {'name': ['Servers']})) >>> **Example 4 (Create BD: )** >>> call_class.create_bd_l3(tenant="Example", bd="L3BD", subnet="4.4.4.4/32") (<Response [200]>, defaultdict(<class 'list'>, {'name': ['L3BD']})) >>> call_class.subnet_finder(subnet="4.4.4.4/32") ('4.4.4.4/32', 'Example', 'L3BD', 'vrf', 'None', 'yes', 'private', 'proxy', 'None', 'None') >>> **Example 5 (Create vrf: )** >>> call_class.create_vrf(tenant="Example", vrf="vrf-1") (<Response [200]>, defaultdict(<class 'list'>, {'vrf': ['vrf-1']})) >>> **Example 6 (Enable Unicast Route: )** >>> call_class.enable_unicast(tenant="Example", bd="L3BD", enable="no") **yes/no** (<Response [200]>, '{"fvBD":{"attributes": {"name": "L3BD", "unicastRoute": "no"}}}') >>> **Example 7 (Assign Vrf to BridgeDomain: )** >>>call_class.vrf_to_bd(tenant="Example", bd="BDL3", vrf="vrf-1") (<Response [200]>, defaultdict(<class 'list'>, {'vrf': ['vrf-1']})) >>> **Example 8 (Routing Scope: )** >>> call_class.routing_scope(tenant="Example", bd="BDL3", scope="private", subnet="4.4.4.4/32") **share|public|shared*** (<Response [200]>, defaultdict(<class 'list'>, {'name': ['L3BD', 'BDL3']}), {'IP': 'uni/tn-Example/BD-BDL3/subnet-[4.4.4.4/32]', 'Tenant': 'Example', 'BD': 'BDL3', 'vrf': 'vrf-1', 'L3Out': 'None', 'Route Enable': 'yes', 'Scope': 'private', 'Uni Flood': 'proxy', 'APs': 'None', 'EPGs': 'None'}) >>>
ACIOps
/ACIOps-2.0.0.tar.gz/ACIOps-2.0.0/README.rst
README.rst
from setuptools import setup, find_packages with open("README.rst", "r") as fh: long_description = fh.read() setup( name="ACIOps", version="2.0.0", author="Chris Oberdalhoff", author_email="cober91130@gmail.com", description="ACIOps allows you to fetch basic ACI information.", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/cober2019/Network-Automation/tree/master/DataCenter%20(ACI)/ACIOperations", packages=find_packages(), py_modules=["ACIOPs"], install_requires=("ipaddress"), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', )
ACIOps
/ACIOps-2.0.0.tar.gz/ACIOps-2.0.0/setup.py
setup.py
import requests import json import warnings import xml.etree.ElementTree as ET import re import collections import ipaddress class AciOps: """Collects authentication information from user, returns session if successfull, or response if not""" def __init__(self): self.session = None self.response = None self.apic = None self.vlan_dict = collections.defaultdict(list) self.policies_dict = collections.defaultdict(list) self.device_info = [] self.tenant_array = [] self.bd_array = [] self.ap_array = [] self.epg_array = [] self.vrf_array = [] self.json_header = headers = {'content-type': 'application/json'} def login(self, apic=None, username=None, password=None): """APIC authentication method. Takes username, password, apic kwargs and returns session""" ignore_warning = warnings.filterwarnings('ignore', message='Unverified HTTPS request') uri = "https://%s/api/aaaLogin.json" % apic json_auth = {'aaaUser': {'attributes': {'name': username, 'pwd': password}}} json_credentials = json.dumps(json_auth) self.session = requests.Session() self.apic = apic try: request = self.session.post(uri, data=json_credentials, verify=False) self.response = json.loads(request.text) except (requests.exceptions.ConnectionError, requests.exceptions.InvalidURL): raise ConnectionError("Login Failed, Verify APIC Address") try: if self.response["imdata"][0]["error"]["attributes"]["code"] == "401": raise ValueError("Login Failed, please verify credentials | Credential Submitted:\n{}\n{}" .format(username, password)) except TypeError: raise TypeError("Something Went Wrong") except KeyError: pass else: return self.session def vlan_pools(self): """Get fabric vlan pools, return pool in a dictionary data structure""" vlan_range_dict = collections.defaultdict(list) uri = "https://" + self.apic + "/api/node/mo/uni/infra.xml?query-target=subtree&target-subtree-class=fvnsVlanInstP&target-subtree-class=fvnsEncapBlk&query-target=subtree&rsp-subtree=full&rsp-subtree-class=tagAliasInst" request = self.session.get(uri, verify=False) root = ET.fromstring(request.text) for fvnsEncapBlk in root.iter("fvnsEncapBlk"): vlan_pool_array = [] if "vxlan" in fvnsEncapBlk.get("from"): continue else: vlan_pool_array.append(fvnsEncapBlk.get("from")) vlan_pool_array.append(fvnsEncapBlk.get("to")) start_range = fvnsEncapBlk.get("from") end_range = fvnsEncapBlk.get("to") dn = fvnsEncapBlk.get("dn") parse_dn = re.findall(r'(?<=vlanns-\[).*?(?=]-[a-z])', dn) vlan_range_dict[parse_dn[0]] = start_range + "-" + end_range vlans = [] for vlan in vlan_pool_array: remove_vlan = vlan.replace("vlan-", "") vlan_range = remove_vlan.split("-") vlans.append(vlan_range[0]) if "vxlan" in vlans: pass else: vlans_unpacked = [] vlan_start = int(vlans[0]) vlan_end = int(vlans[1]) + 1 if vlan_start == vlan_end: vlans_unpacked.append(str(vlan_end)) else: begin = vlan_start for i in range(vlan_start, vlan_end): vlans_unpacked.append(str(begin)) begin = begin + 1 self.vlan_dict[parse_dn[0]].append(vlans_unpacked) return request, vlan_range_dict def find_encap(self, encap=None): """Takes in the vlan encapsulation, intiaates vlan_pool(0 and policy_mappings. Calls _find_encap_comiple to fin fabric information about the encapsulation Returns a series of list to the caller""" vlan_pool = collections.defaultdict(list) phys_doms = collections.defaultdict(list) aaeps = collections.defaultdict(list) location = collections.defaultdict(list) path = collections.defaultdict(list) self.vlan_pools() self.policy_mappings() pools = self._find_encap_compile(encap) vlan_pool[encap].append(pools[0]) phys_doms[encap].append(pools[1]) aaeps[encap].append(pools[2]) location[encap].append(pools[3]) path[encap].append(pools[4]) unpacked_vlan_pools = [v for k, v in vlan_pool.items() for v in v for v in v] unpacked_phys_doms = [v for k, v in phys_doms.items() for v in v for v in v] unpacked_aaep = [v for k, v in aaeps.items() for v in v for v in v] unpacked_location = [v for k, v in location.items() for v in v for v in v] unpacked_path = [v for k, v in path.items() for v in v for v in v] return unpacked_vlan_pools, unpacked_phys_doms, unpacked_aaep, unpacked_location, unpacked_path def _find_encap_compile(self, encap=None): """ This method is for local use only. It works with vlan_pool() to produce a series of list and return them to the call find_encap""" pools = [] phy_doms = [] aaep = [] location = [] path = [] uri = "https://{}/api/class/fvRsPathAtt.xml?query-target-filter=eq(fvRsPathAtt.encap,\"vlan-{}\")".format(self.apic, encap) request = self.session.get(uri, verify=False) root = ET.fromstring(request.text) if "\"0\"" in request.text: print("Encap not Found") else: for fvRsPathAtt in root.iter("fvRsPathAtt"): string = fvRsPathAtt.get("dn") tenant = re.findall(r'(?<=tn-).*(?=/ap)', string) location.append("Tenant: " + tenant[0]) ap = re.findall(r'(?<=ap-).*(?=/ep)', string) location.append("App Profile: " + ap[0]) epg = re.findall(r'(?<=epg-).*(?=/rsp)', string) location.append("EPG: " + epg[0]) if re.findall(r'(?<=protpaths-).*(?=/pat)', string): path_1 = re.findall(r'(?<=protpaths-).*(?=/pat)', string) elif re.findall(r'(?<=paths-).*(?=/pat)', string): path_1 = re.findall(r'(?<=paths-).*(?=/pat)', string) profile = re.findall(r'(?<=pathep-\[).*(?=]])', string) path.append("Path: " + path_1[0] + ": " + profile[0]) for key_1, value_1 in self.vlan_dict.items(): for v in value_1: for v in v: if encap == v: pools.append(key_1) for key_2, value_2 in self.policies_dict.items(): if key_2 == key_1: for v in value_2: phy_doms.append(v) for key_3, value_3 in self.policies_dict.items(): for dom in phy_doms: if dom in value_3: if "AAEP" in key_3: aaep.append(key_3) else: continue else: pass else: continue dup_pools = list(dict.fromkeys(pools)) dup_location = list(dict.fromkeys(location)) dup_aaep = list(dict.fromkeys(aaep)) return dup_pools, phy_doms, dup_aaep, dup_location, path def policy_mappings(self): """Maps AAEPS, Vlan Pools, and phys/vmm/routed domain. Return dictionary data structure""" uri = "https://" + self.apic + "/api/node/mo/uni.xml?query-target=subtree&target-subtree-class=physDomP&target-subtree-class=infraRsVlanNs,infraRtDomP&query-target=subtree" headers = {'content-type': 'text/xml'} request = self.session.get(uri, verify=False, headers=headers) root = ET.fromstring(request.text) for infraRtDomP in root.iter("infraRtDomP"): string = infraRtDomP.get("dn") if re.findall(r'phys-.*?[/]\b', string): aaeps = re.findall(r'(?<=attentp-).*(?=])', string) phys_dom = re.findall(r'(?<=phys-).*(?=/rt)', string) self.policies_dict["AAEP " + aaeps[0]].append(phys_dom) elif re.findall(r'l3dom-.*?[/]\b', string): aaeps = re.findall(r'(?<=attentp-).*(?=])', string) l3_dom = re.findall(r'(?<=l3dom-).*(?=/rt)', string) self.policies_dict["AAEP " + aaeps[0]].append(l3_dom) elif re.findall(r'vmmp-.*?[/]\b', string): aaeps = re.findall(r'(?<=attentp-).*(?=])', string) vmm_dom = re.findall(r'(?<=vmmp-).*(?=/rt)', string) self.policies_dict["AAEP " + aaeps[0]].append(vmm_dom[0]) else: continue for infraRsVlanNs in root.iter("infraRsVlanNs"): vl_pool_dn = infraRsVlanNs.get("tDn") phys_dom_dn = infraRsVlanNs.get("dn") if re.findall(r'(?<=phys-).*(?=/)', phys_dom_dn): phys_dom = re.findall(r'(?<=phys-).*(?=/)', phys_dom_dn) vlan_pool = re.findall(r'(?<=vlanns-\[).*(?=])', vl_pool_dn) self.policies_dict[vlan_pool[0]].append(phys_dom) elif re.findall(r'(?<=ledom-).*(?=/)', phys_dom_dn): l3_dom = re.findall(r'(?<=l3dom-).*(?=/)', phys_dom_dn) vlan_pool = re.findall(r'(?<=vlanns-\[).*(?=])', vl_pool_dn) self.policies_dict[vlan_pool[0]].append(l3_dom) elif re.findall(r'(?<=vmmp-).*(?=/)', phys_dom_dn): vmm_dom = re.findall(r'(?<=vmmp-).*(?=/)', phys_dom_dn) vlan_pool = re.findall(r'(?<=vlanns-\[).*(?=])', vl_pool_dn) self.policies_dict[vlan_pool[0]].append(vmm_dom[0]) else: continue return request, self.policies_dict def infr(self, pod=None): """Takes in pod number , and return all information about the fabric hardware. Greate for TAC use""" pod_num = pod pod_number = "pod-{}".format(pod_num) uri = "https://{}/api/node/mo/topology/{}.xml?query-target=children".format(self.apic, pod_number) request = self.session.get(uri, verify=False) root = ET.fromstring(request.text) for fabricNode in root.iter("fabricNode"): fabric_node = fabricNode.get("name") model_node = fabricNode.get("model") serial_node = fabricNode.get("serial") self.device_info.append(fabric_node) self.device_info.append(model_node) self.device_info.append(serial_node) if not self.device_info: return "No Infrastructor Information" else: return self.device_info def view_tenants(self): """Returns ACI Tenant from the arbitrary APIC""" uri = "https://{}/api/class/fvTenant.json".format(self.apic) request = self.session.get(uri, verify=False) response_dict = request.json() total_count = int(response_dict["totalCount"]) try: index = 0 self.tenant_array.clear() for i in range(0, total_count): self.tenant_array.append(response_dict["imdata"][index]["fvTenant"]["attributes"]["name"]) index = index + 1 except IndexError: pass return self.tenant_array def subnet_finder(self, subnet=None): """ Takes in kwarg subnet and finds all details about the subnet (BD, Tenant, scope etc.""" endpoint_dict = {} uri = "https://{}/api/class/fvBD.xml?query-target=subtree".format(self.apic) request = self.session.get(uri, verify=False) root = ET.fromstring(request.text) for fvSubnet in root.iter("fvSubnet"): location = fvSubnet.get("dn") ip = fvSubnet.get("ip") if subnet in ip: gps = location gps_ip = ip scope = fvSubnet.get("scope") try: for fvBD in root.iter("fvBD"): bridge_domain = fvBD.get("name") if re.findall('[?<=/BD-]' + bridge_domain + '(?=/)', gps): gps_bd = bridge_domain uni_route = fvBD.get("unicastRoute") unkwn_uni = fvBD.get("unkMacUcastAct") for fvRsCtx in root.iter("fvRsCtx"): vrf = fvRsCtx.get("tnFvCtxName") location = fvRsCtx.get("dn") print(location) if re.findall('[?<=/BD-]' + gps_bd + '(?=/)', location): print(vrf) gps_vrf = vrf aps = [] epgs = [] for fvRtBd in root.iter("fvRtBd"): dn = fvRtBd.get("dn") if re.findall('[?<=/BD-]' + gps_bd + '(?=/)', dn): ap = re.findall(r'(?<=ap-).*(?=/ep)', dn) aps.append(ap[0]) epg = re.findall(r'(?<=epg-).*(?=\])', dn) epgs.append(epg[0]) else: pass for fvRsBDToOut in root.iter("fvRsBDToOut"): if "fvRsBDToOut" in fvRsBDToOut: dn = fvRsBDToOut.get("dn") if re.findall('[?<=/BD-]' + gps_bd + '(?=/)', dn): if not fvRsBDToOut.get("tnL3extOutName"): l3out = "N/A" else: l3out = fvRsBDToOut.get("tnL3extOutName") else: l3out = "None" for tenant in self.tenant_array: if tenant in gps: gps_tenant = tenant else: continue unpack_ap = [i for i in aps] if not unpack_ap: unpack_ap = "None" unpack_epg = [i for i in epgs] if not unpack_epg: unpack_epg = "None" endpoint_dict["IP"] = gps endpoint_dict["Tenant"] = gps_tenant endpoint_dict["BD"] = gps_bd endpoint_dict["vrf"] = gps_vrf endpoint_dict["L3Out"] = l3out endpoint_dict["Route Enable"] = uni_route endpoint_dict["Scope"] = scope endpoint_dict["Uni Flood"] = unkwn_uni endpoint_dict["APs"] = unpack_ap endpoint_dict["EPGs"] = unpack_epg return endpoint_dict except UnboundLocalError: return "Subnet not found" def view_tenant_vrf(self, tenant=None): """View Tenant vrf, return Tenant vrf names""" uri = "https://{}/api/node/mo/uni/tn-{}.json?query-target=children&target-subtree-class=fvCtx"\ .format(self.apic, tenant) request = self.session.get(uri, verify=False) response = json.loads(request.text) try: index = 0 self.vrf_array.clear() for i in range(0, 100): self.vrf_array.append(response["imdata"][index]["fvCtx"]["attributes"]["name"]) index = index + 1 except IndexError: pass return self.vrf_array def view_bd(self, tenant=None): """View Bridge domains of a Tenant, returns bridge domain names""" uri = "https://{}/api/node/mo/uni/tn-{}.json?query-target=children&target-subtree-class=fvBD"\ .format(self.apic, tenant) request = self.session.get(uri, verify=False) response = json.loads(request.text) total_count = int(response["totalCount"]) index = 0 self.bd_array.clear() for i in range(0, total_count): self.bd_array.append(response["imdata"][index]["fvBD"]["attributes"]["name"]) index = index + 1 return self.bd_array def view_app_profiles(self, tenant=None): """View Application profiles of a particular Tenant, return App profiles""" uri = "https://{}/api/node/mo/uni/tn-{}.json?query-target=children&target-subtree-class=fvAp"\ .format(self.apic, tenant) request = self.session.get(uri, verify=False) response = json.loads(request.text) total_count = int(response["totalCount"]) index = 0 self.ap_array.clear() for i in range(0, total_count): self.ap_array.append(response["imdata"][index]["fvAp"]["attributes"]["name"]) index = index + 1 return self.ap_array def view_epgs(self, tenant=None, app=None): """View endpoint groups of a particular Tenant-App profile, returns EPG names""" uri = "https://{}/api/node/mo/uni/tn-{}/ap-{}.json?query-target=children&target-subtree-class=fvAEPg"\ .format(self.apic, tenant, app) request = self.session.get(uri, verify=False) response = json.loads(request.text) total_count = int(response["totalCount"]) index = 0 self.epg_array.clear() for i in range(0, total_count): self.epg_array.append(response["imdata"][index]["fvAEPg"]["attributes"]["name"]) index = index + 1 return self.epg_array def enpoint_tracker(self, endpoint=None): """This method take in a IP or MAC address and returns the endpoint data. Return string if no endpoint is found""" try: ipaddress.IPv4Address(endpoint) uri = "https://%s" % self.apic + "/api/node/class/fvCEp.xml?rsp-subtree=full&rsp-subtree-include=" \ "required&rsp-subtree-filter=eq(fvIp.addr," + "\"%s\"" % endpoint except ValueError: uri = "https://%s" % self.apic + "/api/node/class/fvCEp.xml?rsp-subtree=full&rsp-subtree-class=" \ "fvCEp,fvRsCEpToPathEp,fvIp,fvRsHyper,fvRsToNic,fvRsToVm&query-target-filter=eq(fvCEp.mac," \ + "\"%s\"" % endpoint request = self.session.get(uri, verify=False) root = ET.fromstring(request.text) for fvCEp in root.iter("fvCEp"): ep_name = fvCEp.get("name") ep_mac = fvCEp.get("mac") encap = fvCEp.get("encap") ep_loc = fvCEp.get("dn") ep_ip = fvCEp.get("ip") endpoint = ("Name: {0:20}\nEP: {1:<20}\nEncapsulation: {2:<20}\nLocation: {3:<20}\nIP: {4:<20}" .format(ep_name, ep_mac, encap, ep_loc, ep_ip)) try: return endpoint except UnboundLocalError: return "Endpoint Not Found" class AciOpsSend(AciOps): """ACI send basic configs. Return value will be APIC response in dictionary structure, or string notify the caller of and error""" def __init__(self, **kwargs): """ Import * from AciOps class. Use AciOps login method to create a http session. Once session has been intiated, call AciOps view_tenants method. The AciOps self.session and self.tenant_array will be used throughout""" super().__init__() self.login(apic=kwargs["apic"], username=kwargs["username"], password=kwargs["password"]) self.view_tenants() def create_tenant(self, tenant=None): """Create tenant, arg supplied will be tenants name. Conditional check will be done o insure no duplicates""" uri = """https://{}/api/mo/uni.json""".format(self.apic) if tenant not in self.tenant_array: tenants = """{"fvTenant" : { "attributes" : { "name" : "%s"}}}""" % tenant request = self.session.post(uri, verify=False, data=tenants, headers=self.json_header) tenants = self.view_tenants() return request, tenants else: return "Tenant: %s Exist" % tenant def create_app_profile(self, tenant=None, app=None): """Create app prof, args supplied will be tenant, and app prof name. Conditional check will be done to insure no duplicates""" app_profiles = self.view_app_profiles(tenant=tenant) if app not in app_profiles: uri = "https://" + self.apic + "/api/mo/uni/tn-" + tenant + ".json" app_profile = "{\"fvAp\": " \ "{\"attributes\": " \ "{\"name\": \"%s\"}}}}" % app request = self.session.post(uri, verify=False, data=app_profile, headers=self.json_header) app_profiles = self.view_app_profiles(tenant=tenant) return request, app_profiles else: return "App Profile: %s Exist " % app def create_epg(self, tenant=None, app=None, epg=None): """Create epg, args supplied will be tenant, and app prof name, and epg name Conditional check will be done to insure no duplicates""" epgs = self.view_epgs(tenant=tenant, app=app) if epg not in epgs: uri = "https://" + self.apic + "/api/mo/uni/tn-" + tenant + "/ap-" + app + ".json" epg = "{\"fvAEPg\":" \ "{\"attributes\": " \ "{\"name\": \"%s\"}}}}" % epg request = self.session.post(uri, verify=False, data=epg, headers=self.json_header) epgs = self.view_epgs(tenant=tenant, app=app) return request, epgs else: return "EPG: %s Exist" % epg def create_bd_l3(self, tenant=None, bd=None, subnet=None, scope=None): """Create bd, args supplied will be tenant. Conditional check will be done to insure no duplicates""" bds = self.view_bd(tenant=tenant) if bd not in bds: uri = "https://" + self.apic + "/api/mo/uni/tn-" + tenant + ".json" bridge_dom = "{\"fvBD\":" \ "{\"attributes\": " \ "{\"name\": \"%s\"" % bd + "}," \ "\"children:[" \ "{\"fvSubnet\": " \ "{\"attributes\":" \ "{\"ip\": \"%s\"" % subnet + "," \ "{\"scope\": \"%s\"" % scope + "}}}}]}}}" request = self.session.post(uri, verify=False, data=bridge_dom, headers=self.json_header) bds = self.view_bd(tenant=tenant) bd_info = self.subnet_finder(subnet=subnet) return request, bds, bd_info else: return "BD: %s Exist" % bd def routing_scope(self, tenant=None, bd=None, subnet=None, scope=None): """Configuring routing scope (shared, private, external). First we split the scope to check for validity if valid, use the orignal scope arg for the variable""" split_scope = scope.split(",") scope_list = ["private", "public", "shared"] bds = self.view_bd(tenant=tenant) for scope in split_scope: if scope not in scope_list: raise ValueError("Invalid Scope \"{}\" - Expecting private|public|shared".format(scope)) else: pass if bd in bds: uri = "https://" + self.apic + "/api/mo/uni/tn-" + tenant + "/BD-" + bd + "/subnet-[" + subnet + "].json" bridge_dom = "{\"fvSubnet\": " \ "{\"attributes\":" \ "{\"scope\": \"%s\"" % scope + "}}}" request = self.session.post(uri, verify=False, data=bridge_dom, headers=self.json_header) bds = self.view_bd(tenant=tenant) bd_info = self.subnet_finder(subnet=subnet) return request, bds, bd_info else: return "BD: %s Exist" % bd def enable_unicast(self, tenant=None, bd=None, enable=None): """Create bd, args supplied will be tenant Conditional check will be done to insure no duplicates, require yes/no input""" bds = self.view_bd(tenant=tenant) yes_no = ["yes", "no"] if enable not in yes_no: raise ValueError("Invalid arg \"{}\" - Expecting yes/no".format(enable)) if bd in bds: uri = "https://" + self.apic + "/api/mo/uni/tn-" + tenant + ".json" bridge_dom = "{\"fvBD\":" \ "{\"attributes\": " \ "{\"name\": \"%s\"" % bd + ", \"" \ "unicastRoute\": \"%s\"" % enable + "}}}" request = self.session.post(uri, verify=False, data=bridge_dom, headers=self.json_header) return request, bridge_dom else: return "BD: %s Exist" % bd def create_bd_l2(self, tenant=None, bd=None): """Create L2 bd, args supplied will be tenant Conditional check will be done to insure no duplicates""" bds = self.view_bd(tenant=tenant) if bd not in bds: uri = "https://" + self.apic + "/api/mo/uni/tn-" + tenant + ".json" bridge_dom = "{\"fvBD\":" \ "{\"attributes\": " \ "{\"name\": \"%s\"" % bd + "}}}" request = self.session.post(uri, verify=False, data=bridge_dom, headers=self.json_header) bds = self.view_bd(tenant=tenant) return request, bds else: return "BD: %s Exist" % bd def create_vrf(self, tenant=None, vrf=None): """Create tenant vrf, args supplied will be tenant Conditional check will be done to insure no duplicates""" vrfs = self.view_tenant_vrf(tenant=tenant) if vrf not in vrfs: uri = "https://" + self.apic + "/api/mo/uni/tn-" + tenant + ".json" vrf = "{\"fvCtx\":" \ "{\"attributes\": " \ "{\"name\": \"%s\"" % vrf + "}}}" request = self.session.post(uri, verify=False, data=vrf, headers=self.json_header) vrfs = self.view_tenant_vrf(tenant=tenant) return request, vrfs else: return "Vrf: %s Exist" % vrf def vrf_to_bd(self, tenant=None, bd=None, vrf=None): """Assign vrf to bd, args supplied will be tenant, bd name, vrf name Conditional check will be done to insure vrf has been configured""" vrfs = self.view_tenant_vrf(tenant=tenant) if vrf in vrfs: uri = "https://" + self.apic + "/api/mo/uni/tn-" + tenant + ".json" vrf_bd = "{\"fvBD\":" \ "{\"attributes\": " \ "{\"name\": \"%s\"" % bd + "}," \ "\"children:[" \ "{\"fvRsCtx \": " \ "{\"attributes\":" \ "{\"tnFvCtxName\": \"%s\"" % vrf + "}}}]}}}" request = self.session.post(uri, verify=False, data=vrf_bd, headers=self.json_header) vrfs = self.view_tenant_vrf(tenant=tenant) return request, vrfs else: return "VRF: %s Doesn't Exist " % vrf
ACIOps
/ACIOps-2.0.0.tar.gz/ACIOps-2.0.0/ACIOperations/ACIOps.py
ACIOps.py
# # acme.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Starter for the ACME CSE # import argparse, sys sys.path.append('acme') sys.path.append('apps') from Configuration import defaultConfigFile, defaultImportDirectory import CSE version = '0.2.1' description = 'ACME ' + version + ' - An open source CSE Middleware for Education' # Handle command line arguments def parseArgs(): parser = argparse.ArgumentParser(description=description) parser.add_argument('--config', action='store', dest='configfile', default=defaultConfigFile, help='specify the configuration file') # two mutual exlcusive arguments group = parser.add_mutually_exclusive_group() group.add_argument('--apps', action='store_true', dest='appsenabled', default=None, help='enable internal applications') group.add_argument('--no-apps', action='store_false', dest='appsenabled', default=None, help='disable internal applications') parser.add_argument('--db-reset', action='store_true', dest='dbreset', default=None, help='reset the DB when starting the CSE') parser.add_argument('--db-storage', action='store', dest='dbstoragemode', default=None, choices=[ 'memory', 'disk' ], type=str.lower, help='specify the DB´s storage mode') parser.add_argument('--log-level', action='store', dest='loglevel', default=None, choices=[ 'info', 'error', 'warn', 'debug', 'off'], type=str.lower, help='set the log level, or turn logging off') parser.add_argument('--import-directory', action='store', dest='importdirectory', default=None, help='specify the import directory') return parser.parse_args() # TODO init directory if __name__ == '__main__': # Start the CSE with command line arguments. # In case the CSE should be started without command line parsing, the values # can be passed instead. Unknown arguments are ignored. # For example: # # CSE.startup(None, configfile=defaultConfigFile, loglevel='error', resetdb=None) # # Note: Always pass at least 'None' as first and then the 'configfile' parameter. print(description) CSE.startup(parseArgs())
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme.py
acme.py
# ![](webui/img/acme_sm.png) # ACME oneM2M CSE An open source CSE Middleware for Education. Version 0.3.0 ## Introduction This CSE implements a subset of the oneM2M standard specializations (see [http://www.onem2m.org](http://www.onem2m.org)). The intention is to provide an easy to install, extensible, and easy to use and maintain CSE for educational purposes. Also see the discussion on [Limitations](#limitations) below. ![](docs/images/webui.png) ## Prerequisites In order to run the CSE the following prerequisites must be fulfilled: - **Python 3.8** : Install this or a newer version of Python with your favorite package manager. - You may consider to use a virtual environment manager like pyenv + virtualenv (see, for example, [this tutorial](https://realpython.com/python-virtual-environments-a-primer/)). - **flask**: The CSE uses the [Flask](https://flask.palletsprojects.com/) web framework. Install it by running the pip command: pip3 install flask - **psutil**: The [psutil](https://pypi.org/project/psutil/) package is used to gather various system information for the CSE's hosting node resource. Install it by running the pip command: pip3 install psutil - **requests**: The CSE uses the [Requests](https://requests.readthedocs.io) HTTP Library to send requests vi http. Install it by running the pip command: pip3 install requests - **tinydb** : To store resources the CSE uses the lightweight [TinyDB](https://github.com/msiemens/tinydb) document database. Install it by running the pip command: pip3 install tinydb ## Installation and Configuration Install the ACME CSE by copy the whole distribution to a new directory. You also need to copy the configuration file [acme.ini.default](acme.ini.default) to a new file *acme.ini* and make adjustments to that new file. cp acme.ini.default acme.ini Please have a look at the configuration file. All the CSE's settings are read from this file. There are a lot of individual things to configure here. Mostly, the defaults should be sufficient, but individual settings can be applied to each of the sections. ## Running ### Running the Notifications Server If you want to work with subscriptions and notification: You might want to have a Notifications Server running first before starting the CSE. The Notification Server provided with the CSE in the [tools/notificationServer](tools/notificationServer) directory provides a very simple implementation that receives and answers notification requests. See the [README](tools/notificationServer/README.md) file for further details. ### Running the CSE You can start the CSE by simply running it from a command line: python3 acme.py In this case the configuration file *acme.ini* must be in the same directory. In additions, you can provide additional command line arguments that will override the respective settings from the configuration file: - **-h**, **--help** : show a help message and exit. - **--apps**, **--noapps**: Enable or disable the build-in applications. This overrides the settings in the configuration file. - **--config CONFIGFILE**: Specify a configuration file that is used instead of the default (*acme.ini*) one. - **--db-reset**: Reset and clear the database when starting the CSE. - **--db-storage {memory,disk}**: Specify the DB´s storage mode. - **--log-level {info, error, warn, debug, off}**: Set the log level, or turn logging off. - **--import-directory IMPORTDIRECTORY**: Specify the import directory. ### Stopping the CSE The CSE can be stopped by pressing *CTRL-C* **once** on the command line. Please note, that the shutdown might take a moment (e.g. gracefully terminating background processes, writing database caches, sending notifications etc). **Being impatient and hitting *CTRL-C* twice might lead to data corruption.** ### Downloading and Running a Docker Image A Docker image with reasonable defaults is available on Docker Hub: [https://hub.docker.com/repository/docker/ankraft/acme-onem2m-cse](https://hub.docker.com/repository/docker/ankraft/acme-onem2m-cse) . You can download and run it with the following shell command: ```bash $ docker run -p 8080:8080 --rm --name acme-onem2m-cse ankraft/acme-onem2m-cse ``` #### Build Your Own Docker Image You can adapt (ie. configure a new Docker Hub ID) the build script and *Dockerfile* in the [tools/Docker](tools/Docker) directory. The build script takes the current scripts, configuration, resources etc, builds a new Docker image, and uploads the image to the configured Docker Hub repository. ### Importing Resources During startup it is possible to import resources into to CSE. Each resource is read from a single file in the [init](./init) resource directory specified in the configuration file. Not much validation, access control, or registration procedures are performedfor imported resources. #### Importing Mandatory Resources **Please note** that importing is required for creating the CSEBase resource and at least two (admin) ACP resources. Those are imported before all other resources, so that the CSEBase resource can act as the root for the resource tree. The *admin* ACP is used to access resources with the administrator originator. The *default* ACP resource is the one that is assigned for resources that don't specify an ACP on their own. The filenames for these resources must be: - [csebase.json](init/csebase.json) for the CSEBase. - [acp.admin.json](init/acp.admin.json) for the admin ACP. - [acp.default.json](init/acp.default.json) for the default ACP. #### Importing Other Resources After importing the mandatory resources all other resources in the [init](./init) directory are read in alphabetical order and are added (created) to the CSE's resource tree. Imported resources must have a valid *acpi* attribute, because no default *acpi* is assigned during importing. #### Updating Resources If the filename contains the substring *update*, then the resource specified by the resource's *ri* attribute is updated instead of created. #### Examples & Templates A minimal set of resources is provided in the [init](./init) directory. Definitions for a more sophisticated setup can be found in the [tools/init.example](tools/init.example) directory. To use these examples, you can either copy the resources to the *init* directory or change the "cse -> resourcesPath" entry in the *acme.ini* configuration file. The directory [tools/resourceTemplates](tools/resourceTemplates) contains templates for supported resource types. Please see the [README](tools/resourceTemplates/README.md) there for further details. ## Web UI The Web UI is by default enabled and reachable under the (configurable) path *&lt;host>/webui*. - To login you need to specify a valid originator. The default "admin" originator is *CAdmin*. - Beside of the default *CSEBase* resource you can specify a different resource identifier as the root of the resource tree. - You can navigate the resource tree with arrow keys. - You can switch between short and long attribute names (press CTRL-H). ### REST UI The web UI also provides a REST UI where you can send REST requests directed at resources on the CSE. ![](docs/images/webui-REST.png) ## Operation ### Remote CSE When a CSE is configured as an MN-CSE of ASN-CSE it can connect to a remote CSE, respectively an IN-CSE and MN-CSE can receive connection requests from those CSE types. A *remoteCSE* resource is created in case of a successful connection. A CSE checks regularly the connection to other remote CSEs and removes the *remoteCSE* if the connection could not been established. Announced resources are currently **not** supported by this implementation. But you can issue transfer requests to a remote CSE via its *remoteCSE* resource. These requests are forwarded by the CSE. You must configure the details of the remote CSE in the configuration file. ### CSE Originator Assignment Whenever a new *ACP* resource is created, the CSE's admin *originator* is assigned to that resource automatically. This way resources can always accessed by this originator. This behaviour can be configured in the *[cse.resource.acp]* section of the configuration file. ### AE Registration Whenever a new *AE* registers itself with the CSE (using the originators *C* or *S*) then a new originator for that *AE* is created. Also, the CSE automatically creates a new *ACP* resource for that new originator. Be aware that this *ACP* resource is also removed when the *AE* is deleted. The operations for the *ACP* resource can be configured in the *[cse.resource.acp]* section of the configuration file. ## Nodes and Applications Currently, two component implementations are provided in addtion to the main CSE. They serve as examples how implement components that are hosted by the CSE itself. ### CSE Node This component implements a &lt;node> resource that provides additional information about the actual node (system) the CSE is running on. These are specializations of &lt;mgmtObj>'s, namely battery, memory, and device information. It can be enabled/disabled and configured in the **[app.csenode]** section of the configuration file. ### Statistics AE The component implements an &lt;AE> resource that provides statistic information about the CSE. It defines a proprietary &lt;flexContainer> specialization that contains custom attributes for various statistic information, and which is updated every few seconds. It can be enabled/disabled and configured in the **[app.statistics]** section of the configuration file. ### Developing Nodes and AEs You can develop your own components that technically run inside the CSE themselves by following the pattern of those two components: - Implement a class with either *AEBase* or *NodeBase* as a base class. This will create an &lt;AE> or &lt;node> resource for you. - Implement a worker method and start it in the *\_\_init\_\_()* method. This method is called regularly in the background. This worker method can implement the main functionality of the &lt;AE> or &lt;node>. - Implement a *shutdown()* method that is called when the CSE shuts down. - Add your new component to the following methods in [acme/CSE.py](acme/CSE.py): - *startApps()*: starting your component. - *stopApps()*: shutting down your component. There are more helper methods provided by the common *AppBase* and *AEBase* base classes, e.g. to send requests to the CSE via Mca, store AE data persistently etc. ## Integration Into Other Applications It is possible to integrate the CSE into other applications, e.g. a Jupyter Notebook. In this case you would possibly like to provide startup arguments, for example the path of the configuration file or the logging level, directly instead of getting them from *argparse*. You might want to get the example from the starter file [acme.py](acme.py) where you could replace the line: ```python CSE.startup(parseArgs()) ``` with a call to the CSE's *startup()* function: ```python CSE.startup(None, configfile=defaultConfigFile, loglevel='error') ``` Please note that in case you provide the arguments directly the first argument needs to be `None`. The names of the *argparse* variables can be used here, and you may provide all or only some of the arguments. Please note that you need to keep or copy the `import` and `sys.path` statements at the top of that file. ## URL Mappings As a convenience to access resources on a CSE and to let requests look more like "normal" REST request you can define mappings. The format is a path that maps to another path and arguments. When issued a request to one of those mapped paths the http server issues a redirect to the other path. For example, the path */access/v1/devices* can be mapped to */cse-mn?ty=14&fu=1&fo=2&rcn=8* to easily retrieve all nodes from the CSE. See the configuration file for more examples. ## Limitations - **This is by no means a fully compliant, secure or stable CSE! Don't use it in production.** - This CSE is intended for educational purposes. The underlying database system is not optimized in any way for high-volume, high-accessibility. - No support for https yet. - Security: None. Please contact me if you have suggestions to improve this. - Unsupported resource types are just stored, but no check or functionality is provided for those resources. The same is true for unknown resource attributes. Only a few attributes are validated. ## Supported Resource Types and Functionalities ### Resources The CSE supports the following oneM2M resource types: - **CSEBase (CB)** - **Access Control Policy (ACP)** - **Remote CSE (CSR)** Announced resources are yet not supported. Transit request, though, to resources on the remote CSE are supported. - **Application Entity (AE)** - **Container (CNT)** - **Content Instance (CIN)** - **Subscription (SUB)** Notifications via http to a direct url or an AE's Point-of-Access (POA) are supported as well. - **Group (GRP)** The support includes requests via the *fopt* (fan-out-point) virtual resource. - **Node (NOD)** The support includes the following **Management Object (mgmtObj)** specializations: - **Firmware (FWR)** - **Software (SWR)** - **Memory (MEM)** - **AreaNwkInfo (ANI)** - **AreaNwkDeviceInfo (ANDI)** - **Battery (BAT)** - **DeviceInfo (DVI)** - **DeviceCapability (DVC)** - **Reboot (REB)** - **EventLog (EVL)** - **FlexContainer Specializations** Any specializations is supported. There is no check performed against a schema (e.g. via the *cnd* attribute). Resources of any other type are stored in the CSE but no further processed and no checks are performed on these resources. The type is marked as *unknown*. ### Discovery The following result contents are implemented for Discovery: - attributes + child-resources (rcn=4) - attributes + child-resource-references (rcn=5) - child-resource-references (rcn=6) - child-resources (rcn=8) ## Third-Party Components ### CSE - Flask: [https://flask.palletsprojects.com/](https://flask.palletsprojects.com/), BSD 3-Clause License - Requests: [https://requests.readthedocs.io/en/master/](https://requests.readthedocs.io/en/master/), Apache2 License - TinyDB: [https://github.com/msiemens/tinydb](https://github.com/msiemens/tinydb), MIT License - PSUtil: [https://github.com/giampaolo/psutil](https://github.com/giampaolo/psutil), BSD 3-Clause License ### UI Components - TreeJS: [https://github.com/m-thalmann/treejs](https://github.com/m-thalmann/treejs), MIT License - Picnic CSS : [https://picnicss.com](https://picnicss.com), MIT License ## Roadmap & Backlog - CSE: Announcements - CSE: Better resource validations - CSE: Timeseries - CSE: Support discovery also for other request types - UI: Support for resource specific actions (e.g. latest, oldest) - UI: Graph for Container reosurces - Importer: Automatically import/update resources when the CSE is running - App development: support more specializations ## The Messy Details ![](docs/images/cse_uml.png) ## License BSD 3-Clause License for the CSE and its native components and modules. Please see the individual licenses of the used third-party components.
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/README.md
README.md
import os, setuptools with open("README.md", "r") as fh: long_description = fh.read() def createDataFiles(directory): excludes = ( '__pycache__' ) result = [] for root, folders, files in os.walk(directory): if not root.endswith(excludes): result += [(root, [os.path.join(root,f) for f in files])] return result # return [(root, [os.path.join(root,f) for f in files]) # for root, folders, files in os.walk(directory)] # return [(root, [os.path.join(root,f) for f in files]) # for root, folders, files in os.walk(directory)] datafiles = [('.', ['acme.py', 'acme.ini.default', 'CHANGELOG.md'])] datafiles += createDataFiles('acme') datafiles += createDataFiles('apps') datafiles += createDataFiles('docs') datafiles += createDataFiles('init') datafiles += createDataFiles('webui') datafiles += createDataFiles('tools/init.example') datafiles += createDataFiles('tools/notificationServer') datafiles += createDataFiles('tools/resourceTemplates') print(datafiles) setuptools.setup( # Application name: name='ACME oneM2M CSE', # Version number (initial): version='0.3.0', # Application author details: author='Andreas Kraft', author_email='onem2m@mheg.org', url='https://github.com/ankraft/ACME-oneM2M-CSE', # Packages #packages=['acme', 'acme/resources', 'acme/helpers', 'apps', 'docs'], packages = [], # Include additional files into the package include_package_data=False, data_files=datafiles, # Details #url="http://pypi.python.org/pypi/MyApplication_v010/", # license='BSD 3-Clause', description="An open source CSE Middleware for Education.", long_description=long_description, long_description_content_type='text/markdown', # Dependent packages (distributions) install_requires=[ 'flask', 'psutil', 'requests', 'tinydb' ], keywords='onem2m cse framework', classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', ], python_requires='>=3.8' )
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/setup.py
setup.py
# Changelog ## Unreleased 0.3.0 - 2020-04-20 - [CSE] Discovery supports "attributes + children" return content. - [CSE] Changed command line argument --reset-db to --db-reset . - [CSE] Added command line argument --db-storage . - [CSE] Added support for FlexContainerInstance. - [CSE] Fixed discovery results: ignore latest, oldest, and fixed result format. - [CSE] Added command line arguments --apps / --no-apps to enable and disable internal applications. Also added entry in config file. - [CSE] Added sorting of discovery results. Configurable. ## 0.2.1 - 2020-03-06 - [APPS] Fixed wrong originator handling for already registered AEs. - [APPS] Added persistent storage support for AEs. ## 0.2.0 - 2020-03-02 - [CSE] Checking and setting "creator" attribute when creating new resources. - [ACP] Always add "admin" originator to newly created ACPs (configurable). - [ACP] Imporved default ACP. Any new resource without ACP gets the default ACP assigned. - [AE] Added proper AE registration. An ACP is automatically created for a new AE, and also removed when the corresponding AE is removed. - [LOGGING] Added option to enable/disable logging to a log file (Logging:enableFileLogging). If disabled, log-messages are only written to the console. - [LOGGING] Possibility to disable logging on the command line. - [IMPORTING] Added default ACP. - [WEB] Browser request to "/"" will now redirect to the webui's URL. - [WEB] REST UI will not refresh anymore when automatic refresh is on. - [WEB] Added LOGO & favicon. - [MISC] Various fixes and improvements. ## 0.1.0 - 2020-02-09 - First release
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/CHANGELOG.md
CHANGELOG.md
// // main.js // // (c) 2020 by Andreas Kraft // License: BSD 3-Clause License. See the LICENSE file for further details. // // Main functions, setup etc for the web UI // function getChildren(node, errorCallback) { resource = node.resource // get children var ri = resource['ri'] + "?fu=1&lvl=1&rcn=6" // TODO move this to the getchildren request var client = new HttpClient(); addr = cseid + "/" + ri // addr = "/" + ri client.getChildren(addr, node, function(response) { // TODo //client.getChildren(cseid + "/" + ri, node, function(response) { // TODo // remove all children, if any removeChildren(node) resource = JSON.parse(response) ris = resource["m2m:uril"] for (ri of ris) { // TODO in extra function createNode() var childNode = new TreeNode(ri); childNode.on("click", clickOnNode) childNode.on("expand", expandNode) childNode.on("collapse", collapseNode) childNode.on("contextmenu", function(e,n) { showContextMenu(e, n) }) childNode.ri = ri childNode.wasExpanded = false childNode.setExpanded(false) childNode.resolved = false node.addChild(childNode) } if (node != root) { if (node.wasExpanded) { node.setExpanded(true) clickOnNode(null, node) expandNode(node) } else { node.setExpanded(false) } } else { // Display the root node expanded and show attributes etc expandNode(root) root.setSelected(true) clickOnNode(null, root) } // add short info in front of name ty = node.resource['ty'] pfx = shortTypes[ty] if (ty == 13) { var mgd = node.resource['mgd'] if (mgd == undefined) { pfx = "MGO" } else { pfx = mgdShortTypes[mgd] } } if (pfx == undefined) { pfx = "unknown" } node.setUserObject(pfx + ": " + node.getUserObject()) if (tree != null) { tree.reload() } }, function() { typeof errorCallback === 'function' && errorCallback(); }); } function getResource(ri, node, callback) { _getResource(ri, node, function(node) { document.getElementById("connectButton").className = "button success" document.getElementById("connectButton").text = "Connected" typeof callback === 'function' && callback(node); }, function() { // error callback if (node.ri.endsWith("/la") || node.ri.endsWith("/ol")) { // special handling for empty la or ol node.setUserObject(node.ri.slice(-2)) node.resolved = true tree.reload() return } document.getElementById("connectButton").className = "button error" document.getElementById("connectButton").text = "Reconnect" showAppArea(false) var x = document.getElementById("treeContainer"); x.innerHTML = ""; tree = null; root = null; clearResourceInfo() clearRootResourceName() clearAttributesTable() clearJSONArea() // TODO Display Error message }) } function _getResource(ri, node, callback, errorCallback) { var client = new HttpClient(); client.get(ri, node, function(response) { // TODO resource = JSON.parse(response) var k = Object.keys(resource)[0] var oldUserObject = node.getUserObject() node.hasDetails = true if (oldUserObject.endsWith("/la")) { node.setUserObject("la") } else if (oldUserObject.endsWith("/ol")) { node.setUserObject("ol") } else if (oldUserObject.endsWith("/fopt")) { node.setUserObject("fopt") node.hasDetails = false } else { node.setUserObject(resource[k].rn) } node.resource = resource[k] node.resourceFull = resource node.resolved = true node.ri = ri //node.wasExpanded = false getChildren(node, null) typeof callback === 'function' && callback(node); }, function(response, status) { typeof errorCallback === 'function' && errorCallback(status); }); } function connectToCSE() { clearAttributesTable() clearJSONArea() clearResourceInfo() clearRootResourceName() delete nodeClicked // Get input fields originator = document.getElementById("originator").value; rootri = document.getElementById("baseri").value; root = new TreeNode(""); root.on("click", clickOnNode) root.on("expand", expandNode) root.on("collapse", collapseNode) root.on("contextmenu", function(e,n) { showContextMenu(e, n) }) tree = new TreeView(root, "#treeContainer"); getResource(rootri, root, function(node) { showAppArea(true) setRootResourceName(node.resource.rn) // remove the focus from the input field document.activeElement.blur(); var x = document.getElementById("appArea") x.focus() }) } function toggleRefresh() { if (typeof refreshTimer !== "undefined") { document.getElementById("refreshButton").className = "button" cancelRefreshResource() } else { document.getElementById("refreshButton").className = "button success" setupRefreshResource(5) } } function showAppArea(state) { var x = document.getElementById("appArea") var f = document.getElementById("originator") if (state) { x.style.display = "block"; } else { x.style.display = "none"; // inputfield focus f.focus() // f.select() } } var cursorEnabled = true; // callback for info tabs function tabTo( number) { switch(number) { case 1: cursorEnabled = true; break; case 2: cursorEnabled = true; break; case 3: cursorEnabled = false; break; } } function setup() { // document.body.style.zoom=0.6; this.blur(); var x = document.getElementById("baseri"); cseid = getUrlParameterByName("ri") x.value = cseid document.title = "ACME CSE - " + cseid // hide when not connected showAppArea(false) setupContextMenu() // add key event listener for refresh document.onkeypress = function(e) { let key = event.key.toUpperCase(); if (key == 'R' && e.ctrlKey) { refreshNode() } else if (key == 'H' && e.ctrlKey) { printLongNames = !printLongNames clearAttributesTable() if (nodeClicked.hasDetails) { fillAttributesTable(nodeClicked.resource) } } else if (key == 'C' && e.ctrlKey) { connectToCSE(); } } document.onkeydown = function(e) { let keyCode = event.keyCode if (cursorEnabled == false) { return } if (typeof nodeClicked === "undefined") { return } p = nodeClicked.parent if (typeof p !== "undefined") { index = p.getIndexOfChild(nodeClicked) count = p.getChildCount() } if (keyCode == 40 && typeof p !== "undefined") { // down index = (index + 1) % count newnode = p.getChildren()[index] clickOnNode(null, newnode) } else if (keyCode == 38 && typeof p !== "undefined") { // up index = (index + count - 1) % count newnode = p.getChildren()[index] clickOnNode(null, newnode) } else if (keyCode == 39) { // right or open an unexpanded subtree if (nodeClicked.isLeaf()) { return } if (nodeClicked.isExpanded() == false) { nodeClicked.setExpanded(true) tree.reload() return } clickOnNode(null, nodeClicked.getChildren()[0]) } else if (keyCode == 37) { // left or close an expanded subtree if (nodeClicked.isLeaf() == false && nodeClicked.isExpanded()) { nodeClicked.setExpanded(false) tree.reload() return } if (typeof p !== "undefined") { clickOnNode(null, p) } } else if (keyCode == 13) { // return nodeClicked.toggleExpanded() tree.reload() } else if (keyCode == 9) { e.preventDefault(); e.stopPropagation(); } } initRestUI(); }
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/webui/js/main.js
main.js
// // main.js // // (c) 2020 by Andreas Kraft // License: BSD 3-Clause License. See the LICENSE file for further details. // // Adding a context menu for the web UI // var cmenu = [ { "text": "Refresh", "events": { "click": function(e) { refreshNode() } } } ]; var menu function showContextMenu(event, node) { nodeClicked.setSelected(false) nodeClicked = node nodeClicked.setSelected(true) menu.display(event); } function setupContextMenu() { menu = new ContextMenu(cmenu); }
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/webui/js/menu.js
menu.js
// // rest.js // // (c) 2020 by Andreas Kraft // License: BSD 3-Clause License. See the LICENSE file for further details. // // Javascript Mca functions // var HttpClient = function() { this.get = function(id, node, callback, errorCallback) { sendRetrieveRequest(node, id, originator, callback, errorCallback ) } // TODO: do we really need a separate method? this.getChildren = function(id, node, callback, errorCallback) { sendRetrieveRequest(node, id, originator, callback, errorCallback) } } function sendRetrieveRequest(node, id, originator, callback, errorCallback) { sendRequest("GET", node, id, originator, callback, errorCallback) } function sendRequest(method, node, url, originator, callback, errorCallback) { var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState == 4) { if (request.status == 200) { callback(request.responseText, node); } else { typeof errorCallback === 'function' && errorCallback(request.responseText, request.status); } } } while(url.charAt(0) === '/') { // remove possible multiple leading / url = url.slice( 1 ); } request.open(method, "/"+url, true ); request.setRequestHeader("X-M2M-Origin", originator); request.setRequestHeader("Accept", "application/json"); request.setRequestHeader("X-M2M-RI", "123"); request.send(null); }
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/webui/js/rest.js
rest.js
// // restui.js // // (c) 2020 by Andreas Kraft // License: BSD 3-Clause License. See the LICENSE file for further details. // // REST UI components // var currentRestRequestMethod = "GET" var currentResource = null var currentResourceType = null var btnGet var btnPost var btnPut var btnDelete var spanGet var spanPost var spanPut var spanDelete var requestbody var requestarea var sendbutton function initRestUI() { requestbody = document.getElementById("rest-requestbody"); requestarea = document.getElementById("rest-requestarea"); sendbutton = document.getElementById("sendButton"); var rad = document.getElementsByName("rest-method"); for(var i = 0; i < rad.length; i++) { rad[i].onclick = function() { currentRestRequestMethod = this.value fillRequestArea() }; } btnGet = document.getElementById("methodget") btnPost = document.getElementById("methodpost") btnPut = document.getElementById("methodput") btnDelete = document.getElementById("methoddelete") spanGet = document.getElementById("spanget") spanPost = document.getElementById("spanpost") spanPut = document.getElementById("spanput") spanDelete = document.getElementById("spandelete") } function setRestUI(resourceFull) { currentResourceType = Object.keys(resourceFull)[0]; currentResource = resourceFull[currentResourceType] bri = document.getElementById("baseri").value cri = "/" + currentResource.ri if (bri == cri) { document.getElementById("rest-url").value=bri } else { document.getElementById("rest-url").value=bri + cri } // check requests for this resource type // First enable all buttons btnGet.disabled = false btnPost.disabled = false btnPut.disabled = false btnDelete.disabled = false spanGet.style.display = "inline-block" spanPost.style.display = "inline-block" spanPut.style.display = "inline-block" spanDelete.style.display = "inline-block" if (currentResourceType == "m2m:cb") { // CSE disableButton(btnDelete, spanDelete) } else if (currentResourceType == "m2m:acp") { // ACP disableButton(btnPost, spanPost) } else if (currentResourceType == "m2m:cin") { // CIN disableButton(btnPost, spanPost) disableButton(btnPut, spanPut) } else if (currentResourceType == "m2m:sub") { // SUB disableButton(btnPost, spanPost) } fillHeaderArea(currentResource.ty) fillRequestArea() } // disable a button and hide it. If it is selected, then select the GET button function disableButton(btn, spn) { btn.disabled = true spn.style.display = "none" if (btn.checked) { btn.checked = false btnGet.checked = true currentRestRequestMethod = "GET" } } function restSendForm() { restSendData(document.querySelector('input[name="rest-method"]:checked').value, document.getElementById("rest-url").value, document.getElementById("rest-headers").value, requestarea.value) } function restSendData(method, url, headers, data) { var XHR = new XMLHttpRequest(); XHR.addEventListener('error', function(event) { document.getElementById("restui-error").checked = true; }); XHR.onreadystatechange = function() { if (this.readyState == 4) { switch (this.status) { case 200: s = '200 - OK'; break; case 201: s = '201 - Created'; break; case 204: s = '204 - Updated'; break; case 400: s = '400 - Bad Request'; break; case 403: s = '403 - Forbidden'; break; case 404: s = '404 - Not Found'; break; case 405: s = '405 - Method Not Allowed'; break; case 409: s = '409 - Conflict'; break; } document.getElementById("rest-status").value = s; if (this.status == 200 || this.status == 201 || this.status == 204) { if (this.responseText.length > 0) { document.getElementById("rest-result-body").value = JSON.stringify(JSON.parse(this.responseText), null, 4); } if (method == "DELETE") { document.getElementById("rest-result-body").value = ""; connectToCSE(); } else { refreshNode() } } else { document.getElementById("rest-result-body").value = ""; } document.getElementById("rest-result-headers").value = this.getAllResponseHeaders() } }; XHR.open(method, url); var headerLines = headers.split("\n"); for (line of headerLines) { x = line.split(":") if (x.length == 2) { XHR.setRequestHeader(x[0], x[1]); } } // Add the required HTTP header for form data POST requests //XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // Finally, send our data. XHR.send(data); } // Callback and function to clear the status and rest resuld fields/areas. function restClearResult() { document.getElementById("rest-status").value = ''; document.getElementById("rest-result-headers").value = ''; document.getElementById("rest-result-body").value = ''; } // fill the header fields. Depending on the type and the currently selected // method this will change, for example, the Content-Type field. function fillHeaderArea(ty) { if (ty != null && currentRestRequestMethod == "POST") { text = "Content-Type: application/json;ty=" + ty + "\n" } else { text = "Content-Type: application/json\n" } text += "Accept: application/json\n" text += "X-M2M-Origin: " + document.getElementById("originator").value + "\n" text += "X-M2M-RI: " + Math.random().toString(36).slice(2) document.getElementById("rest-headers").value = text; } ///////////////////////////////////////////////////////////////////////////// tplAE = { "m2m:ae": { "acpi": [ "==> fill or remove <==" ], "api": "==> fill <==", "nl": "==> fill <==", "poa": [ "==> fill or remove <==" ], "rn": "==> fill <==", "rr": false } } tplACP = { "m2m:acp": { "pv": { "acr": { "acop": 63, "acor": [ "==> fill <==" ] } }, "pvs": { "acr": { "acop": 51, "acor": [ "==> fill <==" ] } }, "rn": "==> fill <==" } } tplContainer = { "m2m:cnt" : { "acpi": [ "==> fill or remove <==" ], "mbs": 10000, "mni": 10, "rn": "==> fill <==" } } tplContentInstance = { "m2m:cin": { "cnf": "text/plain:0", "con": "==> fill <==", "rn": "==> fill <==" } } tplGroup = { "m2m:grp": { "acpi": [ "==> fill or remove <==" ], "csy": 1, "gn": "==> fill <==", "mid": [ "==> Add members <==" ], "mnm": 10, "mt": 3, "rn": "==> fill <==" } } tplSubscription = { "m2m:sub": { "acpi": [ "==> fill or remove <==" ], "enc": { "net": [ 1, 2, 3, 4 ] }, "nu": [ "==> fill <==" ], "rn": "==> fill <==" } } tplFlexContainer = { "==> fill <==": { "acpi": [ "==> fill or remove <==" ], "cnd": "==> fill <==", "rn": "==> fill <==", "==> custom attributes <==": "==> fill <==" } } tplNode = { "m2m:nod": { "acpi": [ "==> fill or remove <==" ], "ni": "==> fill <==", "nid": "==> fill <==", "rn": "==> fill <==" } } tplAreaNwkDeviceInfo = { "m2m:andi": { "acpi": [ "==> fill or remove <==" ], "awi": "==> fill <==", "dc": "==> fill <==", "dvd": "==> fill <==", "dvt": "==> fill <==", "lnh": [ "==> fill <==" ], "mgd": 1005, "rn": "==> fill <==", "sld": 0, "sli": 0 } } tplAreaNwkType = { "m2m:ani": { "acpi": [ "==> fill or remove <==" ], "ant": "==> fill <==", "dc": "==> fill <==", "ldv": [ "==> fill <==" ], "mgd": 1004, "rn": "==> fill <==" } } tplBattery = { "m2m:bat": { "acpi": [ "==> fill or remove <==" ], "btl": 23, "bts": 7, "dc": "==> fill <==", "mgd": 1006, "rn": "==> fill <==" } } tplDeviceCapability = { "m2m:dvc": { "acpi": [ "==> fill or remove <==" ], "att": true, "can": "==> fill <==", "cas": { "acn": "==> fill <==", "sus": 1 }, "cus": true, "dc": "==> fill <==", "mgd": 1008, "rn": "==> fill <==" } } tplDeviceInfo = { "m2m:dvi": { "acpi": [ "==> fill or remove <==" ], "cnty": "==> fill <==", "dc": "==> fill <==", "dlb": [ "==> label:value <==" ], "dty": "==> fill <==", "dvnm": "==> fill <==", "fwv": "==> fill <==", "hwv": "==> fill <==", "loc": "==> fill <==", "man": "==> fill <==", "mfd": "==> fill timestamp <==", "mfdl": "==> fill <==", "mgd": 1007, "mod": "==> fill <==", "osv": "==> fill <==", "ptl": [ "==> fill <==" ], "purl": "==> fill <==", "rn": "==> fill <==", "smod": "==> fill <==", "spur": "==> fill <==", "swv": "==> fill <==", "syst": "==> fill timestamp <==" } } tplEventLog = { "m2m:evl": { "acpi": [ "==> fill or remove <==" ], "dc": "==> fill <==", "lga": false, "lgd": "==> fill <==", "lgo": false, "lgst": 1, "lgt": 0, "mgd": 1010, "rn": "==> fill <==" } } tplFirmware = { "m2m:fwr": { "acpi": [ "==> fill or remove <==" ], "dc": "==> fill <==", "fwn": "==> fill <==", "mgd": 1001, "rn": "==> fill <==", "ud": false, "uds": { "acn": "==> fill <==", "sus": 0 }, "url": "==> fill <==", "vr": "==> fill <==" } } tplMemory = { "m2m:mem": { "acpi": [ "==> fill or remove <==" ], "dc": "==> fill <==", "mgd": 1003, "mma": 0, "mmt": 0, "rn": "==> fill <==" } } tplReboot = { "m2m:rbo": { "acpi": [ "==> fill or remove <==" ], "dc": "==> fill <==", "far": false, "mgd": 1009, "rbo": false, "rn": "==> fill <==" } } tplSoftware = { "m2m:swr": { "acpi": [ "==> fill or remove <==" ], "act": false, "acts": { "acn": "==> fill <==", "sus": 0 }, "dc": "==> fill <==", "dea": false, "in": false, "ins": { "acn": "==> fill <==", "sus": 0 }, "mgd": 1002, "rn": "==> fill <==", "swn": "==> fill <==", "un": false, "url": "==> fill <==", "vr": "==> fill <==" } } var templates = ["", "", "", "", "", "", "", "", "", ""] var templateTypes = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] var templateButtons = [null, null, null, null, null, null, null, null, null, null] function fillTemplate(nr) { requestarea.value = templates[nr] fillHeaderArea(templateTypes[nr]) } function fillRequestArea() { templateButtons[0] = document.getElementById("tplButton0") templateButtons[1] = document.getElementById("tplButton1") templateButtons[2] = document.getElementById("tplButton2") templateButtons[3] = document.getElementById("tplButton3") templateButtons[4] = document.getElementById("tplButton4") templateButtons[5] = document.getElementById("tplButton5") templateButtons[6] = document.getElementById("tplButton6") templateButtons[7] = document.getElementById("tplButton7") templateButtons[8] = document.getElementById("tplButton8") templateButtons[9] = document.getElementById("tplButton9") templateButtons[10] = document.getElementById("tplButton10") // enable / disable the area depending on the currently selected method if (currentRestRequestMethod == "POST" || currentRestRequestMethod == "PUT") { requestarea.readOnly = false; requestbody.style.display = 'block'; } else { requestarea.readOnly = true; requestbody.style.display = 'none'; } if (currentRestRequestMethod == "DELETE") { sendButton.className = "error" } else { sendButton.className = "button success" } // hide buttons and fill with resource for PUT if (currentRestRequestMethod == "GET" || currentRestRequestMethod == "DELETE") { hideTemplateButtons() return } else if (currentRestRequestMethod == "PUT") { hideTemplateButtons() requestarea.value = JSON.stringify(prepareNodeForPUT(currentResource, currentResourceType), null, 4) return } // only POST from here // add templates and buttons requestarea.value = "" hideTemplateButtons() if (currentResourceType == "m2m:ae") { // AE showTemplateButton(0, "Container", tplContainer, 3) showTemplateButton(1, "FlexContainer", tplFlexContainer, 28) showTemplateButton(2, "Group", tplGroup, 9) showTemplateButton(3, "Subscription", tplSubscription, 23) } else if (currentResourceType == "m2m:cnt") { // Container showTemplateButton(0, "Container", tplContainer, 3) showTemplateButton(1, "ContentInstance", tplContentInstance, 4) showTemplateButton(2, "Subscription", tplSubscription, 23) } else if (currentResourceType == "m2m:cb") { // CSEBase showTemplateButton(0, "ACP", tplACP, 1) showTemplateButton(1, "AE", tplAE, 2) showTemplateButton(2, "Container", tplContainer, 3) showTemplateButton(3, "FlexContainer", tplFlexContainer, 28) showTemplateButton(4, "Group", tplGroup, 9) showTemplateButton(5, "Node", tplNode, 14) showTemplateButton(6, "Subscription", tplSubscription, 23) } else if (currentResourceType == "m2m:nod") { // Node showTemplateButton(0, "AreaNwkDeviceInfo", tplAreaNwkDeviceInfo, 13) showTemplateButton(1, "AreaNwkType", tplAreaNwkType, 13) showTemplateButton(2, "Battery", tplBattery, 13) showTemplateButton(3, "Firmware", tplFirmware, 13) showTemplateButton(4, "DeviceCapability", tplDeviceCapability, 13) showTemplateButton(5, "DeviceInfo", tplDeviceInfo, 13) showTemplateButton(6, "EventLog", tplEventLog, 13) showTemplateButton(7, "Memory", tplMemory, 13) showTemplateButton(8, "Reboot", tplReboot, 13) showTemplateButton(9, "Software", tplSoftware, 13) showTemplateButton(10, "Subscription", tplSubscription, 23) } else if (currentResourceType == "m2m:grp") { // Group showTemplateButton(0, "Subscription", tplSubscription, 23) } else if (currentResource.ty == 28) { // FlexContainer showTemplateButton(0, "Container", tplContainer, 3) showTemplateButton(1, "FlexContainer", tplFlexContainer, 28) showTemplateButton(2, "Subscription", tplSubscription, 23) } else if (currentResource.ty == 13) { // FlexContainer showTemplateButton(0, "Subscription", tplSubscription, 23) } } function hideTemplateButtons() { for (b in templateButtons) { templateButtons[b].style.display = "none" } for (var i = templateTypes.length - 1; i >= 0; i--) { templateTypes[i] = 0 } } function showTemplateButton(idx, text, template, ty) { templateButtons[idx].text = text templateButtons[idx].style.display = 'inline-block' templates[idx] = JSON.stringify(template, null, 4) templateTypes[idx] = ty } function prepareNodeForPUT(resource, tpe) { let r = Object.assign({}, resource); delete r["ct"] delete r["lt"] delete r["ri"] delete r["pi"] delete r["rn"] delete r["st"] delete r["ty"] delete r["cbs"] delete r["cni"] delete r["acpi"] delete r["mgd"] delete r["srt"] delete r["csi"] let result = {} result[tpe] = r return result }
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/webui/js/restui.js
restui.js
function ContextMenu(menu, options){ var self = this; var num = ContextMenu.count++; this.menu = menu; this.contextTarget = null; if(!(menu instanceof Array)){ throw new Error("Parameter 1 must be of type Array"); } if(typeof options !== "undefined"){ if(typeof options !== "object"){ throw new Error("Parameter 2 must be of type object"); } }else{ options = {}; } window.addEventListener("resize", function(){ if(ContextUtil.getProperty(options, "close_on_resize", true)){ self.hide(); } }); this.setOptions = function(_options){ if(typeof _options === "object"){ options = _options; }else{ throw new Error("Parameter 1 must be of type object") } } this.changeOption = function(option, value){ if(typeof option === "string"){ if(typeof value !== "undefined"){ options[option] = value; }else{ throw new Error("Parameter 2 must be set"); } }else{ throw new Error("Parameter 1 must be of type string"); } } this.getOptions = function(){ return options; } this.reload = function(){ if(document.getElementById('cm_' + num) == null){ var cnt = document.createElement("div"); cnt.className = "cm_container"; cnt.id = "cm_" + num; document.body.appendChild(cnt); } var container = document.getElementById('cm_' + num); container.innerHTML = ""; container.appendChild(renderLevel(menu)); } function renderLevel(level){ var ul_outer = document.createElement("ul"); level.forEach(function(item){ var li = document.createElement("li"); li.menu = self; if(typeof item.type === "undefined"){ var icon_span = document.createElement("span"); icon_span.className = 'cm_icon_span'; if(ContextUtil.getProperty(item, "icon", "") != ""){ icon_span.innerHTML = ContextUtil.getProperty(item, "icon", ""); }else{ icon_span.innerHTML = ContextUtil.getProperty(options, "default_icon", ""); } var text_span = document.createElement("span"); text_span.className = 'cm_text'; if(ContextUtil.getProperty(item, "text", "") != ""){ text_span.innerHTML = ContextUtil.getProperty(item, "text", ""); }else{ text_span.innerHTML = ContextUtil.getProperty(options, "default_text", "item"); } var sub_span = document.createElement("span"); sub_span.className = 'cm_sub_span'; if(typeof item.sub !== "undefined"){ if(ContextUtil.getProperty(options, "sub_icon", "") != ""){ sub_span.innerHTML = ContextUtil.getProperty(options, "sub_icon", ""); }else{ sub_span.innerHTML = '&#155;'; } } li.appendChild(icon_span); li.appendChild(text_span); li.appendChild(sub_span); if(!ContextUtil.getProperty(item, "enabled", true)){ li.setAttribute("disabled", ""); }else{ if(typeof item.events === "object"){ var keys = Object.keys(item.events); for(var i = 0; i < keys.length; i++){ li.addEventListener(keys[i], item.events[keys[i]]); } } if(typeof item.sub !== "undefined"){ li.appendChild(renderLevel(item.sub)); } } }else{ if(item.type == ContextMenu.DIVIDER){ li.className = "cm_divider"; } } ul_outer.appendChild(li); }); return ul_outer; } this.display = function(e, target){ if(typeof target !== "undefined"){ self.contextTarget = target; }else{ self.contextTarget = e.target; } var menu = document.getElementById('cm_' + num); var clickCoords = {x: e.clientX, y: e.clientY}; var clickCoordsX = clickCoords.x; var clickCoordsY = clickCoords.y; var menuWidth = menu.offsetWidth + 4; var menuHeight = menu.offsetHeight + 4; var windowWidth = window.innerWidth; var windowHeight = window.innerHeight; var mouseOffset = parseInt(ContextUtil.getProperty(options, "mouse_offset", 2)); if((windowWidth - clickCoordsX) < menuWidth){ menu.style.left = windowWidth - menuWidth + "px"; }else{ menu.style.left = (clickCoordsX + mouseOffset) + "px"; } if((windowHeight - clickCoordsY) < menuHeight){ menu.style.top = windowHeight - menuHeight + "px"; }else{ menu.style.top = (clickCoordsY + mouseOffset) + "px"; } var sizes = ContextUtil.getSizes(menu); if((windowWidth - clickCoordsX) < sizes.width){ menu.classList.add("cm_border_right"); }else{ menu.classList.remove("cm_border_right"); } if((windowHeight - clickCoordsY) < sizes.height){ menu.classList.add("cm_border_bottom"); }else{ menu.classList.remove("cm_border_bottom"); } menu.classList.add("display"); if(ContextUtil.getProperty(options, "close_on_click", true)){ window.addEventListener("click", documentClick); } e.preventDefault(); } this.hide = function(){ document.getElementById('cm_' + num).classList.remove("display"); window.removeEventListener("click", documentClick); } function documentClick(){ self.hide(); } this.reload(); } ContextMenu.count = 0; ContextMenu.DIVIDER = "cm_divider"; const ContextUtil = { getProperty: function(options, opt, def){ if(typeof options[opt] !== "undefined"){ return options[opt]; }else{ return def; } }, getSizes: function(obj){ var lis = obj.getElementsByTagName('li'); var width_def = 0; var height_def = 0; for(var i = 0; i < lis.length; i++){ var li = lis[i]; if(li.offsetWidth > width_def){ width_def = li.offsetWidth; } if(li.offsetHeight > height_def){ height_def = li.offsetHeight; } } var width = width_def; var height = height_def; for(var i = 0; i < lis.length; i++){ var li = lis[i]; var ul = li.getElementsByTagName('ul'); if(typeof ul[0] !== "undefined"){ var ul_size = ContextUtil.getSizes(ul[0]); if(width_def + ul_size.width > width){ width = width_def + ul_size.width; } if(height_def + ul_size.height > height){ height = height_def + ul_size.height; } } } return { "width": width, "height": height }; } };
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/webui/js/contextmenu.js
contextmenu.js
// // shortnames.js // // (c) 2020 by Andreas Kraft // License: BSD 3-Clause License. See the LICENSE file for further details. // // Mapping between oneM2M short and long names // // There are basically 4 types of attributes: // - common & universal : same as oneM2M // - custom : from flexContainer and mgmtObj specializations // - all others const shortNames = { "aa" : { "ln" : "announcedAttribute", "type" : "common" }, "acn" : { "ln" : "action", "type": "" }, "act" : { "ln" : "activate", "type": "" }, "acts" : { "ln" : "activeStatus", "type": "" }, "acpi" : { "ln" : "accessControlPolicyIDs", "type": "common" }, "acn" : { "ln" : "action", "type": "" }, "aei" : { "ln" : "AE-ID", "type": "" }, "ant" : { "ln" : "areaNwkType", "type": "custom" }, "ape" : { "ln" : "activityPatternElements", "type": "" }, "api" : { "ln" : "App-ID", "type": "" }, "apn" : { "ln" : "AppName", "type": "" }, "at" : { "ln" : "announcedTo", "type" : "common" }, "att" : { "ln" : "attached", "type": "custom" }, "awi" : { "ln" : "areaNwkId", "type": "custom" }, "btl" : { "ln" : "batteryLevel", "type": "custom" }, "bts" : { "ln" : "batteryStatus", "type": "custom" }, "can" : { "ln" : "capabilityName", "type": "custom" }, "cas" : { "ln" : "capabilityActionStatus", "type": "custom" }, "cbs" : { "ln" : "currentByteSize", "type": "" }, "cnd" : { "ln" : "containerDefinition", "type": "" }, "cnf" : { "ln" : "contentInfo", "type": "custom" }, "cni" : { "ln" : "currentNrOfInstances", "type": "" }, "cnm" : { "ln" : "currentNrOfMembers", "type": "" }, "cnty" : { "ln" : "country", "type": "custom" }, "con" : { "ln" : "content", "type": "custom" }, "cr" : { "ln" : "creator", "type": "common" }, "cs" : { "ln" : "contentSize", "type": "" }, "csi" : { "ln" : "CSE-ID", "type": "" }, "cst" : { "ln" : "cseType", "type": "" }, "csy" : { "ln" : "consistencyStrategy", "type": "" }, "csz" : { "ln" : "contentSerialization", "type": "" }, "ct" : { "ln" : "creationTime", "type": "universal" }, "cus" : { "ln" : "currentState", "type": "custom" }, "daci" : { "ln" : "dynamicAuthorizationConsultationIDs", "type": "common" }, "dc" : { "ln" : "description", "type": "" }, "dea" : { "ln" : "deactivate", "type": "" }, "dis" : { "ln" : "disable", "type": "" }, "dlb" : { "ln" : "deviceLabel", "type": "custom" }, "dty" : { "ln" : "deviceType", "type": "custom" }, "dvd" : { "ln" : "devId", "type": "custo" }, "dvi" : { "ln" : "deviceInfo", "type": "" }, "dvnm" : { "ln" : "deviceName", "type": "custom" }, "dvt" : { "ln" : "devType", "type": "custom" }, "egid" : { "ln" : "externalGroupID", "type": "" }, "ena" : { "ln" : "enable", "type": "" }, "enc" : { "ln" : "eventNotificationCriteria", "type": "" }, "esi" : { "ln" : "e2eSecInfo", "type": "common" }, "et" : { "ln" : "expirationTime", "type": "common" }, "far" : { "ln" : "factoryReset", "type": "" }, "fwn" : { "ln" : "firmwareName", "type": "custom" }, "fwv" : { "ln" : "fwVersion", "type": "custom" }, "gn" : { "ln" : "groupName", "type": "" }, "hael" : { "ln" : "hostedAELinks", "type": "" }, "hcl" : { "ln" : "hostedCSELink", "type": "" }, "hsl" : { "ln" : "hostedServiceLink", "type": "" }, "hwv" : { "ln" : "hwVersion", "type": "custom" }, "in" : { "ln" : "install", "type": "" }, "ins" : { "ln" : "installStatus", "type": "" }, "lbl" : { "ln" : "labels", "type": "common" }, "ldv" : { "ln" : "listOfDevices", "type": "custom" }, "lga" : { "ln" : "logStart", "type": "custom" }, "lgd" : { "ln" : "logData", "type": "custom" }, "lgo" : { "ln" : "logStop", "type": "custom" }, "lgst" : { "ln" : "logStatus", "type": "custom" }, "lgt" : { "ln" : "logTypeId", "type": "custom" }, "lnh" : { "ln" : "listOfNeighbors", "type": "custom" }, "loc" : { "ln" : "location", "type": "custom" }, "lt" : { "ln" : "lastModifiedTime", "type": "universal" }, "macp" : { "ln" : "membersAccessControlPolicyIDs", "type": "" }, "man" : { "ln" : "manufacturer", "type": "custom" }, "mbs" : { "ln" : "maxByteSize", "type": "" }, "mei" : { "ln" : "M2M-Ext-ID", "type": "" }, "mfd" : { "ln" : "manufacturingDate", "type": "custom" }, "mfdl" : { "ln" : "manufacturerDetailsLink", "type": "custom" }, "mgca" : { "ln" : "mgmtClientAddress", "type": "" }, "mgd" : { "ln" : "mgmtDefinition", "type": "" }, "mid" : { "ln" : "memberIDs", "type": "" }, "mma" : { "ln" : "memAvailable", "type": "custom" }, "mmt" : { "ln" : "memTotal", "type": "custom" }, "mni" : { "ln" : "maxNrOfInstances", "type": "" }, "mnm" : { "ln" : "maxNrOfMembers", "type": "" }, "mod" : { "ln" : "model", "type": "custom" }, "mt" : { "ln" : "memberType", "type": "" }, "mtv" : { "ln" : "memberTypeValidated", "type": "" }, "nar" : { "ln" : "notifyAggregation", "type": "" }, "nct" : { "ln" : "notificationContentType", "type": "" }, "ni" : { "ln" : "nodeID", "type": "" }, "nid" : { "ln" : "networkID", "type": "" }, "nl" : { "ln" : "nodeLink", "type": "" }, "nu" : { "ln" : "notificationURI", "type": "" }, "or" : { "ln" : "ontologyRef", "type" : "" }, "osv" : { "ln" : "osVersion", "type": "custom" }, "pi" : { "ln" : "parentID", "type": "universal" }, "poa" : { "ln" : "pointOfAccess", "type": "" }, "ptl" : { "ln" : "protocol", "type": "custom" }, "purl" : { "ln" : "presentationURL", "type": "custom" }, "pv" : { "ln" : "privileges", "type": "" }, "pvs" : { "ln" : "selfPrivileges", "type": "" }, "rbo" : { "ln" : "reboot", "type": "" }, "regs" : { "ln" : "registrationStatus", "type": "" }, "ri" : { "ln" : "resourceID", "type": "universal" }, "rms" : { "ln" : "roamingStatus", "type": "" }, "rn" : { "ln" : "resourceName", "type": "universal" }, "rr" : { "ln" : "requestReachability", "type": "" }, "scp" : { "ln" : "sessionCapabilities", "type": "" }, "sld" : { "ln" : "sleepDuration", "type": "custom" }, "sli" : { "ln" : "sleepInterval", "type": "custom" }, "smod" : { "ln" : "subModel", "type": "custom" }, "spty" : { "ln" : "specializationType", "type": "" }, "spur" : { "ln" : "supportURL", "type": "custom" }, "srt" : { "ln" : "supportedResourceType", "type": "" }, "srv" : { "ln" : "supportedReleaseVersions", "type": "" }, "ssi" : { "ln" : "semanticSupportIndicator", "type": "" }, "st" : { "ln" : "stateTag", "type": "common" }, "sus" : { "ln" : "status", "type": "" }, "swn" : { "ln" : "softwareName", "type": "" }, "swr" : { "ln" : "software", "type": "" }, "swv" : { "ln" : "swVersion", "type": "custom" }, "syst" : { "ln" : "systemTime", "type": "custom" }, "tri" : { "ln" : "trigger-Recipient-ID", "type": "" }, "tren" : { "ln" : "triggerEnable", "type": "" }, "trn" : { "ln" : "triggerReferenceNumber", "type": "" }, "trps" : { "ln" : "trackRegistrationPoints", "type": "" }, "ty" : { "ln" : "resourceType", "type": "universal" }, "ud" : { "ln" : "update", "type": "" }, "uds" : { "ln" : "updateStatus", "type": "" }, "un" : { "ln" : "uninstall", "type": "" }, "url" : { "ln" : "URL", "type": "custom" }, "vr" : { "ln" : "version", "type": "custom" }, // proprietary custom attributes "crRes" : { "ln" : "createdResources", "type": "custom" }, "cseSU" : { "ln" : "cseStartUpTime", "type": "custom" }, "cseUT" : { "ln" : "cseUptime", "type": "custom" }, "ctRes" : { "ln" : "resourceCount", "type": "custom" }, "htCre" : { "ln" : "httpCreates", "type": "custom" }, "htDel" : { "ln" : "httpDeletes", "type": "custom" }, "htRet" : { "ln" : "httpRetrieves", "type": "custom" }, "htUpd" : { "ln" : "httpUpdates", "type": "custom" }, "lgErr" : { "ln" : "logErrors", "type": "custom" }, "lgWrn" : { "ln" : "logWarnings", "type": "custom" }, "rmRes" : { "ln" : "deletedResources", "type": "custom" } } function shortToLongname(sn) { if (printLongNames && sn in shortNames) { return shortNames[sn].ln } return sn } function attributeRole(sn) { if (sn in shortNames) { return shortNames[sn].type } return "custom" }
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/webui/js/attributes.js
attributes.js
// // resourceTree.js // // (c) 2020 by Andreas Kraft // License: BSD 3-Clause License. See the LICENSE file for further details. // // Javascript tree handling methods // var tree var cseid = '' var root = null var rootri = null var originator = "" var printLongNames = false var nodeClicked = undefined // hack: if this is set to false then the REST UI will not be refreshed. // useful with auto refresh. var refreshRESTUI = true // TODO Clickable references. For each node add ("ri" : TreePath). expand via TreeView.expandPath. // Select the entry and display const types = { 1 : "ACP", 2 : "AE", 3 : "Container", 4 : "ContentInstance", 5 : "CSEBase", 9 : "Group", 14 : "Node", 16 : "RemoteCSE", 23 : "Subscription", 28 : "FlexContainer", 52 : "FlexContainerInstance" } const shortTypes = { 1 : "ACP", 2 : "AE", 3 : "CNT", 4 : "CIN", 5 : "CSE", 9 : "GRP", 14 : "NOD", 16 : "CSR", 23 : "SUB", 28 : "FCNT", 52 : "FCI" } const mgdTypes = { 1001 : "Firmware", 1002 : "Software", 1003 : "Memory", 1004 : "AreaNwkInfo", 1005 : "AreaNwkDeviceInfo", 1006 : "Battery", 1007 : "DeviceInfo", 1008 : "DeviceCapability", 1009 : "Reboot", 1010 : "EventLog" } const mgdShortTypes = { 1001 : "FWR", 1002 : "SWR", 1003 : "MEM", 1004 : "ANI", 1005 : "ANDI", 1006 : "BAT", 1007 : "DVI", 1008 : "DVC", 1009 : "REB", 1010 : "EVL" } function clickOnNode(e, node) { if (typeof nodeClicked !== "undefined") { nodeClicked.setSelected(false) } node.setSelected(true) nodeClicked = node tree.reload() resource = node.resource clearAttributesTable() fillAttributesTable(resource) fillJSONArea(node) setResourceInfo(resource) if (refreshRESTUI) { setRestUI(node.resourceFull) } else { refreshRESTUI = true } } ////////////////////////////////////////////////////////////////////////////// // // Tree handling // function expandNode(node) { for (ch of node.getChildren()) { if (ch.resolved == false) { getResource(ch.ri, ch) } } } function collapseNode(node) { for (ch of node.getChildren()) { ch.setExpanded(false) } } function removeChildren(node) { var chc = node.getChildCount() for (i = 0; i < chc; i++) { node.removeChildPos(0) } } function clearAttributesTable() { var table = document.getElementById("details"); var tb = table.getElementsByTagName('tbody')[0] tb.innerHTML = "&nbsp;" } function fillAttributesTable(resource) { // fill attribute table with resource attributes var table = document.getElementById("details"); var tb = table.getElementsByTagName('tbody')[0] for (var key in resource) { var newRow = tb.insertRow() var keyCell = newRow.insertCell(0) var valueCell = newRow.insertCell(1); // Colorful attributes switch (attributeRole(key)) { case "universal": keyCell.innerHTML = "<font color=\"#e67e00\">" + shortToLongname(key) + "</font>"; break; case "common": keyCell.innerHTML = "<font color=\"#0040ff\">" + shortToLongname(key) + "</font>"; break; case "custom": keyCell.innerHTML = "<font color=\"#239023\">" + shortToLongname(key) + "</font>"; break; default: keyCell.innerHTML = "<font color=\"black\">" + shortToLongname(key) + "</font>"; break; } valueCell.innerText = JSON.stringify(resource[key]) } } function fillJSONArea(node) { // fill JSON text area document.getElementById("resource").value = JSON.stringify(node.resourceFull, null, 4) } function clearJSONArea() { // fill JSON text area document.getElementById("resource").value = "" } function setRootResourceName(name) { document.getElementById("rootResourceName").innerText = name } function clearRootResourceName() { document.getElementById("rootResourceName").innerHTML = "&nbsp;" } function setResourceInfo(resource) { if (typeof resource === "undefined") { return } // extra infos in the header var d = document.getElementById("resourceType"); var ty = resource['ty'] var t = types[ty] if (ty == 13) { var mgd = resource['mgd'] if (mgd == undefined) { t = "mgmtObj" } else { t = mgdTypes[mgd] } } if (t == undefined) { t = "Unknown" } var ri = "/" + resource["ri"] if (ri == cseid) { d.innerText = t + ": " + cseid } else { d.innerText = t + ": " + cseid + "/" + resource["ri"] } } function clearResourceInfo() { document.getElementById("resourceType").innerHTML = "&nbsp;" } function refreshNode() { if (typeof nodeClicked !== "undefined") { nodeClicked.wasExpanded = nodeClicked.isExpanded() removeChildren(nodeClicked) getResource(nodeClicked.resource.ri, nodeClicked) } } ////////////////////////////////////////////////////////////////////////////// // // Utilities // function getUrlParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); } ////////////////////////////////////////////////////////////////////////////// // // Refresh // var refreshTimer = undefined function setupRefreshResource(seconds) { refreshTimer = setInterval(function() { refreshRESTUI = false refreshNode() }, seconds*1000) } function cancelRefreshResource() { clearInterval(refreshTimer); refreshTimer = undefined }
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/webui/js/resourceTree.js
resourceTree.js
/** * TreeJS is a JavaScript librarie for displaying TreeViews * on the web. * * @author Matthias Thalmann */ function TreeView(root, container, options){ var self = this; /* * Konstruktor */ if(typeof root === "undefined"){ throw new Error("Parameter 1 must be set (root)"); } if(!(root instanceof TreeNode)){ throw new Error("Parameter 1 must be of type TreeNode"); } if(container){ if(!TreeUtil.isDOM(container)){ container = document.querySelector(container); if(container instanceof Array){ container = container[0]; } if(!TreeUtil.isDOM(container)){ throw new Error("Parameter 2 must be either DOM-Object or CSS-QuerySelector (#, .)"); } } }else{ container = null; } if(!options || typeof options !== "object"){ options = {}; } /* * Methods */ this.setRoot = function(_root){ if(root instanceof TreeNode){ root = _root; } } this.getRoot = function(){ return root; } this.expandAllNodes = function(){ root.setExpanded(true); root.getChildren().forEach(function(child){ TreeUtil.expandNode(child); }); } this.expandPath = function(path){ if(!(path instanceof TreePath)){ throw new Error("Parameter 1 must be of type TreePath"); } path.getPath().forEach(function(node){ node.setExpanded(true); }); } this.collapseAllNodes = function(){ root.setExpanded(false); root.getChildren().forEach(function(child){ TreeUtil.collapseNode(child); }); } this.setContainer = function(_container){ if(TreeUtil.isDOM(_container)){ container = _container; }else{ _container = document.querySelector(_container); if(_container instanceof Array){ _container = _container[0]; } if(!TreeUtil.isDOM(_container)){ throw new Error("Parameter 1 must be either DOM-Object or CSS-QuerySelector (#, .)"); } } } this.getContainer = function(){ return container; } this.setOptions = function(_options){ if(typeof _options === "object"){ options = _options; } } this.changeOption = function(option, value){ options[option] = value; } this.getOptions = function(){ return options; } // T ODO: set selected key: up down; expand right; collapse left; enter: open; this.getSelectedNodes = function(){ return TreeUtil.getSelectedNodesForNode(root); } this.reload = function(){ if(container == null){ console.warn("No container specified"); return; } container.classList.add("tj_container"); var cnt = document.createElement("ul"); cnt.appendChild(renderNode(root)); container.innerHTML = ""; container.appendChild(cnt); } function renderNode(node){ var li_outer = document.createElement("li"); var span_desc = document.createElement("span"); span_desc.className = "tj_description"; span_desc.tj_node = node; if(!node.isEnabled()){ li_outer.setAttribute("disabled", ""); node.setExpanded(false); node.setSelected(false); } if(node.isSelected()){ span_desc.classList.add("selected"); } span_desc.addEventListener("click", function(e){ var cur_el = e.target; clickRelative = e.clientX - getOffset(this).left // akr while(typeof cur_el.tj_node === "undefined" || cur_el.classList.contains("tj_container")){ cur_el = cur_el.parentElement; } var node_cur = cur_el.tj_node; if(typeof node_cur === "undefined"){ return; } if(node_cur.isEnabled()){ if(e.ctrlKey == false){ if(!node_cur.isLeaf()){ if (clickRelative < 27) { // akr start node_cur.toggleExpanded(); } else if (!node_cur.isExpanded()) { node_cur.setExpanded(true) } // akr end self.reload(); }else{ node_cur.open(); } node_cur.on("click")(e, node_cur); } if(e.ctrlKey == true){ node_cur.toggleSelected(); self.reload(); }else{ var rt = node_cur.getRoot(); if(rt instanceof TreeNode){ TreeUtil.getSelectedNodesForNode(rt).forEach(function(_nd){ _nd.setSelected(false); }); } node_cur.setSelected(true); self.reload(); } } }); span_desc.addEventListener("contextmenu", function(e){ var cur_el = e.target; while(typeof cur_el.tj_node === "undefined" || cur_el.classList.contains("tj_container")){ cur_el = cur_el.parentElement; } var node_cur = cur_el.tj_node; if(typeof node_cur === "undefined"){ return; } if(typeof node_cur.getListener("contextmenu") !== "undefined"){ node_cur.on("contextmenu")(e, node_cur); e.preventDefault(); }else if(typeof TreeConfig.context_menu === "function"){ TreeConfig.context_menu(e, node_cur); e.preventDefault(); } }); if(node.isLeaf()){ var ret = ''; var icon = TreeUtil.getProperty(node.getOptions(), "icon", ""); if(icon != ""){ ret += '<span class="tj_icon">' + icon + '</span>'; }else if((icon = TreeUtil.getProperty(options, "leaf_icon", "")) != ""){ ret += '<span class="tj_icon">' + icon + '</span>'; }else{ ret += '<span class="tj_icon">' + TreeConfig.leaf_icon + '</span>'; } span_desc.innerHTML = ret + node.toString() + "</span>"; span_desc.classList.add("tj_leaf"); li_outer.appendChild(span_desc); }else{ var ret = ''; if(node.isExpanded()){ ret += '<span class="tj_mod_icon">' + TreeConfig.open_icon + '</span>'; }else{ ret += '<span class="tj_mod_icon">' + TreeConfig.close_icon + '</span>'; } // var icon = TreeUtil.getProperty(node.getOptions(), "icon", ""); // if(icon != ""){ // ret += '<span class="tj_icon">' + icon + '</span>'; // }else if((icon = TreeUtil.getProperty(options, "parent_icon", "")) != ""){ // ret += '<span class="tj_icon">' + icon + '</span>'; // }else{ // ret += '<span class="tj_icon">' + TreeConfig.parent_icon + '</span>'; // } span_desc.innerHTML = ret + node.toString() + '</span>'; li_outer.appendChild(span_desc); if(node.isExpanded()){ var ul_container = document.createElement("ul"); node.getChildren().forEach(function(child){ ul_container.appendChild(renderNode(child)); }); li_outer.appendChild(ul_container) } } return li_outer; } if(typeof container !== "undefined") this.reload(); } function TreeNode(userObject, options){ var children = new Array(); var self = this; var events = new Array(); var expanded = true; var enabled = true; var selected = false; /* * Konstruktor */ if(userObject){ if(!(typeof userObject === "string") || typeof userObject.toString !== "function"){ throw new Error("Parameter 1 must be of type String or Object, where it must have the function toString()"); } }else{ userObject = ""; } if(!options || typeof options !== "object"){ options = {}; }else{ expanded = TreeUtil.getProperty(options, "expanded", true); enabled = TreeUtil.getProperty(options, "enabled", true); selected = TreeUtil.getProperty(options, "selected", false); } /* * Methods */ this.addChild = function(node){ if(!TreeUtil.getProperty(options, "allowsChildren", true)){ console.warn("Option allowsChildren is set to false, no child added"); return; } if(node instanceof TreeNode){ children.push(node); //Konstante hinzufügen (workaround) Object.defineProperty(node, "parent", { value: this, writable: false, enumerable: true, configurable: true }); }else{ throw new Error("Parameter 1 must be of type TreeNode"); } } this.removeChildPos = function(pos){ if(typeof children[pos] !== "undefined"){ if(typeof children[pos] !== "undefined"){ children.splice(pos, 1); } } } this.removeChild = function(node){ if(!(node instanceof TreeNode)){ throw new Error("Parameter 1 must be of type TreeNode"); } this.removeChildPos(this.getIndexOfChild(node)); } this.getChildren = function(){ return children; } this.getChildCount = function(){ return children.length; } this.getIndexOfChild = function(node){ for(var i = 0; i < children.length; i++){ if(children[i].equals(node)){ return i; } } return -1; } this.getRoot = function(){ var node = this; while(typeof node.parent !== "undefined"){ node = node.parent; } return node; } this.setUserObject = function(_userObject){ if(!(typeof _userObject === "string") || typeof _userObject.toString !== "function"){ throw new Error("Parameter 1 must be of type String or Object, where it must have the function toString()"); }else{ userObject = _userObject; } } this.getUserObject = function(){ return userObject; } this.setOptions = function(_options){ if(typeof _options === "object"){ options = _options; } } this.changeOption = function(option, value){ options[option] = value; } this.getOptions = function(){ return options; } this.isLeaf = function(){ return (children.length == 0); } this.setExpanded = function(_expanded){ if(this.isLeaf()){ return; } if(typeof _expanded === "boolean"){ if(expanded == _expanded){ return; } expanded = _expanded; if(_expanded){ this.on("expand")(this); }else{ this.on("collapse")(this); } this.on("toggle_expanded")(this); } } this.toggleExpanded = function(){ if(expanded){ this.setExpanded(false); }else{ this.setExpanded(true); } }; this.isExpanded = function(){ if(this.isLeaf()){ return true; }else{ return expanded; } } this.setEnabled = function(_enabled){ if(typeof _enabled === "boolean"){ if(enabled == _enabled){ return; } enabled = _enabled; if(_enabled){ this.on("enable")(this); }else{ this.on("disable")(this); } this.on("toggle_enabled")(this); } } this.toggleEnabled = function(){ if(enabled){ this.setEnabled(false); }else{ this.setEnabled(true); } } this.isEnabled = function(){ return enabled; } this.setSelected = function(_selected){ if(typeof _selected !== "boolean"){ return; } if(selected == _selected){ return; } selected = _selected; if(_selected){ this.on("select")(this); }else{ this.on("deselect")(this); } this.on("toggle_selected")(this); } this.toggleSelected = function(){ if(selected){ this.setSelected(false); }else{ this.setSelected(true); } } this.isSelected = function(){ return selected; } this.open = function(){ if(!this.isLeaf()){ this.on("open")(this); } } this.on = function(ev, callback){ if(typeof callback === "undefined"){ if(typeof events[ev] !== "function"){ return function(){}; }else{ return events[ev]; } } if(typeof callback !== 'function'){ throw new Error("Argument 2 must be of type function"); } events[ev] = callback; } this.getListener = function(ev){ return events[ev]; } this.equals = function(node){ if(node instanceof TreeNode){ if(node.getUserObject() == userObject){ return true; } } return false; } this.toString = function(){ if(typeof userObject === "string"){ return userObject; }else{ return userObject.toString(); } } } function TreePath(root, node){ var nodes = new Array(); this.setPath = function(root, node){ nodes = new Array(); while(typeof node !== "undefined" && !node.equals(root)){ nodes.push(node); node = node.parent; } if(node.equals(root)){ nodes.push(root); }else{ nodes = new Array(); throw new Error("Node is not contained in the tree of root"); } nodes = nodes.reverse(); return nodes; } this.getPath = function(){ return nodes; } this.toString = function(){ return nodes.join(" - "); } if(root instanceof TreeNode && node instanceof TreeNode){ this.setPath(root, node); } } /* * Util-Methods */ const TreeUtil = { // default_leaf_icon: "<span>&#128441;</span>", // default_parent_icon: "<span>&#128449;</span>", // default_open_icon: "<span>&#9698;</span>", // default_close_icon: "<span>&#9654;</span>", // default_leaf_icon: "<span>&#9655;</span>", default_leaf_icon: "<span>&#9649;</span>", default_parent_icon: "<span></span>", default_open_icon: "<span>&#9660;</span>", default_close_icon: "<span>&#9654;</span>", isDOM: function(obj){ try { return obj instanceof HTMLElement; } catch(e){ return (typeof obj==="object") && (obj.nodeType===1) && (typeof obj.style === "object") && (typeof obj.ownerDocument ==="object"); } }, getProperty: function(options, opt, def){ if(typeof options[opt] === "undefined"){ return def; } return options[opt]; }, expandNode: function(node){ node.setExpanded(true); if(!node.isLeaf()){ node.getChildren().forEach(function(child){ TreeUtil.expandNode(child); }); } }, collapseNode: function(node){ node.setExpanded(false); if(!node.isLeaf()){ node.getChildren().forEach(function(child){ TreeUtil.collapseNode(child); }); } }, getSelectedNodesForNode: function(node){ if(!(node instanceof TreeNode)){ throw new Error("Parameter 1 must be of type TreeNode"); } var ret = new Array(); if(node.isSelected()){ ret.push(node); } node.getChildren().forEach(function(child){ if(child.isSelected()){ if(ret.indexOf(child) == -1){ ret.push(child); } } if(!child.isLeaf()){ TreeUtil.getSelectedNodesForNode(child).forEach(function(_node){ if(ret.indexOf(_node) == -1){ ret.push(_node); } }); } }); return ret; } }; var TreeConfig = { leaf_icon: TreeUtil.default_leaf_icon, parent_icon: TreeUtil.default_parent_icon, open_icon: TreeUtil.default_open_icon, close_icon: TreeUtil.default_close_icon, context_menu: undefined }; function getOffset(el) { const rect = el.getBoundingClientRect(); return { left: rect.left + window.scrollX, top: rect.top + window.scrollY }; }
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/webui/js/tree.js
tree.js
# # EventManager.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Managing event handlers and events # import threading from Logging import Logging from Constants import Constants as C import CSE # TODO: create/delete each resource to count! resourceCreate(ty) # TODO move event creations from here to the resp modules. class EventManager(object): def __init__(self): self.addEvent('httpRetrieve') self.addEvent('httpCreate') self.addEvent('httpDelete') self.addEvent('httpUpdate') self.addEvent('httpRedirect') self.addEvent('createResource') self.addEvent('deleteResource') self.addEvent('cseStartup') self.addEvent('logError') self.addEvent('logWarning') Logging.log('EventManager initialized') def shutdown(self): Logging.log('EventManager shut down') ######################################################################### # Event topics are added as new methods of the handler class with the # given name and can be raised by calling those new methods, e.g. # # manager.addEvent("someName") # add new event topic # manager.addHandler(manager.someName, handlerFunction) # add an event handler # handler.someName() # raises the event def addEvent(self, name): if not hasattr(self, name): setattr(self, name, Event()) return getattr(self, name) def removeEvent(self, name): if hasattr(self, name): delattr(self, name) def hasEvent(self, name): return name in self.__dict__ def addHandler(self, event, func): event.append(func) def removeHandler(self, event, func): try: del event[func] except Exception as e: pass ######################################################################### # # Event class. # class Event(list): """Event subscription. A list of callable methods. Calling an instance of Event will cause a call to each function in the list in ascending order by index. It supports all methods from its base class (list), so use append() and remove() to add and remove functions. An event is raised by calling the event: anEvent(anArgument). It may have an arbitrary number of arguments which are passed to the functions. The function will be called in a separate thread in order to prevent waiting for the returns. This might lead to some race conditions, so the synchronizations must be done insode the functions. """ def __call__(self, *args, **kwargs): # Call the handlers in a thread so that we don't block everything thrd = threading.Thread(target=self._callThread, args=args, kwargs=kwargs) thrd.setDaemon(True) # Make the thread a daemon of the main thread thrd.start() def _callThread(self, *args, **kwargs): for function in self: function(*args, **kwargs) def __repr__(self): return "Event(%s)" % list.__repr__(self)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/EventManager.py
EventManager.py
# # GroupManager.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Managing entity for resource groups # from Logging import Logging from Constants import Constants as C import CSE, Utils from resources import FCNT, MgmtObj class GroupManager(object): def __init__(self): # Add delete event handler because we like to monitor the resources in mid CSE.event.addHandler(CSE.event.deleteResource, self.handleDeleteEvent) Logging.log('GroupManager initialized') def shutdown(self): Logging.log('GroupManager shut down') ######################################################################### def validateGroup(self, group, originator): # Get consistencyStrategy csy = group.csy # Check member types and group set type # Recursive for sub groups, if .../fopt. Check privileges of originator if not (res := self._checkMembersAndPrivileges(group, group.mt, group.csy, group.spty, originator))[0]: return res # Check for max members if group.hasAttribute('mnm'): # only if mnm attribute is set try: # mnm may not be a number if len(group.mid) > int(group.mnm): return (False, C.rcMaxNumberOfMemberExceeded) except ValueError: return (False, C.rcInvalidArguments) # TODO: check virtual resources return (True, C.rcOK) def _checkMembersAndPrivileges(self, group, mt, csy, spty, originator): # check for duplicates and remove them midsList = [] # contains the real mid list for mid in group['mid']: # get the resource and check it id = mid[:-5] if (hasFopt := mid.endswith('/fopt')) else mid # remove /fopt to retrieve the resource if (r := CSE.dispatcher.retrieveResource(id))[0] is None: return (False, C.rcNotFound) resource = r[0] # skip if ri is already in the list if (ri := resource.ri) in midsList: continue # check privileges if not CSE.security.hasAccess(originator, resource, C.permRETRIEVE): return (False, C.rcReceiverHasNoPrivileges) # if it is a group + fopt, then recursively check members if (ty := resource.ty) == C.tGRP and hasFopt: if not (res := self._checkMembersAndPrivileges(resource, mt, csy, spty, originator))[0]: return res ty = resource.mt # set the member type to the group's member type # check specializationType spty if spty is not None: if isinstance(spty, int): # mgmtobj type if isinstance(resource, MgmtObj.MgmtObj) and ty != spty: return (False, C.rcGroupMemberTypeInconsistent) elif isinstance(spty, str): # fcnt specialization if isinstance(resource, FCNT.FCNT) and resource.cnd != spty: return (False, C.rcGroupMemberTypeInconsistent) # check type of resource and member type of group if not (mt == C.tMIXED or ty == mt): # types don't match if csy == C.csyAbandonMember: # abandon member continue elif csy == C.csySetMixed: # change group's member type mt = C.tMIXED group['mt'] = C.tMIXED else: # abandon group return (False, C.rcGroupMemberTypeInconsistent) # member seems to be ok, so add ri to the list midsList.append(ri if not hasFopt else ri + '/fopt') # restore fopt for ri group['mid'] = midsList # replace with a cleaned up mid group['cnm'] = len(midsList) return (True, C.rcOK) def foptRequest(self, operation, fopt, request, id, originator, ct=None, ty=None): """ Handle requests to a fanOutPoint. This method might be called recursivly, when there are groups in groups.""" # get parent / group group = fopt.retrieveParentResource() if group is None: return (None, C.rcNotFound) # get the rqi header field (_, _, _, rqi, _) = Utils.getRequestHeaders(request) # check whether there is something after the /fopt ... (_, _, tail) = id.partition('/fopt/') if '/fopt/' in id else (_, _, '') Logging.logDebug('Adding additional path elements: %s' % tail) # walk through all members result = [] tail = '/' + tail if len(tail) > 0 else '' # add remaining path, if any for mid in group.mid: # Try to get the SRN and add the tail if (srn := Utils.structuredPathFromRI(mid)) is not None: mid = srn + tail else: mid = mid + tail # Invoke the request if operation == C.opRETRIEVE: if (res := CSE.dispatcher.handleRetrieveRequest(request, mid, originator))[0] is None: return res elif operation == C.opCREATE: if (res := CSE.dispatcher.handleCreateRequest(request, mid, originator, ct, ty))[0] is None: return res elif operation == C.opUPDATE: if (res := CSE.dispatcher.handleUpdateRequest(request, mid, originator, ct))[0] is None: return res elif operation == C.opDELETE: if (res := CSE.dispatcher.handleDeleteRequest(request, mid, originator))[1] != C.rcDeleted: return res else: return (None, C.rcOperationNotAllowed) result.append(res) # construct aggregated response if len(result) > 0: items = [] for r in result: item = { 'rsc' : r[1], 'rqi' : rqi, 'pc' : r[0].asJSON(), 'to' : r[0].__srn__ } items.append(item) rsp = { 'm2m:rsp' : items} agr = { 'm2m:agr' : rsp } else: agr = {} # Different "ok" results per operation return (agr, [ C.rcOK, C.rcCreated, C.rcUpdated, C.rcDeleted ][operation]) ######################################################################### def handleDeleteEvent(self, deletedResource): """Handle a delete event. Check whether the deleted resource is a member of group. If yes, remove the member.""" ri = deletedResource.ri groups = CSE.storage.searchByTypeFieldValue(C.tGRP, 'mid', ri) for group in groups: group['mid'].remove(ri) group['cnm'] = group.cnm - 1 CSE.storage.updateResource(group)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/GroupManager.py
GroupManager.py
# # Utils.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # This module contains various utilty functions that are used from various # modules and entities of the CSE. # import datetime, random, string, sys, re from resources import ACP, AE, ANDI, ANI, BAT, CIN, CNT, CNT_LA, CNT_OL, CSEBase, CSR, DVC from resources import DVI, EVL, FCI, FCNT, FCNT_LA, FCNT_OL, FWR, GRP, GRP_FOPT, MEM, NOD, RBO, SUB, SWR, Unknown from Constants import Constants as C from Configuration import Configuration from Logging import Logging import CSE def uniqueRI(prefix=''): p = prefix.split(':') p = p[1] if len(p) == 2 else p[0] return p + uniqueID() def isUniqueRI(ri): return len(CSE.storage.identifier(ri)) == 0 def uniqueRN(prefix='un'): p = prefix.split(':') p = p[1] if len(p) == 2 else p[0] return "%s_%s" % (p, ''.join(random.choices(string.ascii_uppercase + string.digits + string.ascii_lowercase, k=C.maxIDLength))) # create a unique aei, M2M-SP type def uniqueAEI(prefix='S'): return prefix + ''.join(random.choices(string.ascii_uppercase + string.digits + string.ascii_lowercase, k=C.maxIDLength)) def fullRI(ri): return '/' + Configuration.get('cse.csi') + '/' + ri def uniqueID(): return str(random.randint(1,sys.maxsize)) def isVirtualResource(resource): return (ty := r.ty) and ty in C.tVirtualResources # Check for valid ID def isValidID(id): #return len(id) > 0 and '/' not in id # pi might be "" return '/' not in id def getResourceDate(delta=0): return toISO8601Date(datetime.datetime.utcnow() + datetime.timedelta(seconds=delta)) def toISO8601Date(ts): if isinstance(ts, float): ts = datetime.datetime.utcfromtimestamp(ts) return ts.strftime('%Y%m%dT%H%M%S,%f') def structuredPath(resource): rn = resource.rn if resource.ty == C.tCSEBase: # if CSE return rn # retrieve identifier record of the parent if (pi := resource.pi) is None: Logging.logErr('PI is None') return rn rpi = CSE.storage.identifier(pi) if len(rpi) == 1: return rpi[0]['srn'] + '/' + rn Logging.logErr('Parent not fount in DB') return rn # fallback def structuredPathFromRI(ri): if len((identifiers := CSE.storage.identifier(ri))) == 1: return identifiers[0]['srn'] return None def resourceFromJSON(jsn, pi=None, acpi=None, tpe=None, create=False): (jsn, root) = pureResource(jsn) # remove optional "m2m:xxx" level ty = jsn['ty'] if 'ty' in jsn else tpe if ty != None and tpe != None and ty != tpe: return None mgd = jsn['mgd'] if 'mgd' in jsn else None # for mgmtObj # Add extra acpi if acpi is not None: jsn['acpi'] = acpi if type(acpi) is list else [ acpi ] # sorted by assumed frequency (small optimization) if ty == C.tCIN or root == C.tsCIN: return CIN.CIN(jsn, pi=pi, create=create) elif ty == C.tCNT or root == C.tsCNT: return CNT.CNT(jsn, pi=pi, create=create) elif ty == C.tGRP or root == C.tsGRP: return GRP.GRP(jsn, pi=pi, create=create) elif ty == C.tGRP_FOPT or root == C.tsGRP_FOPT: return GRP_FOPT.GRP_FOPT(jsn, pi=pi, create=create) elif ty == C.tACP or root == C.tsACP: return ACP.ACP(jsn, pi=pi, create=create) elif ty == C.tFCNT: return FCNT.FCNT(jsn, pi=pi, fcntType=root, create=create) elif ty == C.tFCI: return FCI.FCI(jsn, pi=pi, fcntType=root, create=create) elif ty == C.tAE or root == C.tsAE: return AE.AE(jsn, pi=pi, create=create) elif ty == C.tSUB or root == C.tsSUB: return SUB.SUB(jsn, pi=pi, create=create) elif ty == C.tCSR or root == C.tsCSR: return CSR.CSR(jsn, pi=pi, create=create) elif ty == C.tNOD or root == C.tsNOD: return NOD.NOD(jsn, pi=pi, create=create) elif (ty == C.tMGMTOBJ and mgd == C.mgdFWR) or root == C.tsFWR: return FWR.FWR(jsn, pi=pi, create=create) elif (ty == C.tMGMTOBJ and mgd == C.mgdSWR) or root == C.tsSWR: return SWR.SWR(jsn, pi=pi, create=create) elif (ty == C.tMGMTOBJ and mgd == C.mgdMEM) or root == C.tsMEM: return MEM.MEM(jsn, pi=pi, create=create) elif (ty == C.tMGMTOBJ and mgd == C.mgdANI) or root == C.tsANI: return ANI.ANI(jsn, pi=pi, create=create) elif (ty == C.tMGMTOBJ and mgd == C.mgdANDI) or root == C.tsANDI: return ANDI.ANDI(jsn, pi=pi, create=create) elif (ty == C.tMGMTOBJ and mgd == C.mgdBAT) or root == C.tsBAT: return BAT.BAT(jsn, pi=pi, create=create) elif (ty == C.tMGMTOBJ and mgd == C.mgdDVI) or root == C.tsDVI: return DVI.DVI(jsn, pi=pi, create=create) elif (ty == C.tMGMTOBJ and mgd == C.mgdDVC) or root == C.tsDVC: return DVC.DVC(jsn, pi=pi, create=create) elif (ty == C.tMGMTOBJ and mgd == C.mgdRBO) or root == C.tsRBO: return RBO.RBO(jsn, pi=pi, create=create) elif (ty == C.tMGMTOBJ and mgd == C.mgdEVL) or root == C.tsEVL: return EVL.EVL(jsn, pi=pi, create=create) elif ty == C.tCNT_LA or root == C.tsCNT_LA: return CNT_LA.CNT_LA(jsn, pi=pi, create=create) elif ty == C.tCNT_OL or root == C.tsCNT_OL: return CNT_OL.CNT_OL(jsn, pi=pi, create=create) elif ty == C.tFCNT_LA: return FCNT_LA.FCNT_LA(jsn, pi=pi, create=create) elif ty == C.tFCNT_OL: return FCNT_OL.FCNT_OL(jsn, pi=pi, create=create) elif ty == C.tCSEBase or root == C.tsCSEBase: return CSEBase.CSEBase(jsn, create=create) else: return Unknown.Unknown(jsn, ty, root, pi=pi, create=create) # Capture-All resource return None # return the "pure" json without the "m2m:xxx" resource specifier excludeFromRoot = [ 'pi' ] def pureResource(jsn): rootKeys = list(jsn.keys()) if len(rootKeys) == 1 and rootKeys[0] not in excludeFromRoot: return (jsn[rootKeys[0]], rootKeys[0]) return (jsn, None) # find a structured element in JSON def findXPath(jsn, element, default=None): paths = element.split("/") data = jsn for i in range(0,len(paths)): if paths[i] not in data: return default data = data[paths[i]] return data # set a structured element in JSON. Create if necessary, and observce the overwrite option def setXPath(jsn, element, value, overwrite=True): paths = element.split("/") ln = len(paths) data = jsn for i in range(0,ln-1): if paths[i] not in data: data[paths[i]] = {} data = data[paths[i]] if paths[ln-1] in data is not None and not overwrite: return # don't overwrite data[paths[ln-1]] = value urlregex = re.compile( r'^(?:http|ftp)s?://' # http://, https://, ftp://, ftps:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9]))|' # localhost or single name w/o domain r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ipv4 r'(?::\d+)?' # optional port r'(?:/?|[/?]\S+)$', re.IGNORECASE) # optional path def isURL(url): return url is not None and re.match(urlregex, url) is not None # Compare an old and a new resource. Keywords and values. Ignore internal __XYZ__ keys # Return a dictionary. def resourceDiff(old, new): res = {} for k,v in new.items(): if k.startswith('__'): # ignore all internal attributes continue if not k in old: # Key not in old res[k] = v elif v != old[k]: # Value different res[k] = v return res def getCSE(): return CSE.dispatcher.retrieveResource(Configuration.get('cse.ri')) # Check whether the target contains a fanoutPoint in between or as the target def fanoutPointResource(id): nid = None if id.endswith('/fopt'): nid = id elif '/fopt/' in id: (head, sep, tail) = id.partition('/fopt/') nid = head + '/fopt' if nid is not None: if (result := CSE.dispatcher.retrieveResource(nid))[0] is not None: return result[0] return None # # HTTP request helper functions # def requestID(request, rootPath): p = request.path if p.startswith(rootPath): p = p[len(rootPath):] if p.startswith('/'): p = p[1:] return p def requestHeaderField(request, field): if not request.headers.has_key(field): return None return request.headers.get(field) def getRequestHeaders(request): originator = requestHeaderField(request, C.hfOrigin) rqi = requestHeaderField(request, C.hfRI) # content-type ty = None if (ct := request.content_type) is not None: if not ct.startswith(tuple(C.supportedContentSerializations)): ct = None else: p = ct.partition(';') ct = p[0] # content-type t = p[2].partition('=')[2] ty = int(t) if t.isdigit() else C.tUNKNOWN # resource type return (originator, ct, ty, rqi, C.rcOK)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/Utils.py
Utils.py
# # Importer.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Entity to import various resources into the CSE. It is mainly run before # the CSE is actually started. # import json, os, fnmatch from Utils import * from Configuration import Configuration from Constants import Constants as C import CSE from Logging import Logging from resources import Resource class Importer(object): # List of "priority" resources that must be imported first for correct CSE operation _firstImporters = [ 'csebase.json', 'acp.admin.json', 'acp.default.json' ] def __init__(self): Logging.log('Importer initialized') def importResources(self, path=None): # Only when the DB is empty else don't imports if CSE.dispatcher.countResources() > 0: Logging.log('Resources already imported, skipping importing') # But we still need the CSI etc of the CSE rss = CSE.dispatcher.retrieveResourcesByType(C.tCSEBase) if rss is not None: Configuration.set('cse.csi', rss[0]['csi']) Configuration.set('cse.ri', rss[0]['ri']) Configuration.set('cse.rn', rss[0]['rn']) return True Logging.logErr('CSE not found') return False # get the originator for the creator attribute of imported resources originator = Configuration.get('cse.originator') # Import if path is None: if Configuration.has('cse.resourcesPath'): path = Configuration.get('cse.resourcesPath') else: Logging.logErr('cse.resourcesPath not set') raise RuntimeError('cse.resourcesPath not set') if not os.path.exists(path): Logging.logWarn('Import directory does not exist: %s' % path) return False Logging.log('Importing resources from directory: %s' % path) self._prepareImporting() # first import the priority resources, like CSE, Admin ACP, Default ACP hasCSE = False hasACP = False for rn in self._firstImporters: fn = path + '/' + rn if os.path.exists(fn): Logging.log('Importing resource: %s ' % fn) with open(fn) as jfile: r = resourceFromJSON(json.load(jfile), create=True) # Check resource creation if not CSE.registration.checkResourceCreation(r, originator): continue CSE.dispatcher.createResource(r) ty = r.ty if ty == C.tCSEBase: Configuration.set('cse.csi', r.csi) Configuration.set('cse.ri', r.ri) Configuration.set('cse.rn', r.rn) hasCSE = True elif ty == C.tACP: hasACP = True # Check presence of CSE and at least one ACP if not (hasCSE and hasACP): Logging.logErr('CSE and/or default ACP missing during import') self._finishImporting() return False # then get the filenames of all other files and sort them. Process them in order filenames = sorted(os.listdir(path)) for fn in filenames: if fn not in self._firstImporters: Logging.log('Importing resource from file: %s' % fn) with open(path + '/' + fn) as jfile: # update an existing resource if 'update' in fn: j = json.load(jfile) keys = list(j.keys()) if len(keys) == 1 and (k := keys[0]) and 'ri' in j[k] and (ri := j[k]['ri']) is not None: (r, _) = CSE.dispatcher.retrieveResource(ri) if r is not None: CSE.dispatcher.updateResource(r, j) # create a new cresource else: r = resourceFromJSON(json.load(jfile), create=True) # Try to get parent resource if r is not None: parent = None if (pi := r.pi) is not None: (parent, _) = CSE.dispatcher.retrieveResource(pi) # Check resource creation if not CSE.registration.checkResourceCreation(r, originator): continue # Add the resource CSE.dispatcher.createResource(r, parent) else: Logging.logWarn('Unknown resource in file: %s' % fn) self._finishImporting() return True def _prepareImporting(self): # temporarily disable access control self._oldacp = Configuration.get('cse.enableACPChecks') Configuration.set('cse.enableACPChecks', False) def _finishImporting(self): Configuration.set('cse.enableACPChecks', self._oldacp)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/Importer.py
Importer.py
# # Logging.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Wrapper for the logging sub-system. It provides simpler access as well # some more usefull output rendering. # """ Wrapper class for the logging subsystem. """ import logging, logging.handlers, os, inspect, re, sys, datetime# from logging import StreamHandler from Configuration import Configuration levelName = { logging.INFO : 'ℹ️ I', logging.DEBUG : '🐞 D', logging.ERROR : '🔥 E', logging.WARNING : '⚠️ W' # logging.INFO : 'INFO ', # logging.DEBUG : 'DEBUG ', # logging.ERROR : 'ERROR ', # logging.WARNING : 'WARNING' } class Logging: """ Wrapper class for the logging subsystem. This class wraps the initialization of the logging subsystem and provides convenience methods for printing log, error and warning messages to a logfile and to the console. """ logger = None logLevel = logging.INFO loggingEnabled = True enableFileLogging = True @staticmethod def init(): """Init the logging system. """ if Logging.logger is not None: return Logging.enableFileLogging = Configuration.get('logging.enableFileLogging') Logging.logLevel = Configuration.get('logging.level') Logging.loggingEnabled = Configuration.get('logging.enable') Logging.logger = logging.getLogger('logging') # Log to file only when file logging is enabled if Logging.enableFileLogging: logfile = Configuration.get('logging.file') os.makedirs(os.path.dirname(logfile), exist_ok=True)# create log directory if necessary logfp = logging.handlers.RotatingFileHandler( logfile, maxBytes=Configuration.get('logging.size'), backupCount=Configuration.get('logging.count')) logfp.setLevel(Logging.logLevel) logfp.setFormatter(logging.Formatter('%(levelname)s %(asctime)s %(message)s')) Logging.logger.addHandler(logfp) Logging.logger.setLevel(Logging.logLevel) @staticmethod def log(msg, withPath=True): """Print a log message with level INFO. """ Logging._log(logging.INFO, msg, withPath) @staticmethod def logDebug(msg, withPath=True): """Print a log message with level DEBUG. """ Logging._log(logging.DEBUG, msg, withPath) @staticmethod def logErr(msg, withPath=True): """Print a log message with level ERROR. """ import CSE CSE.event.logError() # raise logError event Logging._log(logging.ERROR, msg, withPath) @staticmethod def logWarn(msg, withPath=True): """Print a log message with level WARNING. """ import CSE CSE.event.logWarning() # raise logWarning event Logging._log(logging.WARNING, msg, withPath) @staticmethod def _log(level, msg, withPath): try: if Logging.loggingEnabled and Logging.logLevel <= level: caller = inspect.getframeinfo(inspect.stack()[2][0]) if withPath: msg = '(%s:%d) %s' % (os.path.basename(caller.filename), caller.lineno, msg) #print( "(" + time.ctime(time.time()) + ") " + msg) print('%s %s %s' % (levelName[level], datetime.datetime.now().isoformat(sep=' ', timespec='milliseconds'), msg)) Logging.logger.log(level, msg) except: pass # # Redirect handler to redirect other log output to our log # class RedirectHandler(StreamHandler): def __init__(self, topic): StreamHandler.__init__(self) self.topic = topic def emit(self, record): msg = '(%s) %s' % (self.topic, record.getMessage()) msg = re.sub(r'\[.+?\] ', '', msg) # clean up (remove superflous date and time) if record.levelno == logging.DEBUG: Logging.logDebug(msg, False) elif record.levelno == logging.INFO: Logging.log(msg, False) elif record.levelno == logging.WARNING: Logging.logWarn(msg, False) elif record.levelName == logging.ERROR: Logging.logErr(msg, False)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/Logging.py
Logging.py
# # Constante.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Various CSE and oneM2M constante # class Constants(object): # Type constants tUNKNOWN = -1 tMIXED = 0 tsMIXED = 'mixed' tACP = 1 tsACP = 'm2m:acp' tAE = 2 tsAE = 'm2m:ae' tCNT = 3 tsCNT = 'm2m:cnt' tCIN = 4 tsCIN = 'm2m:cin' tCSEBase = 5 tsCSEBase = 'm2m:cb' tGRP = 9 tsGRP = 'm2m:grp' tMGMTOBJ = 13 tsMGMTOBJ = 'm2m:mgo' # not an official shortname tNOD = 14 tsNOD = 'm2m:nod' tCSR = 16 tsCSR = 'm2m:csr' tSUB = 23 tsSUB = 'm2m:sub' tFCNT = 28 tsFCNT = 'm2m:fcnt' # not an official shortname tFCI = 52 tsFCI = 'm2m:fci' # not an official shortname # Virtual resources (proprietary resource types) tCNT_OL = -20001 tsCNT_OL = 'm2m:ol' tCNT_LA = -20002 tsCNT_LA = 'm2m:la' tGRP_FOPT = -20003 tsGRP_FOPT = 'm2m:fopt' tFCNT_OL = -20004 tsFCNT_OL = 'm2m:ol' tFCNT_LA = -20005 tsFCNT_LA = 'm2m:la' # <mgmtObj> Specializations mgdFWR = 1001 tsFWR = 'm2m:fwr' mgdSWR = 1002 tsSWR = 'm2m:swr' mgdMEM = 1003 tsMEM = 'm2m:mem' mgdANI = 1004 tsANI = 'm2m:ani' mgdANDI = 1005 tsANDI = 'm2m:andi' mgdBAT = 1006 tsBAT = 'm2m:bat' mgdDVI = 1007 tsDVI = 'm2m:dvi' mgdDVC = 1008 tsDVC = 'm2m:dvc' mgdRBO = 1009 tsRBO = 'm2m:rbo' mgdEVL = 1010 tsEVL = 'm2m:evl' # List of virtual resources tVirtualResources = [ tCNT_LA, tCNT_OL, tGRP_FOPT ] # Supported by this CSE supportedResourceTypes = [ tACP, tAE, tCNT, tCIN, tCSEBase, tGRP, tMGMTOBJ, tNOD, tCSR, tSUB, tFCNT, tFCI ] supportedContentSerializations = [ 'application/json', 'application/vnd.onem2m-res+json' ] supportedReleaseVersions = [ '3' ] # List of resource types for which "creator" is allowed # Also add later: eventConfig, pollingChannel, statsCollect, statsConfig, semanticDescriptor, # notificationTargetPolicy, timeSeries, crossResourceSubscription, backgroundDataTransfer tCreatorAllowed = [ tCIN, tCNT, tGRP, tSUB, tFCNT ] # max length of identifiers maxIDLength = 10 # Response codes rcOK = 2000 rcCreated = 2001 rcDeleted = 2002 rcUpdated = 2004 rcBadRequest = 4000 rcNotFound = 4004 rcOperationNotAllowed = 4005 rcContentsUnacceptable = 4102 rcOriginatorHasNoPrivilege = 4103 rcInvalidChildResourceType = 4108 rcGroupMemberTypeInconsistent = 4110 rcInternalServerError = 5000 rcNotImplemented = 5001 rcTargetNotReachable = 5103 rcReceiverHasNoPrivileges = 5105 rcAlreadyExists = 5106 rcTargetNotSubscribable = 5203 rcMaxNumberOfMemberExceeded = 6010 rcInvalidArguments = 6023 rcInsufficientArguments = 6024 # Operations opRETRIEVE = 0 opCREATE = 1 opUPDATE = 2 opDELETE = 3 # Permissions permNONE = 0 permCREATE = 1 permRETRIEVE = 2 permUPDATE = 4 permDELETE = 8 permNOTIFY = 16 permDISCOVERY = 32 permALL = 63 # CSE Types cseTypeIN = 1 cseTypeMN = 2 cseTypeASN = 3 cseTypes = [ '', 'IN', 'MN', 'ASN' ] # Header Fields hfOrigin = 'X-M2M-Origin' hfRI = 'X-M2M-RI' hfvContentType = 'application/json' # Subscription-related # notificationContentTypes nctAll = 1 nctModifiedAttributes = 2 nctRI = 3 # eventNotificationCriteria/NotificationEventTypes netResourceUpdate = 1 # default netResourceDelete = 2 netCreateDirectChild = 3 netDeleteDirectChild = 4 netRetrieveCNTNoChild = 5 # TODO not supported yet # Result Content types rcnNothing = 0 rcnAttributes = 1 rcnAttributesAndChildResources = 4 rcnAttributesAndChildResourceReferences = 5 rcnChildResourceReferences = 6 rcnChildResources = 8 rcnModifiedAttributes = 9 # TODO support other RCN # Desired Identifier Result Type drtStructured = 1 # default drtUnstructured = 2 # Filter Usage fuDiscoveryCriteria = 1 fuConditionalRetrieval = 2 # default fuIPEOnDemandDiscovery = 3 # Group related # consistencyStrategy csyAbandonMember = 1 # default csyAbandonGroup = 2 csySetMixed = 3
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/Constants.py
Constants.py
# # Configuration.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Managing CSE configurations # import logging, configparser from Constants import Constants as C defaultConfigFile = 'acme.ini' defaultImportDirectory = './init' class Configuration(object): _configuration = {} @staticmethod def init(args = None): global _configuration # resolve the args, of any argsConfigfile = args.configfile if args is not None else defaultConfigFile argsLoglevel = args.loglevel if args is not None else None argsDBReset = args.dbreset if args is not None else False argsDBStorageMode = args.dbstoragemode if args is not None else None argsImportDirectory = args.importdirectory if args is not None else None argsAppsEnabled = args.appsenabled if args is not None else None config = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation()) config.read(argsConfigfile) try: Configuration._configuration = { 'configfile' : argsConfigfile, # # HTTP Server # 'http.listenIF' : config.get('server.http', 'listenIF', fallback='127.0.0.1'), 'http.port' : config.getint('server.http', 'port', fallback=8080), 'http.root' : config.get('server.http', 'root', fallback='/'), 'http.address' : config.get('server.http', 'address', fallback='http://127.0.0.1:8080'), 'http.multiThread' : config.getboolean('server.http', 'multiThread', fallback=True), # # Database # 'db.path' : config.get('database', 'path', fallback='./data'), 'db.inMemory' : config.getboolean('database', 'inMemory', fallback=False), 'db.cacheSize' : config.getint('database', 'cacheSize', fallback=0), # Default: no caching 'db.resetAtStartup' : config.getboolean('database', 'resetAtStartup', fallback=False), # # Logging # 'logging.enable' : config.getboolean('logging', 'enable', fallback=True), 'logging.enableFileLogging' : config.getboolean('logging', 'enableFileLogging', fallback=True), 'logging.file' : config.get('logging', 'file', fallback='./logs/cse.log'), 'logging.level' : config.get('logging', 'level', fallback='debug'), 'logging.size' : config.getint('logging', 'size', fallback=100000), 'logging.count' : config.getint('logging', 'count', fallback=10), # Number of log files # # CSE # 'cse.type' : config.get('cse', 'type', fallback='IN'), # IN, MN, ASN 'cse.resourcesPath' : config.get('cse', 'resourcesPath', fallback=defaultImportDirectory), 'cse.expirationDelta' : config.getint('cse', 'expirationDelta', fallback=60*60*24*365), # 1 year, in seconds 'cse.enableACPChecks' : config.getboolean('cse', 'enableACPChecks', fallback=True), 'cse.adminACPI' : config.get('cse', 'adminACPI', fallback='acpAdmin'), 'cse.defaultACPI' : config.get('cse', 'defaultACPI', fallback='acpDefault'), 'cse.originator' : config.get('cse', 'originator', fallback='CAdmin'), 'cse.csi' : '(not set yet)', # will be set by importer 'cse.ri' : '(not set yet)', # will be set by importer 'cse.rn' : '(not set yet)', # will be set by importer 'cse.enableApplications' : config.getboolean('cse', 'enableApplications', fallback=True), 'cse.enableNotifications' : config.getboolean('cse', 'enableNotifications', fallback=True), 'cse.enableRemoteCSE' : config.getboolean('cse', 'enableRemoteCSE', fallback=True), 'cse.enableTransitRequests' : config.getboolean('cse', 'enableTransitRequests', fallback=True), 'cse.sortDiscoveredResources' : config.getboolean('cse', 'sortDiscoveredResources', fallback=True), # # Remote CSE # 'cse.remote.address' : config.get('cse.remote', 'address', fallback=''), 'cse.remote.root' : config.get('cse.remote', 'root', fallback='/'), 'cse.remote.cseid' : config.get('cse.remote', 'cseid', fallback=''), 'cse.remote.originator' : config.get('cse.remote', 'originator', fallback='CAdmin'), 'cse.remote.checkInterval' : config.getint('cse.remote', 'checkInterval', fallback=30), # Seconds # # Statistics # 'cse.statistics.writeIntervall' : config.getint('cse.statistics', 'writeIntervall', fallback=60), # Seconds # # Defaults for Container Resources # 'cse.cnt.mni' : config.getint('cse.resource.cnt', 'mni', fallback=10), 'cse.cnt.mbs' : config.getint('cse.resource.cnt', 'mbs', fallback=10000), # # Defaults for Access Control Policies # 'cse.acp.pv.acop' : config.getint('cse.resource.acp', 'permission', fallback=63), 'cse.acp.pvs.acop' : config.getint('cse.resource.acp', 'selfPermission', fallback=51), 'cse.acp.addAdminOrignator' : config.getboolean('cse.resource.acp', 'addAdminOrignator', fallback=True), # # Defaults for Application Entities # 'cse.ae.createACP' : config.getboolean('cse.resource.ae', 'createACP', fallback=True), 'cse.ae.removeACP' : config.getboolean('cse.resource.ae', 'removeACP', fallback=True), # # Web UI # 'cse.webui.enable' : config.getboolean('cse.webui', 'enable', fallback=True), 'cse.webui.root' : config.get('cse.webui', 'root', fallback='/webui'), # # App: Statistics AE # 'app.statistics.enable' : config.getboolean('app.statistics', 'enable', fallback=True), 'app.statistics.aeRN' : config.get('app.statistics', 'aeRN', fallback='statistics'), 'app.statistics.aeAPI' : config.get('app.statistics', 'aeAPI', fallback='ae-statistics'), 'app.statistics.fcntRN' : config.get('app.statistics', 'fcntRN', fallback='statistics'), 'app.statistics.fcntCND' : config.get('app.statistics', 'fcntCND', fallback='acme.statistics'), 'app.statistics.fcntType' : config.get('app.statistics', 'fcntType', fallback='acme:csest'), 'app.statistics.originator' : config.get('app.statistics', 'originator', fallback='C'), 'app.statistics.intervall' : config.getint('app.statistics', 'intervall', fallback=10), # seconds # # App: CSE Node # 'app.csenode.enable' : config.getboolean('app.csenode', 'enable', fallback=True), 'app.csenode.nodeRN' : config.get('app.csenode', 'nodeRN', fallback='cse-node'), 'app.csenode.nodeID' : config.get('app.csenode', 'nodeID', fallback='cse-node'), 'app.csenode.originator' : config.get('app.csenode', 'originator', fallback='CAdmin'), 'app.csenode.batteryLowLevel' : config.getint('app.csenode', 'batteryLowLevel', fallback=20), # percent 'app.csenode.batteryChargedLevel' : config.getint('app.csenode', 'batteryChargedLevel', fallback=100), # percent 'app.csenode.intervall' : config.getint('app.csenode', 'updateIntervall', fallback=60), # seconds } except Exception as e: # about when findings errors in configuration print('Error in configuration file: %s - %s' % (argsConfigfile, str(e))) return False # Read id-mappings if config.has_section('server.http.mappings'): Configuration._configuration['server.http.mappings'] = config.items('server.http.mappings') #print(config.items('server.http.mappings')) # Some clean-ups and overrites # CSE type cseType = Configuration._configuration['cse.type'].lower() if cseType == 'asn': Configuration._configuration['cse.type'] = C.cseTypeASN elif cseType == 'mn': Configuration._configuration['cse.type'] = C.cseTypeMN else: Configuration._configuration['cse.type'] = C.cseTypeIN # Loglevel from command line logLevel = Configuration._configuration['logging.level'].lower() logLevel = argsLoglevel if argsLoglevel is not None else logLevel # command line args override config if logLevel == 'off': Configuration._configuration['logging.enable'] = False Configuration._configuration['logging.level'] = logging.DEBUG elif logLevel == 'info': Configuration._configuration['logging.level'] = logging.INFO elif logLevel == 'warn': Configuration._configuration['logging.level'] = logging.WARNING elif logLevel == 'error': Configuration._configuration['logging.level'] = logging.ERROR else: Configuration._configuration['logging.level'] = logging.DEBUG # Override DB reset from command line if argsDBReset is True: Configuration._configuration['db.resetAtStartup'] = True # Override DB storage mode from command line if argsDBStorageMode is not None: Configuration._configuration['db.inMemory'] = argsDBStorageMode == 'memory' # Override import directory from command line if argsImportDirectory is not None: Configuration._configuration['cse.resourcesPath'] = argsImportDirectory # Override app enablement if argsAppsEnabled is not None: Configuration._configuration['cse.enableApplications'] = argsAppsEnabled return True @staticmethod def print(): result = 'Configuration:\n' for kv in Configuration._configuration.items(): result += ' %s = %s\n' % kv return result @staticmethod def all(): return Configuration._configuration @staticmethod def get(key): if not Configuration.has(key): return None return Configuration._configuration[key] @staticmethod def set(key, value): Configuration._configuration[key] = value @staticmethod def has(key): return key in Configuration._configuration
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/Configuration.py
Configuration.py
# # CSE.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Container that holds references to instances of various managing entities. # import atexit, argparse, os, threading, time from Constants import Constants as C from AnnouncementManager import AnnouncementManager from Configuration import Configuration, defaultConfigFile from Dispatcher import Dispatcher from EventManager import EventManager from GroupManager import GroupManager from HttpServer import HttpServer from Importer import Importer from Logging import Logging from NotificationManager import NotificationManager from RegistrationManager import RegistrationManager from RemoteCSEManager import RemoteCSEManager from SecurityManager import SecurityManager from Statistics import Statistics from Storage import Storage from AEStatistics import AEStatistics from CSENode import CSENode # singleton main components. These variables will hold all the various manager # components that are used throughout the CSE implementation. announce = None dispatcher = None event = None group = None httpServer = None notification = None registration = None remote = None security = None statistics = None storage = None rootDirectory = None aeCSENode = None aeStatistics = None appsStarted = False aeStartupDelay = 5 # seconds # TODO make AE registering a bit more generic ############################################################################## #def startup(args=None, configfile=None, resetdb=None, loglevel=None): def startup(args, **kwargs): global announce, dispatcher, group, httpServer, notification, registration, remote, security, statistics, storage, event global rootDirectory global aeStatistics rootDirectory = os.getcwd() # get the root directory # Handle command line arguments and load the configuration if args is None: args = argparse.Namespace() # In case args is None create a new args object and populate it args.configfile = None args.resetdb = False args.loglevel = None for key, value in kwargs.items(): args.__setattr__(key, value) if not Configuration.init(args): return # init Logging Logging.init() Logging.log('============') Logging.log('Starting CSE') Logging.log('CSE-Type: %s' % C.cseTypes[Configuration.get('cse.type')]) Logging.log(Configuration.print()) # Initiatlize the resource storage storage = Storage() # Initialize the event manager event = EventManager() # Initialize the statistics system statistics = Statistics() # Initialize the registration manager registration = RegistrationManager() # Initialize the resource dispatcher dispatcher = Dispatcher() # Initialize the security manager security = SecurityManager() # Initialize the HTTP server httpServer = HttpServer() # Initialize the notification manager notification = NotificationManager() # Initialize the announcement manager announce = AnnouncementManager() # Initialize the group manager group = GroupManager() # Import a default set of resources, e.g. the CSE, first ACP or resource structure importer = Importer() if not importer.importResources(): return # Initialize the remote CSE manager remote = RemoteCSEManager() remote.start() # Start AEs startAppsDelayed() # the Apps are actually started after the CSE finished the startup # Start the HTTP server event.cseStartup() Logging.log('CSE started') httpServer.run() # This does NOT return # Gracefully shutdown the CSE, e.g. when receiving a keyboard interrupt @atexit.register def shutdown(): if appsStarted: stopApps() if remote is not None: remote.shutdown() if group is not None: group.shutdown() if announce is not None: announce.shutdown() if notification is not None: notification.shutdown() if dispatcher is not None: dispatcher.shutdown() if security is not None: security.shutdown() if registration is not None: registration.shutdown() if statistics is not None: statistics.shutdown() if event is not None: event.shutdown() if storage is not None: storage.shutdown() # Delay starting the AEs in the backround. This is needed because the CSE # has not yet started. This will be called when the cseStartup event is raised. def startAppsDelayed(): event.addHandler(event.cseStartup, startApps) def startApps(): global appsStarted, aeStatistics, aeCSENode if not Configuration.get('cse.enableApplications'): return time.sleep(aeStartupDelay) Logging.log('Starting Apps') appsStarted = True if Configuration.get('app.csenode.enable'): aeCSENode = CSENode() if Configuration.get('app.statistics.enable'): aeStatistics = AEStatistics() # Add more apps here def stopApps(): global appsStarted if appsStarted: Logging.log('Stopping Apps') appsStarted = False if aeStatistics is not None: aeStatistics.shutdown() if aeCSENode is not None: aeCSENode.shutdown()
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/CSE.py
CSE.py
# # SecurityManager.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # This entity handles access to resources # from Logging import Logging from Constants import Constants as C import CSE from Configuration import Configuration class SecurityManager(object): def __init__(self): Logging.log('SecurityManager initialized') if Configuration.get('cse.enableACPChecks'): Logging.log('ACP checking ENABLED') else: Logging.log('ACP checking DISABLED') def shutdown(self): Logging.log('SecurityManager shut down') def hasAccess(self, originator, resource, requestedPermission, checkSelf=False, ty=None, isCreateRequest=False): if not Configuration.get('cse.enableACPChecks'): # check or ignore the check return True # originator may be None or empty or C or S. # That is okay if type is AE and this is a create request if originator is None or len(originator) == 0 or originator in ['C', 'S']: if ty is not None and ty == C.tAE and isCreateRequest: Logging.logDebug("Empty originator for AE CREATE. OK.") return True # Check parameters if resource is None: Logging.logWarn("Resource must not be None") return False if requestedPermission is None or not (0 <= requestedPermission <= C.permALL): Logging.logWarn("RequestedPermission must not be None, and between 0 and 63") return False Logging.logDebug("Checking permission for originator: %s, ri: %s, permission: %d, selfPrivileges: %r" % (originator, resource.ri, requestedPermission, checkSelf)) if resource.ty == C.tACP: # target is an ACP resource if resource.checkSelfPermission(originator, requestedPermission): Logging.logDebug('Permission granted') return True else: # target is not an ACP resource if (acpi := resource.acpi) is None or len(acpi) == 0: if resource.inheritACP: (parentResource, _) = CSE.dispatcher.retrieveResource(resource.pi) return self.hasAccess(originator, parentResource, requestedPermission, checkSelf) Logging.logDebug("Missing acpi in resource") return False for a in acpi: (acp, _) = CSE.dispatcher.retrieveResource(a) if acp is None: continue if checkSelf: # forced check for self permissions if acp.checkSelfPermission(originator, requestedPermission): Logging.logDebug('Permission granted') return True else: if acp.checkPermission(originator, requestedPermission): Logging.logDebug('Permission granted') return True # no fitting permission identified Logging.logDebug('Permission NOT granted') return False
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/SecurityManager.py
SecurityManager.py
# # RegistrationManager.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Managing resource / AE registrations # from Logging import Logging from Constants import Constants as C from Configuration import Configuration import CSE, Utils from resources import ACP acpPrefix = 'acp_' class RegistrationManager(object): def __init__(self): Logging.log('RegistrationManager initialized') def shutdown(self): Logging.log('RegistrationManager shut down') ######################################################################### # # Handle new resources in general # def checkResourceCreation(self, resource, originator, parentResource=None): if resource.ty in [ C.tAE ]: if (originator := self.handleAERegistration(resource, originator, parentResource)) is None: return (originator, C.rcOK) # Test and set creator attribute. if (rc := self.handleCreator(resource, originator)) != C.rcOK: return (None, rc) return (originator, C.rcOK) # Check for (wrongly) set creator attribute as well as assign it to allowed resources. def handleCreator(self, resource, originator): # Check whether cr is set. This is wrong if resource.cr is not None: Logging.logWarn('Setting "creator" attribute is not allowed.') return C.rcBadRequest # Set cr for some of the resource types if resource.ty in C.tCreatorAllowed: resource['cr'] = Configuration.get('cse.originator') if originator in ['C', 'S', '', None ] else originator return C.rcOK def checkResourceDeletion(self, resource, originator): if resource.ty in [ C.tAE ]: if not self.handleAEDeRegistration(resource): return (False, originator) return (True, originator) ######################################################################### # # Handle AE registration # def handleAERegistration(self, ae, originator, parentResource): if originator == 'C': originator = Utils.uniqueAEI('C') elif originator == 'S': originator = Utils.uniqueAEI('S') elif originator is None or len(originator) == 0: originator = Utils.uniqueAEI('S') Logging.logDebug('Registering AE. aei: %s ' % originator) # set the aei to the originator ae['aei'] = originator # Verify that parent is the CSEBase, else this is an error if parentResource is None or parentResource.ty != C.tCSEBase: return None # Create an ACP for this AE-ID if there is none set if Configuration.get("cse.ae.createACP"): if ae.acpi is None or len(ae.acpi) == 0: Logging.logDebug('Adding ACP for AE') cseOriginator = Configuration.get('cse.originator') acp = ACP.ACP(pi=parentResource.ri, rn=acpPrefix + ae.rn) acp.addPermissionOriginator(originator) acp.addPermissionOriginator(cseOriginator) acp.setPermissionOperation(Configuration.get('cse.acp.pv.acop')) acp.addSelfPermissionOriginator(cseOriginator) acp.setSelfPermissionOperation(Configuration.get('cse.acp.pvs.acop')) if not (res := self.checkResourceCreation(acp, originator, parentResource))[0]: return None CSE.dispatcher.createResource(acp, parentResource=parentResource, originator=originator) # Set ACPI (anew) ae['acpi'] = [ acp.ri ] else: ae['acpi'] = [ Configuration.get('cse.defaultACPI') ] return originator # # Handle AE deregistration # def handleAEDeRegistration(self, resource): # remove the before created ACP, if it exist Logging.logDebug('DeRegisterung AE. aei: %s ' % resource.aei) if Configuration.get("cse.ae.removeACP"): Logging.logDebug('Removing ACP for AE') acpi = '%s/%s%s' % (Configuration.get("cse.rn"), acpPrefix, resource.rn) if (res := CSE.dispatcher.retrieveResource(acpi))[1] != C.rcOK: Logging.logWarn('Could not find ACP: %s' % acpi) return False CSE.dispatcher.deleteResource(res[0]) return True
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/RegistrationManager.py
RegistrationManager.py
# # Statistics.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Statistics Module # from Logging import Logging from Configuration import Configuration import CSE, Utils import datetime from threading import Lock from helpers import BackgroundWorker deletedResources = 'rmRes' createdresources = 'crRes' httpRetrieves = 'htRet' httpCreates = 'htCre' httpUpdates = 'htUpd' httpDeletes = 'htDel' logErrors = 'lgErr' logWarnings = 'lgWrn' cseStartUpTime = 'cseSU' cseUpTime = 'cseUT' resourceCount = 'ctRes' # TODO startup, uptime, restartcount, errors, warnings class Statistics(object): def __init__(self): # create lock self.statLock = Lock() # retrieve or create statitics record self.stats = self.setupStats() # Start b ackground worker to handle writing to DB Logging.log('Starting statistics DB thread') self.worker = BackgroundWorker.BackgroundWorker(Configuration.get('cse.statistics.writeIntervall'), self.statisticsDBWorker) self.worker.start() # subscripe vto various events CSE.event.addHandler(CSE.event.createResource, self.handleCreateEvent) CSE.event.addHandler(CSE.event.deleteResource, self.handleDeleteEvent) CSE.event.addHandler(CSE.event.httpRetrieve, self.handleHttpRetrieveEvent) CSE.event.addHandler(CSE.event.httpCreate, self.handleHttpCreateEvent) CSE.event.addHandler(CSE.event.httpUpdate, self.handleHttpUpdateEvent) CSE.event.addHandler(CSE.event.httpDelete, self.handleHttpDeleteEvent) CSE.event.addHandler(CSE.event.cseStartup, self.handleCseStartup) CSE.event.addHandler(CSE.event.logError, self.handleLogError) CSE.event.addHandler(CSE.event.logWarning, self.handleLogWarning) Logging.log('Statistics initialized') def shutdown(self): # Stop the worker Logging.log('Stopping statistics DB thread') self.worker.stop() # One final write self.storeDBStatistics() Logging.log('Statistics shut down') def setupStats(self): result = self.retrieveDBStatistics() if result is not None: return result return { deletedResources : 0, createdresources : 0, httpRetrieves : 0, httpCreates : 0, httpUpdates : 0, httpDeletes : 0, cseStartUpTime : 0.0, logErrors : 0, logWarnings : 0 } # Return stats def getStats(self): s = self.stats.copy() # Calculate some stats s[cseUpTime] = str(datetime.timedelta(seconds=int(datetime.datetime.utcnow().timestamp() - s[cseStartUpTime]))) s[cseStartUpTime] = Utils.toISO8601Date(s[cseStartUpTime]) s[resourceCount] = s[createdresources] - s[deletedResources] return s ######################################################################### # # Event handlers # def handleCreateEvent(self, resource): with self.statLock: self.stats[createdresources] += 1 def handleDeleteEvent(self, resource): with self.statLock: self.stats[deletedResources] += 1 def handleHttpRetrieveEvent(self): with self.statLock: self.stats[httpRetrieves] += 1 def handleHttpCreateEvent(self): with self.statLock: self.stats[httpCreates] += 1 def handleHttpUpdateEvent(self): with self.statLock: self.stats[httpUpdates] += 1 def handleHttpDeleteEvent(self): with self.statLock: self.stats[httpDeletes] += 1 def handleCseStartup(self): with self.statLock: self.stats[cseStartUpTime] = datetime.datetime.utcnow().timestamp() def handleLogError(self): with self.statLock: self.stats[logErrors] += 1 def handleLogWarning(self): with self.statLock: self.stats[logWarnings] += 1 ######################################################################### # # Store statistics handling # Called by the background worker def statisticsDBWorker(self): Logging.logDebug('Writing statistics DB') try: self.storeDBStatistics() except Exception as e: Logging.logErr('Exception: %s' % e) return False return True def retrieveDBStatistics(self): with self.statLock: return CSE.storage.getStatistics() def storeDBStatistics(self): with self.statLock: return CSE.storage.updateStatistics(self.stats)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/Statistics.py
Statistics.py
# # NotificationManager.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # This entity handles subscriptions and sending of notifications. # from Logging import Logging from Constants import Constants as C from Configuration import Configuration import Utils, CSE import requests, json # TODO: removal policy (e.g. unsuccessful tries) # TODO: no async notifications yet, no batches etc class NotificationManager(object): def __init__(self): Logging.log('NotificationManager initialized') if Configuration.get('cse.enableNotifications'): Logging.log('Notifications ENABLED') else: Logging.log('Notifications DISABLED') def shutdown(self): Logging.log('NotificationManager shut down') def addSubscription(self, subscription): if Configuration.get('cse.enableNotifications') is not True: return False Logging.logDebug('Adding subscription') if self._getAndCheckNUS(subscription) is None: # verification requests happen here return False return CSE.storage.addSubscription(subscription) def removeSubscription(self, subscription): Logging.logDebug('Removing subscription') # This check does allow for removal of subscriptions if Configuration.get('cse.enableNotifications'): for nu in self._getNotificationURLs(subscription.nu): if not self._sendDeletionNotification(nu, subscription): Logging.logDebug('Deletion request failed') # but ignore the error return CSE.storage.removeSubscription(subscription) def updateSubscription(self, subscription): Logging.logDebug('Updating subscription') previousSub = CSE.storage.getSubscription(subscription.ri) if self._getAndCheckNUS(subscription, previousSub['nus']) is None: # verification/delete requests happen here return False return CSE.storage.updateSubscription(subscription) def checkSubscriptions(self, resource, reason, childResource=None): if Configuration.get('cse.enableNotifications') is not True: return ri = resource.ri subs = CSE.storage.getSubscriptionsForParent(ri) if subs is None or len(subs) == 0: return Logging.logDebug('Checking subscription for: %s, reason: %d' % (ri, reason)) for sub in subs: # Prevent own notifications for subscriptions if childResource is not None and \ sub['ri'] == childResource.ri and \ reason in [C.netCreateDirectChild, C.netDeleteDirectChild]: continue if reason not in sub['net']: # check whether reason is actually included in the subscription continue if reason in [C.netCreateDirectChild, C.netDeleteDirectChild]: # reasons for child resources for nu in self._getNotificationURLs(sub['nus']): if not self._sendNotification(sub, nu, reason, childResource): pass else: # all other reasons that target the resource for nu in self._getNotificationURLs(sub['nus']): if not self._sendNotification(sub, nu, reason, resource): pass ######################################################################### # Return resolved notification URLs, so also POA from referenced AE's etc def _getNotificationURLs(self, nus): result = [] for nu in nus: # check if it is a direct URL if Utils.isURL(nu): result.append(nu) else: (r, _) = CSE.dispatcher.retrieveResource(nu) if r is None: continue if not CSE.security.hasAccess('', r, C.permNOTIFY): # check whether AE/CSE may receive Notifications continue if (poa := r['poa']) is not None and isinstance(poa, list): #TODO? check whether AE or CSEBase result += poa return result def _getAndCheckNUS(self, subscription, previousNus=None): newNus = self._getNotificationURLs(subscription['nu']) # notify removed nus (deletion notification) if previousNus is not None: for nu in previousNus: if nu not in newNus: if not self._sendDeletionNotification(nu, subscription): Logging.logDebug('Deletion request failed') # but ignore the error # notify new nus (verification request) for nu in newNus: if previousNus is None or (previousNus and nu not in previousNus): if not self._sendVerificationRequest(nu, subscription): Logging.logDebug('Verification request failed: %s' % nu) return None return newNus ######################################################################### _verificationRequest = { 'm2m:sgn' : { 'vrq' : True, 'sur' : '' } } def _sendVerificationRequest(self, nu, subscription): Logging.logDebug('Sending verification request to: %s' % nu) return self._sendRequest(nu, subscription['ri'], self._verificationRequest) _deletionNotification = { 'm2m:sgn' : { 'sud' : True, 'sur' : '' } } def _sendDeletionNotification(self, nu, subscription): Logging.logDebug('Sending deletion notification to: %s' % nu) return self._sendRequest(nu, subscription['ri'], self._deletionNotification) _notificationRequest = { 'm2m:sgn' : { 'nev' : { 'rep' : {}, 'net' : 0 }, 'sur' : '' } } def _sendNotification(self, subscription, nu, reason, resource): Logging.logDebug('Sending notification to: %s, reason: %d' % (nu, reason)) return self._sendRequest(nu, subscription['ri'], self._notificationRequest, reason, resource) def _sendRequest(self, nu, ri, jsn, reason=None, resource=None): Utils.setXPath(jsn, 'm2m:sgn/sur', Utils.fullRI(ri)) if reason is not None: Utils.setXPath(jsn, 'm2m:sgn/nev/net', reason) if resource is not None: Utils.setXPath(jsn, 'm2m:sgn/nev/rep', resource.asJSON()) (_, rc) = CSE.httpServer.sendCreateRequest(nu, Configuration.get('cse.csi'), data=json.dumps(jsn)) return rc in [C.rcOK]
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/NotificationManager.py
NotificationManager.py
# # HttpServer.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Server to implement the http part of the oneM2M Mcx communication interface. # This manager is the main run-loop for the CSE (when using http). # from flask import Flask, request, make_response import flask from Configuration import Configuration from Constants import Constants as C import CSE, Utils from Logging import Logging, RedirectHandler from resources.Resource import Resource import json, requests, logging, os from werkzeug.serving import WSGIRequestHandler class HttpServer(object): def __init__(self): # Initialize the http server # Meaning defaults are automatically provided. self.flaskApp = Flask(Configuration.get('cse.csi')) self.rootPath = Configuration.get('http.root') Logging.log('Registering http server root at: %s' % self.rootPath) while self.rootPath.endswith('/'): self.rootPath = self.rootPath[:-1] # Add endpoints # self.addEndpoint(self.rootPath + '/', handler=self.handleGET, methods=['GET']) self.addEndpoint(self.rootPath + '/<path:path>', handler=self.handleGET, methods=['GET']) # self.addEndpoint(self.rootPath + '/', handler=self.handlePOST, methods=['POST']) self.addEndpoint(self.rootPath + '/<path:path>', handler=self.handlePOST, methods=['POST']) # self.addEndpoint(self.rootPath + '/', handler=self.handlePUT, methods=['PUT']) self.addEndpoint(self.rootPath + '/<path:path>', handler=self.handlePUT, methods=['PUT']) # self.addEndpoint(self.rootPath + '/', handler=self.handleDELETE, methods=['DELETE']) self.addEndpoint(self.rootPath + '/<path:path>', handler=self.handleDELETE, methods=['DELETE']) # Register the endpoint for the web UI if Configuration.get('cse.webui.enable'): self.webuiRoot = Configuration.get('cse.webui.root') self.webuiDirectory = '%s/webui' % CSE.rootDirectory Logging.log('Registering web ui at: %s, serving from %s' % (self.webuiRoot, self.webuiDirectory)) self.addEndpoint(self.webuiRoot, handler=self.handleWebUIGET, methods=['GET']) self.addEndpoint(self.webuiRoot + '/<path:path>', handler=self.handleWebUIGET, methods=['GET']) self.addEndpoint('/', handler=self.redirectRoot, methods=['GET']) # Add mapping / macro endpoints self.mappings = {} if (mappings := Configuration.get('server.http.mappings')) is not None: # mappings is a list of tuples for (k, v) in mappings: Logging.log('Registering mapping: %s%s -> %s%s' % (self.rootPath, k, self.rootPath, v)) self.addEndpoint(self.rootPath + k, handler=self.requestRedirect, methods=['GET', 'POST', 'PUT', 'DELETE']) self.mappings = dict(mappings) def run(self): # Redirect the http server (Flask) log output to the CSE logs werkzeugLog = logging.getLogger('werkzeug') werkzeugLog.addHandler(RedirectHandler("httpServer")) WSGIRequestHandler.protocol_version = "HTTP/1.1" # Run the http server. This runs forever. # The server can run single-threadedly since some of the underlying # components (e.g. TinyDB) may run into problems otherwise. if self.flaskApp is not None: try: self.flaskApp.run(host=Configuration.get('http.listenIF'), port=Configuration.get('http.port'), threaded=Configuration.get('http.multiThread')) except Exception as e: Logging.logErr(e) def addEndpoint(self, endpoint=None, endpoint_name=None, handler=None, methods=None): self.flaskApp.add_url_rule(endpoint, endpoint_name, handler, methods=methods) def handleGET(self, path=None): Logging.logDebug('==> Retrieve: %s' % request.path) Logging.logDebug('Headers: \n' + str(request.headers)) CSE.event.httpRetrieve() (resource, rc) = CSE.dispatcher.retrieveRequest(request) return self._prepareResponse(request, resource, rc) def handlePOST(self, path=None): Logging.logDebug('==> Create: %s' % request.path) Logging.logDebug('Headers: \n' + str(request.headers)) Logging.logDebug('Body: \n' + str(request.data)) CSE.event.httpCreate() (resource, rc) = CSE.dispatcher.createRequest(request) return self._prepareResponse(request, resource, rc) def handlePUT(self, path=None): Logging.logDebug('==> Update: %s' % request.path) Logging.logDebug('Headers: \n' + str(request.headers)) Logging.logDebug('Body: \n' + str(request.data)) CSE.event.httpUpdate() (resource, rc) = CSE.dispatcher.updateRequest(request) return self._prepareResponse(request, resource, rc) def handleDELETE(self, path=None): Logging.logDebug('==> Delete: %s' % request.path) Logging.logDebug('Headers: \n' + str(request.headers)) CSE.event.httpDelete() (resource, rc) = CSE.dispatcher.deleteRequest(request) return self._prepareResponse(request, resource, rc) ######################################################################### # Handle requests to mapped paths def requestRedirect(self): path = request.path[len(self.rootPath):] if request.path.startswith(self.rootPath) else request.path if path in self.mappings: Logging.logDebug('==> Redirecting to: %s' % path) CSE.event.httpRedirect() return flask.redirect(self.mappings[path], code=307) return '', 404 ######################################################################### # Redirect request to / to webui def redirectRoot(self): return flask.redirect(Configuration.get('cse.webui.root'), code=302) def handleWebUIGET(self, path=None): # security check whether the path will under the web root if not (CSE.rootDirectory + request.path).startswith(CSE.rootDirectory): return None, 404 # Redirect to index file. Also include base / cse RI if path == None or len(path) == 0 or (path.endswith('index.html') and len(request.args) != 1): return flask.redirect('%s/index.html?ri=/%s' % (self.webuiRoot, Configuration.get('cse.ri')), code=302) else: filename = '%s/%s' % (self.webuiDirectory, path) # return any file in the web directory try: return flask.send_file(filename) except Exception as e: flask.abort(404) ######################################################################### # # Send various types of HTTP requests # def sendRetrieveRequest(self, url, originator): return self.sendRequest(requests.get, url, originator) def sendCreateRequest(self, url, originator, ty=None, data=None): return self.sendRequest(requests.post, url, originator, ty, data) def sendUpdateRequest(self, url, originator, data): return self.sendRequest(requests.put, url, originator, data=data) def sendDeleteRequest(self, url, originator): return self.sendRequest(requests.delete, url, originator) def sendRequest(self, method, url, originator, ty=None, data=None, ct='application/json'): headers = { 'Content-Type' : '%s%s' % (ct, ';ty=%d' % ty if ty is not None else ''), 'X-M2M-Origin' : originator, 'X-M2M-RI' : Utils.uniqueRI() } try: r = method(url, data=data, headers=headers) except Exception as e: Logging.logWarn('Failed to send request: %s' % str(e)) return (None, C.rcTargetNotReachable) rc = int(r.headers['X-M2M-RSC']) if 'X-M2M-RSC' in r.headers else C.rcInternalServerError return (r.json() if len(r.content) > 0 else None, rc) ######################################################################### def _prepareResponse(self, request, resource, returnCode): if resource is None or returnCode == C.rcDeleted: r = '' elif isinstance(resource, dict): r = json.dumps(resource) else: if (r := resource.asJSON() if isinstance(resource, Resource) else resource) is None: r = '' returnCode = C.rcNotFound Logging.logDebug('Response: \n' + str(r)) resp = make_response(r) # headers resp.headers['X-M2M-RSC'] = str(returnCode) if 'X-M2M-RI' in request.headers: resp.headers['X-M2M-RI'] = request.headers['X-M2M-RI'] if 'X-M2M-RVI' in request.headers: resp.headers['X-M2M-RVI'] = request.headers['X-M2M-RVI'] resp.status_code = self._statusCode(returnCode) resp.content_type = C.hfvContentType return resp # # Mapping of oneM2M return codes to http status codes # _codes = { C.rcOK : 200, # OK C.rcDeleted : 200, # DELETED C.rcUpdated : 200, # UPDATED C.rcCreated : 201, # CREATED C.rcBadRequest : 400, # BAD REQUEST C.rcContentsUnacceptable : 400, # NOT ACCEPTABLE C.rcInsufficientArguments : 400, # INSUFFICIENT ARGUMENTS C.rcInvalidArguments : 400, # INVALID ARGUMENTS C.rcMaxNumberOfMemberExceeded : 400, # MAX NUMBER OF MEMBER EXCEEDED C.rcGroupMemberTypeInconsistent : 400, # GROUP MEMBER TYPE INCONSISTENT C.rcOriginatorHasNoPrivilege : 403, # ORIGINATOR HAS NO PRIVILEGE C.rcInvalidChildResourceType : 403, # INVALID CHILD RESOURCE TYPE C.rcTargetNotReachable : 403, # TARGET NOT REACHABLE C.rcAlreadyExists : 403, # ALREAD EXISTS C.rcTargetNotSubscribable : 403, # TARGET NOT SUBSCRIBABLE C.rcReceiverHasNoPrivileges : 403, # RECEIVER HAS NO PRIVILEGE C.rcNotFound : 404, # NOT FOUND C.rcOperationNotAllowed : 405, # OPERATION NOT ALLOWED C.rcInternalServerError : 500, # INTERNAL SERVER ERROR C.rcNotImplemented : 501, # NOT IMPLEMENTED } def _statusCode(self, sc): return self._codes[sc]
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/HttpServer.py
HttpServer.py
# # Storage.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Store, retrieve and manage resources in the database. It currently relies on # the document database TinyDB. It is possible to store resources either on disc # or just in memory. # from tinydb import TinyDB, Query, where from tinydb.storages import MemoryStorage from tinydb.operations import delete import os, json, re from threading import Lock from Configuration import Configuration from Constants import Constants as C from Logging import Logging from resources.Resource import Resource import Utils class Storage(object): def __init__(self): # create data directory path = None if not Configuration.get('db.inMemory'): if Configuration.has('db.path'): path = Configuration.get('db.path') Logging.log('Using data directory: ' + path) os.makedirs(path, exist_ok=True) else: Logging.logErr('db.path not set') raise RuntimeError('db.path not set') self.db = TinyDBBinding(path) self.db.openDB() # Reset dbs? if Configuration.get('db.resetAtStartup') is True: self.db.purgeDB() Logging.log('Storage initialized') def shutdown(self): self.db.closeDB() Logging.log('Storage shut down') ######################################################################### ## ## Resources ## def createResource(self, resource, overwrite=True): if resource is None: Logging.logErr('resource is None') raise RuntimeError('resource is None') ri = resource.ri # Logging.logDebug('Adding resource (ty: %d, ri: %s, rn: %s)' % (resource['ty'], resource['ri'], resource['rn'])) did = None srn = resource.__srn__ if overwrite: Logging.logDebug('Resource enforced overwrite') self.db.upsertResource(resource) else: # if not self.db.hasResource(ri=ri) and not self.db.hasResource(srn=srn): # Only when not resource does not exist yet if not self.hasResource(ri, srn): # Only when not resource does not exist yet self.db.insertResource(resource) else: Logging.logWarn('Resource already exists (Skipping)') return (False, C.rcAlreadyExists) # Add path to identifiers db self.db.insertIdentifier(resource, ri, srn) return (True, C.rcCreated) # Check whether a resource with either the ri or the srn already exists def hasResource(self, ri, srn): return self.db.hasResource(ri=ri) or self.db.hasResource(srn=srn) # Return a resource via different addressing methods def retrieveResource(self, ri=None, csi=None, srn=None, ty=-1): resources = [] if ri is not None: # get a resource by its ri # Logging.logDebug('Retrieving resource ri: %s' % ri) resources = self.db.searchResources(ri=ri) elif srn is not None: # get a resource by its structured rn # Logging.logDebug('Retrieving resource srn: %s' % srn) # get the ri via the srn from the identifers table resources = self.db.searchResources(srn=srn) elif csi is not None: # get the CSE by its csi # Logging.logDebug('Retrieving resource csi: %s' % csi) resources = self.db.searchResources(csi=csi) elif ty != -1: # get all resources of a specific type # Logging.logDebug('Retrieving all resources ty: %d' % ty) return self.db.searchResources(ty=ty) return Utils.resourceFromJSON(resources[0].copy()) if len(resources) == 1 else None def discoverResources(self, rootResource, handling, conditions, attributes, fo): # preparations rootSRN = rootResource.__srn__ handling['__returned__'] = 0 handling['__matched__'] = 0 if 'lvl' in handling: handling['__lvl__'] = rootSRN.count('/') + handling['lvl'] # a bit of optimization. This length stays the same. allLen = ((len(conditions) if conditions is not None else 0) + (len(attributes) if attributes is not None else 0) + (len(conditions['ty']) if conditions is not None else 0) - 1 + (len(conditions['cty']) if conditions is not None else 0) - 1 ) rs = self.db.discoverResources(lambda r: _testDiscovery(r, rootSRN, handling, conditions, attributes, fo, handling['lim'] if 'lim' in handling else None, handling['ofst'] if 'ofst' in handling else None, allLen)) # transform JSONs to resources result = [] for r in rs: result.append(Utils.resourceFromJSON(r)) # sort resources by type and then by lowercase rn if Configuration.get('cse.sortDiscoveredResources'): result.sort(key=lambda x:(x.ty, x.rn.lower())) return result def updateResource(self, resource): if resource is None: Logging.logErr('resource is None') raise RuntimeError('resource is None') ri = resource.ri # Logging.logDebug('Updating resource (ty: %d, ri: %s, rn: %s)' % (resource['ty'], ri, resource['rn'])) resource = self.db.updateResource(resource) return (resource, C.rcUpdated) def deleteResource(self, resource): if resource is None: Logging.logErr('resource is None') raise RuntimeError('resource is None') # Logging.logDebug('Removing resource (ty: %d, ri: %s, rn: %s)' % (resource['ty'], ri, resource['rn'])) self.db.deleteResource(resource) self.db.deleteIdentifier(resource) return (True, C.rcDeleted) def subResources(self, pi, ty=None): rs = self.db.searchResources(pi=pi, ty=ty) # if ty is not None: # rs = self.tabResources.search((Query().pi == pi) & (Query().ty == ty)) # else: # rs = self.tabResources.search(Query().pi == pi) result = [] for r in rs: result.append(Utils.resourceFromJSON(r.copy())) return result def countResources(self): return self.db.countResources() def identifier(self, ri): return self.db.searchIdentifiers(ri=ri) def searchByTypeFieldValue(self, ty, field, value): """Search and return all resources of a specific type and a value in a field, and return them in an array.""" result = [] for j in self.db.searchByTypeFieldValue(ty, field, value): result.append(Utils.resourceFromJSON(j)) return result ######################################################################### ## ## Subscriptions ## def getSubscription(self, ri): # Logging.logDebug('Retrieving subscription: %s' % ri) subs = self.db.searchSubscriptions(ri=ri) if subs is None or len(subs) != 1: return None return subs[0] def getSubscriptionsForParent(self, pi): # Logging.logDebug('Retrieving subscriptions for parent: %s' % pi) return self.db.searchSubscriptions(pi=pi) def addSubscription(self, subscription): # Logging.logDebug('Adding subscription: %s' % ri) return self.db.upsertSubscription(subscription) def removeSubscription(self, subscription): # Logging.logDebug('Removing subscription: %s' % subscription.ri) return self.db.removeSubscription(subscription) def updateSubscription(self, subscription): # Logging.logDebug('Updating subscription: %s' % ri) return self.db.upsertSubscription(subscription) ######################################################################### ## ## Statistics ## def getStatistics(self): return self.db.searchStatistics() def updateStatistics(self, stats): return self.db.upsertStatistics(stats) ######################################################################### ## ## App Support ## def getAppData(self, id): return self.db.searchAppData(id) def updateAppData(self, data): return self.db.upsertAppData(data) def removeAppData(self, data): return self.db.removeData(data) ######################################################################### ## ## internal utilities ## # handler function for discovery search and matching resources def _testDiscovery(r, rootSRN, handling, conditions, attributes, fo, lim, ofst, allLen): # check limits # TinyDB doesn't support pagination. So we need to implement it here. See also offset below. if lim is not None and handling['__returned__'] >= lim: return False # check for SRN first # Add / to the "startswith" check to terminate the search string if (srn := r['__srn__']) is not None and rootSRN.count('/') >= srn.count('/') or not srn.startswith(rootSRN+'/') or srn == rootSRN: return False # Ignore virtual resources TODO: correct? # if (ty := r.get('ty')) and ty in C.tVirtualResources: # return False ty = r.get('ty') # ignore some resource types if ty in [ C.tGRP_FOPT ]: return False # check level if (h_lvl := handling.get('__lvl__')) is not None and srn.count('/') > h_lvl: return False # check conditions if conditions is not None: found = 0 # found += 1 if (c_ty := conditions.get('ty')) is not None and (str(ty) == c_ty) else 0 if (ct := r.get('ct')) is not None: found += 1 if (c_crb := conditions.get('crb')) is not None and (ct < c_crb) else 0 found += 1 if (c_cra := conditions.get('cra')) is not None and (ct > c_cra) else 0 if (lt := r.get('lt')) is not None: found += 1 if (c_ms := conditions.get('ms')) is not None and (lt > c_ms) else 0 found += 1 if (c_us := conditions.get('us')) is not None and (lt < c_us) else 0 if (st := r.get('st')) is not None: found += 1 if (c_sts := conditions.get('sts')) is not None and (str(st) > c_sts) else 0 found += 1 if (c_stb := conditions.get('stb')) is not None and (str(st) < c_stb) else 0 if (et := r.get('et')) is not None: found += 1 if (c_exb := conditions.get('exb')) is not None and (et < c_exb) else 0 found += 1 if (c_exa := conditions.get('exa')) is not None and (et > c_exa) else 0 # special handling of label-list if (lbl := r.get('lbl')) is not None and (c_lbl := conditions.get('lbl')) is not None: lbla = c_lbl.split() fnd = 0 for l in lbla: fnd += 1 if l in lbl else 0 found += 1 if (fo == 1 and fnd == len(lbl)) or (fo == 2 and fnd > 0) else 0 # fo==or -> find any label if ty in [ C.tCIN, C.tFCNT ]: # special handling for CIN, FCNT if (cs := r.get('cs')) is not None: found += 1 if (sza := conditions.get('sza')) is not None and (str(cs) >= sza) else 0 found += 1 if (szb := conditions.get('szb')) is not None and (str(cs) < szb) else 0 if ty in [ C.tCIN ]: # special handling for CIN if (cnf := r.get('cnf')) is not None: found += 1 if cnf in conditions['cty'] else 0 # TODO labelsQuery # TODO childLabels # TODO parentLabels # TODO childResourceType # TODO parentResourceType # Attributes: if attributes is not None: for name in attributes: val = attributes[name] if '*' in val: val = val.replace('*', '.*') found += 1 if (rval := r.get(name)) is not None and re.match(val, str(rval)) else 0 else: found += 1 if (rval := r.get(name)) is not None and str(val) == str(rval) else 0 # TODO childAttribute # TODO parentAttribute # Test Types found += 1 if str(ty) in conditions['ty'] else 0 # Test whether the OR or AND criteria is fullfilled if not ((fo == 2 and found > 0) or # OR and found something (fo == 1 and allLen == found) # AND and found everything ): return False # Check offset. Dont match if offset not reached handling['__matched__'] += 1 if ofst is not None and handling['__matched__'] <= ofst: return False handling['__returned__'] += 1 return True ######################################################################### # # DB class that implements the TinyDB binding # # This class may be moved later to an own module. class TinyDBBinding(object): def __init__(self, path=None): self.path = path self.cacheSize = Configuration.get('db.cacheSize') Logging.log('Cache Size: %s' % self.cacheSize) # create transaction locks self.lockResources = Lock() self.lockIdentifiers = Lock() self.lockSubscriptions = Lock() self.lockStatistics = Lock() self.lockAppData = Lock() def openDB(self): if Configuration.get('db.inMemory'): Logging.log('DB in memory') self.dbResources = TinyDB(storage=MemoryStorage) self.dbIdentifiers = TinyDB(storage=MemoryStorage) self.dbSubscriptions = TinyDB(storage=MemoryStorage) self.dbStatistics = TinyDB(storage=MemoryStorage) self.dbAppData = TinyDB(storage=MemoryStorage) else: Logging.log('DB in file system') self.dbResources = TinyDB(self.path + '/resources.json') self.dbIdentifiers = TinyDB(self.path + '/identifiers.json') self.dbSubscriptions = TinyDB(self.path + '/subscriptions.json') self.dbStatistics = TinyDB(self.path + '/statistics.json') self.dbAppData = TinyDB(self.path + '/appdata.json') self.tabResources = self.dbResources.table('resources', cache_size=self.cacheSize) self.tabIdentifiers = self.dbIdentifiers.table('identifiers', cache_size=self.cacheSize) self.tabSubscriptions = self.dbSubscriptions.table('subsriptions', cache_size=self.cacheSize) self.tabStatistics = self.dbStatistics.table('statistics', cache_size=self.cacheSize) self.tabAppData = self.dbAppData.table('appdata', cache_size=self.cacheSize) def closeDB(self): Logging.log('Closing DBs') self.dbResources.close() self.dbIdentifiers.close() self.dbSubscriptions.close() self.dbStatistics.close() self.dbAppData.close() def purgeDB(self): Logging.log('Purging DBs') self.tabResources.purge() self.tabIdentifiers.purge() self.tabSubscriptions.purge() self.tabStatistics.purge() self.tabAppData.purge() # # Resources # def insertResource(self, resource): with self.lockResources: self.tabResources.insert(resource.json) def upsertResource(self, resource): with self.lockResources: self.tabResources.upsert(resource.json, Query().ri == resource.ri) # Update existing or insert new when overwriting def updateResource(self, resource): ri = resource.ri with self.lockResources: self.tabResources.update(resource.json, Query().ri == ri) # remove nullified fields from db and resource for k in list(resource.json): if resource.json[k] is None: self.tabResources.update(delete(k), Query().ri == ri) del resource.json[k] return resource def deleteResource(self, resource): with self.lockResources: self.tabResources.remove(Query().ri == resource.ri) def searchResources(self, ri=None, csi=None, srn=None, pi=None, ty=None): # find the ri first and then try again recursively if srn is not None: if len((identifiers := self.searchIdentifiers(srn=srn))) == 1: return self.searchResources(ri=identifiers[0]['ri']) return [] with self.lockResources: if ri is not None: r = self.tabResources.search(Query().ri == ri) elif csi is not None: r = self.tabResources.search(Query().csi == csi) elif pi is not None and ty is not None: r = self.tabResources.search((Query().pi == pi) & (Query().ty == ty)) elif pi is not None: r = self.tabResources.search(Query().pi == pi) elif ty is not None: r = self.tabResources.search(Query().ty == ty) return r def discoverResources(self, func): with self.lockResources: rs = self.tabResources.search(func) return rs def hasResource(self, ri=None, csi=None, srn=None, ty=None): # find the ri first and then try again recursively if srn is not None: if len((identifiers := self.searchIdentifiers(srn=srn))) == 1: return self.hasResource(ri=identifiers[0]['ri']) ret = False with self.lockResources: if ri is not None: ret = self.tabResources.contains(Query().ri == ri) elif csi is not None: ret = self.tabResources.contains(Query().csi == csi) elif ty is not None: ret = self.tabResources.contains(Query().ty == ty) return ret def countResources(self): with self.lockResources: result = len(self.tabResources) return result def searchByTypeFieldValue(self, ty, field, value): """Search and return all resources of a specific type and a value in a field, and return them in an array.""" with self.lockResources: result = self.tabResources.search((Query().ty == ty) & (where(field).any(value))) return result # # Identifiers # def insertIdentifier(self, resource, ri, srn): with self.lockIdentifiers: self.tabIdentifiers.upsert( # ri, rn, srn {'ri' : ri, 'rn' : resource.rn, 'srn' : srn, 'ty' : resource.ty}, Query().ri == ri) def deleteIdentifier(self, resource): with self.lockIdentifiers: self.tabIdentifiers.remove(Query().ri == resource.ri) def searchIdentifiers(self, ri=None, srn=None): with self.lockIdentifiers: if srn is not None: r = self.tabIdentifiers.search(Query().srn == srn) elif ri is not None: r = self.tabIdentifiers.search(Query().ri == ri) return r # # Subscriptions # def searchSubscriptions(self, ri=None, pi=None): subs = None with self.lockSubscriptions: if ri is not None: subs = self.tabSubscriptions.search(Query().ri == ri) if pi is not None: subs = self.tabSubscriptions.search(Query().pi == pi) return subs def upsertSubscription(self, subscription): ri = subscription.ri with self.lockSubscriptions: result = self.tabSubscriptions.upsert( { 'ri' : ri, 'pi' : subscription.pi, 'nct' : subscription.nct, 'net' : subscription['enc/net'], 'nus' : subscription.nu }, Query().ri == ri) return result is not None def removeSubscription(self, subscription): with self.lockSubscriptions: result = self.tabSubscriptions.remove(Query().ri == subscription.ri) return result # # Statistics # def searchStatistics(self): stats = None with self.lockStatistics: stats = self.tabStatistics.get(doc_id=1) return stats if stats is not None and len(stats) > 0 else None def upsertStatistics(self, stats): with self.lockStatistics: if len(self.tabStatistics) > 0: result = self.tabStatistics.update(stats, doc_ids=[1]) else: result = self.tabStatistics.insert(stats) return result is not None # # App Data # def searchAppData(self, id): data = None with self.lockAppData: data = self.tabAppData.get(Query().id == id) return data if data is not None and len(data) > 0 else None def upsertAppData(self, data): if 'id' not in data: return None with self.lockAppData: if len(self.tabAppData) > 0: result = self.tabAppData.update(data, Query().id == data['id']) else: result = self.tabAppData.insert(data) return result is not None def removeAppData(self, data): if 'id' not in data: return None with self.lockAppData: result = self.tabAppData.remove(Query().id == data['id']) return result
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/Storage.py
Storage.py
# # AnnouncementManager.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Managing entity for resource announcements # from Logging import Logging # TODO: This manager will be implemented in the future. # # # Table 9.6.26.1-1: Announced Resource Types # 9.6.26 Resource Announcement # Update to the announcedAttribute attribute in the original resource will trigger new attribute announcement or the de-announcement of the announced attribute(s). # the announced resource shall be created as a direct child of the Hosting CSE’s <remoteCSE> hosted by the announcement target CSE. class AnnouncementManager(object): def __init__(self): Logging.log('AnnouncementManager initialized') def shutdown(self): Logging.log('AnnouncementManager shut down')
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/AnnouncementManager.py
AnnouncementManager.py
# # Dispatcher.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Main request dispatcher. All external and most internal requests are routed # through here. # from Logging import Logging from Configuration import Configuration from Constants import Constants as C import CSE, Utils class Dispatcher(object): def __init__(self): self.rootPath = Configuration.get('http.root') self.enableTransit = Configuration.get('cse.enableTransitRequests') Logging.log('Dispatcher initialized') def shutdown(self): Logging.log('Dispatcher shut down') # The "xxxRequest" methods handle http requests while the "xxxResource" # methods handle actions on the resources. Security/permission checking # is done for requests, not on resource actions. # # Retrieve resources # def retrieveRequest(self, request): (originator, _, _, _, _) = Utils.getRequestHeaders(request) id = Utils.requestID(request, self.rootPath) Logging.logDebug('ID: %s, originator: %s' % (id, originator)) # handle transit requests if CSE.remote.isTransitID(id): return CSE.remote.handleTransitRetrieveRequest(request, id, originator) if self.enableTransit else (None, C.rcOperationNotAllowed) # handle fanoutPoint requests if (fanoutPointResource := Utils.fanoutPointResource(id)) is not None and fanoutPointResource.ty == C.tGRP_FOPT: Logging.logDebug('Redirecting request to fanout point: %s' % fanoutPointResource.__srn__) return fanoutPointResource.retrieveRequest(request, id, originator) # just a normal retrieve request return self.handleRetrieveRequest(request, id, originator) def handleRetrieveRequest(self, request, id, originator): try: attrs = self._getArguments(request) fu = attrs.get('fu') drt = attrs.get('drt') handling = attrs.get('__handling__') conditions = attrs.get('__conditons__') attributes = attrs.get('__attrs__') fo = attrs.get('fo') rcn = attrs.get('rcn') except Exception as e: return (None, C.rcInvalidArguments) if fu == 1 and rcn != C.rcnAttributes: # discovery. rcn == Attributes is actually "normal retrieval" Logging.logDebug('Discover resources (fu: %s, drt: %s, handling: %s, conditions: %s, resultContent: %d, attributes: %s)' % (fu, drt, handling, conditions, rcn, str(attributes))) if rcn not in [C.rcnAttributesAndChildResourceReferences, C.rcnChildResourceReferences, C.rcnChildResources, C.rcnAttributesAndChildResources]: # Only allow those two return (None, C.rcInvalidArguments) # do discovery (rs, _) = self.discoverResources(id, handling, conditions, attributes, fo) if rs is not None: # check and filter by ACP allowedResources = [] for r in rs: if CSE.security.hasAccess(originator, r, C.permDISCOVERY): allowedResources.append(r) if rcn == C.rcnChildResourceReferences: # child resource references return (self._resourcesToURIList(allowedResources, drt), C.rcOK) # quiet strange for discovery, since children might not be direct descendants... elif rcn == C.rcnAttributesAndChildResourceReferences: (resource, res) = self.retrieveResource(id) if resource is None: return (None, res) self._resourceTreeReferences(allowedResources, resource, drt) # the function call add attributes to the result resource return (resource, C.rcOK) # resource and child resources, full attributes elif rcn == C.rcnAttributesAndChildResources: (resource, res) = self.retrieveResource(id) if resource is None: return (None, res) self._childResourceTree(allowedResources, resource) # the function call add attributes to the result resource return (resource, C.rcOK) # direct child resources, NOT the root resource elif rcn == C.rcnChildResources: resource = { } # empty self._resourceTreeJSON(allowedResources, resource) return (resource, C.rcOK) # return (self._childResources(allowedResources), C.rcOK) return (None, C.rcNotFound) elif fu == 2 or rcn == C.rcnAttributes: # normal retrieval Logging.logDebug('Get resource: %s' % id) (resource, res) = self.retrieveResource(id) if resource is None: return (None, res) if not CSE.security.hasAccess(originator, resource, C.permRETRIEVE): return (None, C.rcOriginatorHasNoPrivilege) if rcn == C.rcnAttributes: # Just the resource & attributes return (resource, res) (rs, rc) = self.discoverResources(id, handling, rootResource=resource) if rs is None: return (None, rc) # check and filter by ACP result = [] for r in rs: if CSE.security.hasAccess(originator, r, C.permRETRIEVE): result.append(r) # Handle more sophisticated result content types if rcn == C.rcnAttributesAndChildResources: self._resourceTreeJSON(result, resource) # the function call add attributes to the result resource return (resource, C.rcOK) elif rcn == C.rcnAttributesAndChildResourceReferences: self._resourceTreeReferences(result, resource, drt) # the function call add attributes to the result resource return (resource, C.rcOK) elif rcn == C.rcnChildResourceReferences: # child resource references return (self._resourcesToURIList(result, drt), C.rcOK) return (None, C.rcInvalidArguments) # TODO check rcn. Allowed only 1, 4, 5 . 1= as now. If 4,5 check lim etc else: return (None, C.rcInvalidArguments) def retrieveResource(self, id): Logging.logDebug('Retrieve resource: %s' % id) if id is None: return (None, C.rcNotFound) oid = id csi = Configuration.get('cse.csi') if '/' in id: # when the id is in the format <cse RI>/<resource RI> if id.startswith(csi): id = id[len(csi)+1:] if not '/' in id: return self.retrieveResource(id) # elif id.startswith('-') or id.startswith('~'): # remove shortcut (== csi) (Also the ~ makes it om2m compatible) if id.startswith('-') or id.startswith('~'): # remove shortcut (== csi) (Also the ~ makes it om2m compatible) id = "%s/%s" % (csi, id[2:]) return self.retrieveResource(id) # Check whether it is Unstructured-CSE-relativeResource-ID s = id.split('/') if len(s) == 2 and s[0] == Configuration.get('cse.ri'): # Logging.logDebug('Resource via Unstructured-CSE-relativeResource-ID') r = CSE.storage.retrieveResource(ri=s[1]) else: # Assume it is a Structured-CSE-relativeResource-ID # Logging.logDebug('Resource via Structured-CSE-relativeResource-ID') r = CSE.storage.retrieveResource(srn=id) else: # only the cseid or ri if id == csi: # SP-relative-CSE-ID # Logging.logDebug('Resource via SP-relative-CSE-ID') r = CSE.storage.retrieveResource(csi=id) else: # Unstructured-CSE-relativeResource-ID # Logging.logDebug('Resource via Unstructured-CSE-relativeResource-ID') r = CSE.storage.retrieveResource(ri=id) if r is None: # special handling for CSE. ID could be ri or srn... r = CSE.storage.retrieveResource(srn=id) if r is not None: return (r, C.rcOK) Logging.logDebug('Resource not found: %s' % oid) return (None, C.rcNotFound) def discoverResources(self, id, handling, conditions=None, attributes=None, fo=None, rootResource=None): if rootResource is None: (rootResource, _) = self.retrieveResource(id) if rootResource is None: return (None, C.rcNotFound) return (CSE.storage.discoverResources(rootResource, handling, conditions, attributes, fo), C.rcOK) # # Add resources # def createRequest(self, request): (originator, ct, ty, _, _) = Utils.getRequestHeaders(request) id = Utils.requestID(request, self.rootPath) Logging.logDebug('ID: %s, originator: %s' % (id, originator)) # handle transit requests if CSE.remote.isTransitID(id): return CSE.remote.handleTransitCreateRequest(request, id, originator, ty) if self.enableTransit else (None, C.rcOperationNotAllowed) # handle fanoutPoint requests if (fanoutPointResource := Utils.fanoutPointResource(id)) is not None and fanoutPointResource.ty == C.tGRP_FOPT: Logging.logDebug('Redirecting request to fanout point: %s' % fanoutPointResource.__srn__) return fanoutPointResource.createRequest(request, id, originator, ct, ty) # just a normal create request return self.handleCreateRequest(request, id, originator, ct, ty) def handleCreateRequest(self, request, id, originator, ct, ty): Logging.logDebug('Adding new resource') if ct == None or ty == None: return (None, C.rcBadRequest) # Check whether the target contains a fanoutPoint in between or as the target # TODO: Is this called twice (here + in createRequest)? if (fanoutPointResource := Utils.fanoutPointResource(id)) is not None: Logging.logDebug('Redirecting request to fanout point: %s' % fanoutPointResource.__srn__) return fanoutPointResource.createRequest(request, id, originator, ct, ty) # Get parent resource and check permissions (pr, res) = self.retrieveResource(id) if pr is None: Logging.log('Parent resource not found') return (None, C.rcNotFound) if CSE.security.hasAccess(originator, pr, C.permCREATE, ty=ty, isCreateRequest=True) == False: return (None, C.rcOriginatorHasNoPrivilege) # Add new resource #nr = resourceFromJSON(request.json, pi=pr['ri'], tpe=ty) # Add pi if (nr := Utils.resourceFromJSON(request.json, pi=pr.ri, tpe=ty)) is None: # something wrong, perhaps wrong type return (None, C.rcBadRequest) # # determine and add the srn # nr[nr._srn] = Utils.structuredPath(nr) # check whether the resource already exists if CSE.storage.hasResource(nr.ri, nr.__srn__): Logging.logWarn('Resource already registered') return (None, C.rcAlreadyExists) # Check resource creation if (res := CSE.registration.checkResourceCreation(nr, originator, pr))[1] != C.rcOK: return (None, res[1]) originator = res[0] return self.createResource(nr, pr, originator) def createResource(self, resource, parentResource=None, originator=None): Logging.logDebug('Adding resource ri: %s, type: %d' % (resource.ri, resource.ty)) if parentResource is not None: Logging.logDebug('Parent ri: %s' % parentResource.ri) if not parentResource.canHaveChild(resource): Logging.logWarn('Invalid child resource type') return (None, C.rcInvalidChildResourceType) # if not already set: determine and add the srn if resource.__srn__ is None: resource[resource._srn] = Utils.structuredPath(resource) # add the resource to storage if (res := CSE.storage.createResource(resource, overwrite=False))[1] != C.rcCreated: return (None, res[1]) # Activate the resource # This is done *after* writing it to the DB, because in activate the resource might create or access other # resources that will try to read the resource from the DB. if not (res := resource.activate(originator))[0]: # activate the new resource CSE.storage.deleteResource(resource) return res # Could be that we changed the resource in the activate, therefore write it again if (res := CSE.storage.updateResource(resource))[0] is None: CSE.storage.deleteResource(resource) return res if parentResource is not None: parentResource.childAdded(resource, originator) # notify the parent resource CSE.event.createResource(resource) # send a create event return (resource, C.rcCreated) # everything is fine. resource created. # # Update resources # def updateRequest(self, request): (originator, ct, _, _, _) = Utils.getRequestHeaders(request) id = Utils.requestID(request, self.rootPath) Logging.logDebug('ID: %s, originator: %s' % (id, originator)) # handle transit requests if CSE.remote.isTransitID(id): return CSE.remote.handleTransitUpdateRequest(request, id, originator) if self.enableTransit else (None, C.rcOperationNotAllowed) # handle fanoutPoint requests if (fanoutPointResource := Utils.fanoutPointResource(id)) is not None and fanoutPointResource.ty == C.tGRP_FOPT: Logging.logDebug('Redirecting request to fanout point: %s' % fanoutPointResource.__srn__) return fanoutPointResource.updateRequest(request, id, originator, ct) # just a normal retrieve request return self.handleUpdateRequest(request, id, originator, ct) def handleUpdateRequest(self, request, id, originator, ct): # get arguments try: attrs = self._getArguments(request) rcn = attrs.get('rcn') except Exception as e: return (None, C.rcInvalidArguments) Logging.logDebug('Updating resource') if ct == None: return (None, C.rcBadRequest) # Get resource to update (r, _) = self.retrieveResource(id) if r is None: Logging.log('Resource not found') return (None, C.rcNotFound) if r.readOnly: return (None, C.rcOperationNotAllowed) # check permissions jsn = request.json acpi = Utils.findXPath(jsn, list(jsn.keys())[0] + '/acpi') if acpi is not None: # update of acpi attribute means check for self privileges! updateOrDelete = C.permDELETE if acpi is None else C.permUPDATE if CSE.security.hasAccess(originator, r, updateOrDelete, checkSelf=True) == False: return (None, C.rcOriginatorHasNoPrivilege) if CSE.security.hasAccess(originator, r, C.permUPDATE) == False: return (None, C.rcOriginatorHasNoPrivilege) jsonOrg = r.json.copy() if (result := self.updateResource(r, jsn, originator=originator))[0] is None: return (None, result[1]) (r, rc) = result # only send the diff if rcn == C.rcnAttributes: return result if rcn == C.rcnModifiedAttributes: jsonNew = r.json.copy() result = { r.tpe : Utils.resourceDiff(jsonOrg, jsonNew) } return ( result if rc == C.rcUpdated else None, rc) return (None, C.rcNotImplemented) def updateResource(self, resource, json=None, doUpdateCheck=True, originator=None): Logging.logDebug('Updating resource ri: %s, type: %d' % (resource.ri, resource.ty)) if doUpdateCheck: if not (res := resource.update(json, originator))[0]: return (None, res[1]) else: Logging.logDebug('No check, skipping resource update') return CSE.storage.updateResource(resource) # # Remove resources # def deleteRequest(self, request): (originator, _, _, _, _) = Utils.getRequestHeaders(request) id = Utils.requestID(request, self.rootPath) Logging.logDebug('ID: %s, originator: %s' % (id, originator)) # handle transit requests if CSE.remote.isTransitID(id): return CSE.remote.handleTransitDeleteRequest(id, originator) if self.enableTransit else (None, C.rcOperationNotAllowed) # handle fanoutPoint requests if (fanoutPointResource := Utils.fanoutPointResource(id)) is not None and fanoutPointResource.ty == C.tGRP_FOPT: Logging.logDebug('Redirecting request to fanout point: %s' % fanoutPointResource.__srn__) return fanoutPointResource.deleteRequest(request, id, originator) # just a normal delete request return self.handleDeleteRequest(request, id, originator) def handleDeleteRequest(self, request, id, originator): Logging.logDebug('Removing resource') # get resource to be removed and check permissions (r, _) = self.retrieveResource(id) if r is None: Logging.logDebug('Resource not found') return (None, C.rcNotFound) # if r.readOnly: # return (None, C.rcOperationNotAllowed) if CSE.security.hasAccess(originator, r, C.permDELETE) == False: return (None, C.rcOriginatorHasNoPrivilege) # Check resource deletion if not (res := CSE.registration.checkResourceDeletion(r, originator))[0]: return (None, C.rcBadRequest) # remove resource return self.deleteResource(r, originator) def deleteResource(self, resource, originator=None): Logging.logDebug('Removing resource ri: %s, type: %d' % (resource.ri, resource.ty)) if resource is None: Logging.log('Resource not found') resource.deactivate(originator) # deactivate it first # notify the parent resource parentResource = resource.retrieveParentResource() # (parentResource, _) = self.retrieveResource(resource['pi']) (_, rc) = CSE.storage.deleteResource(resource) CSE.event.deleteResource(resource) # send a delete event if parentResource is not None: parentResource.childRemoved(resource, originator) return (resource, rc) # # Utility methods # def subResources(self, pi, ty=None): return CSE.storage.subResources(pi, ty) def countResources(self): return CSE.storage.countResources() # All resources of a type def retrieveResourcesByType(self, ty): return CSE.storage.retrieveResource(ty=ty) ######################################################################### # # Internal methods # # Get the request arguments, or meaningful defaults. # Only a small subset is supported yet def _getArguments(self, request): result = { } args = request.args.copy() # copy for greedy attributes checking # basic attributes if (fu := args.get('fu')) is not None: fu = int(fu) del args['fu'] else: fu = C.fuConditionalRetrieval result['fu'] = fu if (drt := args.get('drt')) is not None: # 1=strucured, 2=unstructured drt = int(drt) del args['drt'] else: drt = C.drtStructured result['drt'] = drt if (rcn := args.get('rcn')) is not None: rcn = int(rcn) del args['rcn'] else: rcn = C.rcnAttributes if fu == C.fuConditionalRetrieval else C.rcnChildResourceReferences result['rcn'] = rcn # handling conditions handling = {} for c in ['lim', 'lvl', 'ofst']: # integer parameters if c in args: handling[c] = int(args[c]) del args[c] for c in ['arp']: if c in args: handling[c] = args[c] del args[c] result['__handling__'] = handling # conditions conditions = {} # TODO Check ty multiple times. Then -> "ty" : array? # also contentType # Extra dictionary! as in attributes for c in ['crb', 'cra', 'ms', 'us', 'sts', 'stb', 'exb', 'exa', 'lbl', 'lbq', 'sza', 'szb', 'catr', 'patr']: if (x:= args.get(c)) is not None: conditions[c] = x del args[c] # get types (multi) conditions['ty'] = args.getlist('ty') args.poplist('ty') # get contentTypes (multi) conditions['cty'] = args.getlist('cty') args.poplist('cty') result['__conditons__'] = conditions # filter operation if (fo := args.get('fo')) is not None: # 1=AND, 2=OR fo = int(fo) del args['fo'] else: fo = 1 # default result['fo'] = fo # all remaining arguments are treated as matching attributes result['__attrs__'] = args.copy() return result # Create a m2m:uril structure from a list of resources def _resourcesToURIList(self, resources, drt): cseid = '/' + Configuration.get('cse.csi') + '/' lst = [] for r in resources: lst.append(Utils.structuredPath(r) if drt == C.drtStructured else cseid + r.ri) return { 'm2m:uril' : lst } # def _attributesAndChildResources(self, parentResource, resources): # result = parentResource.asJSON() # ch = [] # for r in resources: # ch.append(r.asJSON(embedded=False)) # result[parentResource.tpe]['ch'] = ch # return result # Recursively walk the results and build a sub-resource tree for each resource type def _resourceTreeJSON(self, rs, rootResource): rri = rootResource['ri'] if 'ri' in rootResource else None while True: # go multiple times per level through the resources until the list is empty result = [] handledTy = None idx = 0 while idx < len(rs): r = rs[idx] if rri is not None and r.pi != rri: # only direct children idx += 1 continue if r.ty in [ C.tCNT_OL, C.tCNT_LA, C.tFCNT_OL, C.tFCNT_LA ]: # Skip latest, oldest virtual resources idx += 1 continue if handledTy is None: handledTy = r.ty # this round we check this type if r.ty == handledTy: # handle only resources of the currently handled type result.append(r) # append the found resource rs.remove(r) # remove resource from the original list (greedy), but don't increment the idx rs = self._resourceTreeJSON(rs, r) # check recursively whether this resource has children else: idx += 1 # next resource # add all found resources under the same type tag to the rootResource if len(result) > 0: rootResource[result[0].tpe] = [r.asJSON(embedded=False) for r in result] # TODO not all child resources are lists [...] Handle just to-1 relations else: break # end of list, leave while loop return rs # Return the remaining list # Retrieve child resource referenves of a resource and add them to a new target resource as "children" def _resourceTreeReferences(self, resources, targetResource, drt): if len(resources) == 0: return t = [] for r in resources: if r.ty in [ C.tCNT_OL, C.tCNT_LA, C.tFCNT_OL, C.tFCNT_LA ]: # Skip latest, oldest virtual resources continue t.append({ 'nm' : r['rn'], 'typ' : r['ty'], 'val' : Utils.structuredPath(r) if drt == C.drtStructured else r.ri}) targetResource['ch'] = t # Retrieve full child resources of a resource and add them to a new target resource def _childResourceTree(self, resource, targetResource): if len(resource) == 0: return result = {} self._resourceTreeJSON(resource, result) # rootResource is filled with the result for k,v in result.items(): # copy child resources to result resource targetResource[k] = v
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/Dispatcher.py
Dispatcher.py
# # RemoteCSEManager.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # This entity handles the registration to remote CSEs as well as the management # of remotly registered CSEs in this CSE. It also handles the forwarding of # transit requests to remote CSEs. # import requests, json, urllib from Configuration import Configuration from Logging import Logging from Constants import Constants as C import Utils, CSE from resources import CSR, CSEBase from helpers import BackgroundWorker class RemoteCSEManager(object): def __init__(self): self.csetype = Configuration.get('cse.type') self.isConnected = False self.remoteAddress = Configuration.get('cse.remote.address') self.remoteRoot = Configuration.get('cse.remote.root') self.remoteCseid = Configuration.get('cse.remote.cseid') self.originator = Configuration.get('cse.remote.originator') self.worker = None self.checkInterval = Configuration.get('cse.remote.checkInterval') self.cseCsi = Configuration.get('cse.csi') self.remoteCSEURL = self.remoteAddress + self.remoteRoot + self.remoteCseid self.remoteCSRURL = self.remoteCSEURL + '/' + self.cseCsi Logging.log('RemoteCSEManager initialized') def shutdown(self): self.stop() Logging.log('RemoteCSEManager shut down') # # Connection Monitor # # Start the monitor in a thread. def start(self): if not Configuration.get('cse.enableRemoteCSE'): return; Logging.log('Starting remote CSE connection monitor') self.worker = BackgroundWorker.BackgroundWorker(self.checkInterval, self.connectionMonitorWorker) self.worker.start() # Stop the monitor. Also delete the CSR resources on both sides def stop(self): if not Configuration.get('cse.enableRemoteCSE'): return; Logging.log('Stopping remote CSE connection monitor') # Stop the thread if self.worker is not None: self.worker.stop() # Remove resources if self.csetype in [ C.cseTypeASN, C.cseTypeMN ]: (_, rc) = self._deleteRemoteCSR() # delete remote CSR (csr, rc) = self._retrieveLocalCSR() # retrieve local CSR if rc == C.rcOK: self._deleteLocalCSR(csr[0]) # delete local CSR # # Check the connection, and presence and absence of CSE and CSR in a # thread periodically. # # It works like this for connections for an ASN or MN to the remote CSE: # # Is there is a local <remoteCSE> for a remote <CSEBase>? # - Yes: Is there a remote <remoteCSE>? # - Yes: # - Retrieve the remote <CSEBase>. # - Has the remote <CSEBase> been modified? # - Yes: # - Update the local <remoteCSE> # - Retrieve the local <CSEBase> # - Has the local <CSEBase> been modified? # - Yes: # -Update the remote <remoteCSE> # - No: # - Delete a potential local <remoteCSE> # - Create a remote <remoteCSE> # - Success: # - Retrieve the remote <CSEBase> # - Create a local <remoteCSE> for it # - No: # - Delete a potential remote <remoteCSE> # - Create a new remote <remoteCSE> # - Success: # - Retrieve the remote <CSEBase> # - Create a local <remoteCSE> for it # def connectionMonitorWorker(self): Logging.logDebug('Checking connections to remote CSEs') try: # Check the current state of the connection to the "upstream" CSEs if self.csetype in [ C.cseTypeASN, C.cseTypeMN ]: self._checkOwnConnection() # Check the liveliness of other CSR connections if self.csetype in [ C.cseTypeMN, C.cseTypeIN ]: self._checkCSRLiveliness() except Exception as e: Logging.logErr('Exception: %s' % e) return False return True # Check the connection for this CSE to the remote CSE. def _checkOwnConnection(self): # first check whether there is already a local CSR (localCSR, rc) = self._retrieveLocalCSR() localCSR = localCSR[0] # hopefully, there is only one upstream CSR+ if rc == C.rcOK: (remoteCSR, rc) = self._retrieveRemoteCSR() # retrieve own if rc == C.rcOK: # check for changes in remote CSE (remoteCSE, rc) = self._retrieveRemoteCSE() if rc == C.rcOK: if remoteCSE.isModifiedSince(localCSR): # remote CSE modified self._updateLocalCSR(localCSR, remoteCSE) Logging.log('Local CSR updated') (localCSE, _) = Utils.getCSE() if localCSE.isModifiedSince(remoteCSR): # local CSE modified self._updateRemoteCSR(localCSE) Logging.log('Remote CSR updated') else: # Potential disconnect (_, rc) = self._deleteLocalCSR(localCSR) (remoteCSR, rc) = self._createRemoteCSR() if rc == C.rcCreated: (remoteCSE, rc) = self._retrieveRemoteCSE() if rc == C.rcOK: self._createLocalCSR(remoteCSE) Logging.log('Remote CSE connected') else: Logging.log('Remote CSE disconnected') else: # No local CSR, so try to delete an optional remote one and re-create everything. (_, rc) = self._deleteRemoteCSR() if rc in [C.rcDeleted, C.rcNotFound]: (_, rc) = self._createRemoteCSR() if rc == C.rcCreated: (remoteCSE, rc) = self._retrieveRemoteCSE() if rc == C.rcOK: self._createLocalCSR(remoteCSE) Logging.log('Remote CSE connected') # Check the liveliness of all remote CSE's that are connected to this CSE. # This is done by trying to retrie a remote CSR. If it cannot be retrieved # then the related local CSR is removed. def _checkCSRLiveliness(self): (csrs, rc) = self._retrieveLocalCSR(own=False) for csr in csrs: found = False for url in csr.poa: if Utils.isURL(url): (cse, rc) = self._retrieveRemoteCSE(url='%s/%s' % (url, csr.csi )) if rc != C.rcOK: Logging.logWarn('Remote CSE unreachable. Removing CSR: %s' % csr.rn) CSE.dispatcher.deleteResource(csr) # # Local CSR # def _retrieveLocalCSR(self, csi=None, own=True): #Logging.logDebug('Retrieving local CSR: %s' % csi) csrs = CSE.dispatcher.subResources(pi=Configuration.get('cse.ri'), ty=C.tCSR) if csi is None: csi = self.remoteCseid if own: for csr in csrs: if (c := csr.csi) is not None and c == csi: return ([csr], C.rcOK) return ([None], C.rcBadRequest) else: result = [] for csr in csrs: if (c := csr.csi) is not None and c == csi: continue result.append(csr) return (result, C.rcOK) def _createLocalCSR(self, remoteCSE): Logging.logDebug('Creating local CSR: %s' % remoteCSE.ri) # copy attributes (localCSE, _) = Utils.getCSE() csr = CSR.CSR() # csr['pi'] = localCSE['ri'] csr['pi'] = Configuration.get('cse.ri') self._copyCSE2CSE(csr, remoteCSE) csr['ri'] = remoteCSE.ri # add local CSR return CSE.dispatcher.createResource(csr, localCSE) def _updateLocalCSR(self, localCSR, remoteCSE): Logging.logDebug('Updating local CSR: %s' % localCSR.rn) # copy attributes self._copyCSE2CSE(localCSR, remoteCSE) return CSE.dispatcher.updateResource(localCSR) def _deleteLocalCSR(self, resource): Logging.logDebug('Deleting local CSR: %s' % resource.ri) return CSE.dispatcher.deleteResource(resource) # # Remote CSR # def _retrieveRemoteCSR(self): #Logging.logDebug('Retrieving remote CSR: %s' % self.remoteCseid) (jsn, rc) = CSE.httpServer.sendRetrieveRequest(self.remoteCSRURL, self.originator) if rc not in [C.rcOK]: return (None, rc) return (CSR.CSR(jsn), C.rcOK) def _createRemoteCSR(self): Logging.logDebug('Creating remote CSR: %s' % self.remoteCseid) # get local CSEBase and copy relevant attributes (localCSE, _) = Utils.getCSE() csr = CSR.CSR() self._copyCSE2CSE(csr, localCSE) csr['ri'] = self.cseCsi data = json.dumps(csr.asJSON()) (jsn, rc) = CSE.httpServer.sendCreateRequest(self.remoteCSEURL, self.originator, ty=C.tCSR, data=data) if rc not in [C.rcCreated, C.rcOK]: if rc != C.rcAlreadyExists: Logging.logDebug('Error creating remote CSR: %d' % rc) return (None, rc) Logging.logDebug('Remote CSR created: %s' % self.remoteCseid) return (CSR.CSR(jsn), C.rcCreated) def _updateRemoteCSR(self, localCSE): Logging.logDebug('Updating remote CSR: %s' % remoteCSR.rn) csr = CSR.CSR() self._copyCSE2CSE(csr, localCSE) del csr['acpi'] # remove ACPI (don't provide ACPI in updates...a bit) data = json.dumps(csr.asJSON()) (jsn, rc) = CSE.httpServer.sendUpdateRequest(self.remoteCSRURL, self.originator, data=data) if rc not in [C.rcUpdated, C.rcOK]: if rc != C.rcAlreadyExists: Logging.logDebug('Error updating remote CSR: %d' % rc) return (None, rc) Logging.logDebug('Remote CSR updated: %s' % self.remoteCseid) return (CSR.CSR(jsn), C.rcUpdated) def _deleteRemoteCSR(self): Logging.logDebug('Deleting remote CSR: %s' % self.remoteCseid) (jsn, rc) = CSE.httpServer.sendDeleteRequest(self.remoteCSRURL, self.originator) if rc not in [C.rcDeleted, C.rcOK]: return (None, rc) Logging.log('Remote CSR deleted: %s' % self.remoteCseid) return (None, C.rcDeleted) # # Remote CSE # # Retrieve the remote CSE def _retrieveRemoteCSE(self, url=None): #Logging.logDebug('Retrieving remote CSE: %s' % self.remoteCseid) (jsn, rc) = CSE.httpServer.sendRetrieveRequest(url if url is not None else self.remoteCSEURL, self.originator) if rc not in [C.rcOK]: return (None, rc) return (CSEBase.CSEBase(jsn), C.rcOK) ######################################################################### # # Handling of Transit requests. Forward requests to the resp. remote CSE's. # # Forward a Retrieve request to a remote CSE def handleTransitRetrieveRequest(self, request, id, origin): if (url := self._getForwardURL(id)) is None: return (None, C.rcNotFound) if len(request.args) > 0: # pass on other arguments, for discovery url += '?' + urllib.parse.urlencode(request.args) Logging.log('Forwarding Retrieve/Discovery request to: %s' % url) return CSE.httpServer.sendRetrieveRequest(url, origin) # Forward a Create request to a remote CSE def handleTransitCreateRequest(self, request, id, origin, ty): if (url := self._getForwardURL(id)) is None: return (None, C.rcNotFound) Logging.log('Forwarding Create request to: %s' % url) return CSE.httpServer.sendCreateRequest(url, origin, data=request.data, ty=ty) # Forward a Update request to a remote CSE def handleTransitUpdateRequest(self, request, id, origin): if (url := self._getForwardURL(id)) is None: return (None, C.rcNotFound) Logging.log('Forwarding Update request to: %s' % url) return CSE.httpServer.sendUpdateRequest(url, origin, data=request.data) # Forward a Delete request to a remote CSE def handleTransitDeleteRequest(self, id, origin): if (url := self._getForwardURL(id)) is None: return (None, C.rcNotFound) Logging.log('Forwarding Delete request to: %s' % url) return CSE.httpServer.sendDeleteRequest(url, origin) # Check whether an ID is a targeting a remote CSE via a CSR def isTransitID(self, id): (r, _) = self._getCSRFromPath(id) return r is not None and r.ty == C.tCSR # Get the new target URL when forwarding def _getForwardURL(self, path): (r, pe) = self._getCSRFromPath(path) if r is not None: return '%s/-/%s' % (r.poa[0], '/'.join(pe[1:])) return None # try to get a CSR even from a longer path (only the first 2 path elements are relevant) def _getCSRFromPath(self, id): pathElements = id.split('/') if len(pathElements) <= 2: return (None, None) id = '%s/%s' % (pathElements[0], pathElements[1]) (r, rc) = CSE.dispatcher.retrieveResource(id) return (r, pathElements) ######################################################################### def _copyCSE2CSE(self, target, source): if 'csb' in source: target['csb'] = self.remoteCSEURL if 'csi' in source: target['csi'] = source.csi if 'cst' in source: target['cst'] = source.cst if 'csz' in source: target['csz'] = source.csz if 'lbl' in source: target['lbl'] = source.lbl if 'nl' in source: target['nl'] = source.nl if 'poa' in source: target['poa'] = source.poa if 'rn' in source: target['rn'] = source.rn if 'rr' in source: target['rr'] = source.rr if 'srt' in source: target['srt'] = source.srt if 'srv' in source: target['srv'] = source.srv if 'st' in source: target['st'] = source.st
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/RemoteCSEManager.py
RemoteCSEManager.py
# # BackgroundWorker.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # This class implements a background process. # from Logging import Logging import threading, time class BackgroundWorker(object): def __init__(self, updateIntervall, workerCallback): self.workerUpdateIntervall = updateIntervall self.workerCallback = workerCallback self.doStop = True self.workerThread = None def start(self): Logging.logDebug('Starting worker thread') self.doStop = False self.workerThread = threading.Thread(target=self.work) self.workerThread.setDaemon(True) # Make the thread a daemon of the main thread self.workerThread.start() def stop(self): Logging.log('Stopping worker thread') # Stop the thread self.doStop = True if self.workerThread is not None: self.workerThread.join(self.workerUpdateIntervall + 5) # wait a short time for the thread to terminate self.workerThread = None def work(self): while not self.doStop: if self.workerCallback(): self.sleep() else: self.stop() # self-made sleep. Helps in speed-up shutdown etc divider = 5.0 def sleep(self): for i in range(0, int(self.workerUpdateIntervall * self.divider)): time.sleep(1.0 / self.divider) if self.doStop: break
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/helpers/BackgroundWorker.py
BackgroundWorker.py
# # GRP_FOPT.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: fanOutPoint (virtual resource) # from Constants import Constants as C import CSE from .Resource import * from Logging import Logging from Constants import Constants as C # TODO: # - Handle Group Request Target Members parameter # - Handle Group Request Identifier parameter # LIMIT # Only blockingRequest ist supported class GRP_FOPT(Resource): def __init__(self, jsn=None, pi=None, create=False): super().__init__(C.tsGRP_FOPT, jsn, pi, C.tGRP_FOPT, create=create, inheritACP=True, readOnly=True) if self.json is not None: self.setAttribute('rn', 'fopt') # Enable check for allowed sub-resources def canHaveChild(self, resource): return super()._canHaveChild(resource, []) def retrieveRequest(self, request, id, originator): Logging.logDebug('Retrieving resources from fopt') return CSE.group.foptRequest(C.opRETRIEVE, self, request, id, originator) def createRequest(self, request, id, originator, ct, ty): Logging.logDebug('Creating resources at fopt') return CSE.group.foptRequest(C.opCREATE, self, request, id, originator, ct, ty) def updateRequest(self, request, id, originator, ct): Logging.logDebug('Updating resources at fopt') return CSE.group.foptRequest(C.opUPDATE, self, request, id, originator, ct) def deleteRequest(self, request, id, originator): Logging.logDebug('Deleting resources at fopt') return CSE.group.foptRequest(C.opDELETE, self, request, id, originator)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/GRP_FOPT.py
GRP_FOPT.py
# # BAT.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: mgmtObj:Battery # from .MgmtObj import * from Constants import Constants as C import Utils btsNORMAL = 1 btsCHARGING = 2 btsCHARGING_COMPLETE = 3 btsDAMAGED = 4 btsLOW_BATTERY = 5 btsNOT_INSTALLED = 6 btsUNKNOWN = 7 defaultBatteryLevel = 100 defaultBatteryStatus = btsUNKNOWN class BAT(MgmtObj): def __init__(self, jsn=None, pi=None, create=False): super().__init__(jsn, pi, C.tsBAT, C.mgdBAT, create=create) if self.json is not None: self.setAttribute('btl', defaultBatteryLevel, overwrite=False) self.setAttribute('bts', defaultBatteryStatus, overwrite=False)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/BAT.py
BAT.py
# # Unknown.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: Unknown # # This is the default-capture class for all unknown resources. # This is only for storing the resource, no further processing is done. # from .Resource import Resource class Unknown(Resource): def __init__(self, jsn, ty, root, pi=None, create=False): super().__init__(root, jsn, pi, ty, create=create) # Enable check for allowed sub-resources (ie. all) def canHaveChild(self, resource): return True
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/Unknown.py
Unknown.py
# # ACP.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: AccessControlPolicy # from Constants import Constants as C from .Resource import * import Utils class ACP(Resource): def __init__(self, jsn=None, pi=None, rn=None, create=False): super().__init__(C.tsACP, jsn, pi, C.tACP, create=create, inheritACP=True, rn=rn) # store permissions for easier access self._storePermissions() def validate(self, originator, create=False): if (res := super().validate(originator, create))[0] == False: return res # add admin originator if Configuration.get('cse.acp.addAdminOrignator'): cseOriginator = Configuration.get('cse.originator') if cseOriginator not in self.pv_acor: self.addPermissionOriginator(cseOriginator) if cseOriginator not in self.pvs_acor: self.addSelfPermissionOriginator(cseOriginator) self._storePermissions() return (True, C.rcOK) ######################################################################### # # Permission handlings # def addPermissionOriginator(self, originator): if originator not in self.pv_acor: self.pv_acor.append(originator) self.setAttribute('pv/acr/acor', self.pv_acor) def setPermissionOperation(self, operation): self.pv_acop = operation self.setAttribute('pv/acr/acop', self.pv_acop) def addSelfPermissionOriginator(self, originator): if originator not in self.pvs_acor: self.pvs_acor.append(originator) self.setAttribute('pvs/acr/acor', self.pvs_acor) def setSelfPermissionOperation(self, operation): self.pvs_acop = operation self.setAttribute('pvs/acr/acop', self.pvs_acop) def checkPermission(self, origin, requestedPermission): if requestedPermission & self.pv_acop == 0: # permission not fitting at all return False return 'all' in self.pv_acor or origin in self.pv_acor or requestedPermission == C.permNOTIFY def checkSelfPermission(self, origin, requestedPermission): if requestedPermission & self.pvs_acop == 0: # permission not fitting at all return False return 'all' in self.pvs_acor or origin in self.pvs_acor def _storePermissions(self): self.pv_acop = self.attribute('pv/acr/acop', 0) self.pv_acor = self.attribute('pv/acr/acor', []) self.pvs_acop = self.attribute('pvs/acr/acop', 0) self.pvs_acor = self.attribute('pvs/acr/acor', [])
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/ACP.py
ACP.py
# # FCNT.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: FlexContainer # import sys from Constants import Constants as C import Utils from .Resource import * class FCNT(Resource): def __init__(self, jsn=None, pi=None, fcntType=None, create=False): super().__init__(fcntType, jsn, pi, C.tFCNT, create=create) if self.json is not None: self.setAttribute('cs', 0, overwrite=False) # "current" attributes are added when necessary in the validate() method # Indicates whether this FC has flexContainerInstances. # Might change during the lifetime of a resource. Used for optimization self.hasInstances = False self.ignoreAttributes = [ self._rtype, self._srn, self._node, 'acpi', 'cbs', 'cni', 'cnd', 'cs', 'cr', 'ct', 'et', 'lt', 'mbs', 'mia', 'mni', 'or', 'pi', 'ri', 'rn', 'st', 'ty' ] # Enable check for allowed sub-resources def canHaveChild(self, resource): return super()._canHaveChild(resource, [ C.tCNT, C.tFCNT, C.tSUB ]) def activate(self, originator): super().activate(originator) # TODO Error checking above # register latest and oldest virtual resources Logging.logDebug('Registering latest and oldest virtual resources for: %s' % self.ri) if self.hasInstances: # add latest r = Utils.resourceFromJSON({}, pi=self.ri, acpi=self.acpi, tpe=C.tFCNT_LA) CSE.dispatcher.createResource(r) # add oldest r = Utils.resourceFromJSON({}, pi=self.ri, acpi=self.acpi, tpe=C.tFCNT_OL) CSE.dispatcher.createResource(r) return (True, C.rcOK) # Checking the presentse of cnd and calculating the size def validate(self, originator, create=False): if (res := super().validate(originator, create))[0] == False: return res # No CND? if (cnd := self.cnd) is None or len(cnd) == 0: return (False, C.rcContentsUnacceptable) # Calculate contentSize # This is not at all realistic since this is the in-memory representation # TODO better implementation needed cs = 0 for attr in self.json: if attr in self.ignoreAttributes: continue cs += sys.getsizeof(self[attr]) self['cs'] = cs # # Handle flexContainerInstances # # TODO When cni and cbs is set to 0, then delete mni, mbs, la, ol, and all children if self.mni is not None or self.mbs is not None: self.hasInstances = True # Change the internal flag whether this FC has flexContainerInstances self.addFlexContainerInstance(originator) fci = self.flexContainerInstances() # check mni if self.mni is not None: mni = self.mni fcii = len(fci) i = 0 l = fcii while fcii > mni and i < l: # remove oldest CSE.dispatcher.deleteResource(fci[i]) fcii -= 1 i += 1 changed = True self['cni'] = fcii # Add "current" atribute, if it is not there self.setAttribute('cni', 0, overwrite=False) # check size if self.mbs is not None: fci = self.flexContainerInstances() # get FCIs again (bc may be different now) mbs = self.mbs cbs = 0 for f in fci: # Calculate cbs cbs += f.cs i = 0 l = len(fci) print(fci) while cbs > mbs and i < l: # remove oldest cbs -= fci[i].cs CSE.dispatcher.deleteResource(fci[i]) i += 1 self['cbs'] = cbs # Add "current" atribute, if it is not there self.setAttribute('cbs', 0, overwrite=False) # TODO Remove la, ol, existing FCI when mni etc are not present anymore. # TODO support maxInstanceAge # May have been changed, so store the resource x = CSE.dispatcher.updateResource(self, doUpdateCheck=False) # To avoid recursion, dont do an update check return (True, C.rcOK) # Get all flexContainerInstances of a resource and return a sorted (by ct) list def flexContainerInstances(self): return sorted(CSE.dispatcher.subResources(self.ri, C.tFCI), key=lambda x: (x.ct)) # Add a new FlexContainerInstance for this flexContainer def addFlexContainerInstance(self, originator): Logging.logDebug('Adding flexContainerInstance') jsn = { 'rn' : '%s_%d' % (self.rn, self.st), #'cnd' : self.cnd, 'lbl' : self.lbl, 'ct' : self.lt, 'et' : self.et, 'cs' : self.cs, 'or' : originator } for attr in self.json: if attr not in self.ignoreAttributes: jsn[attr] = self[attr] fci = Utils.resourceFromJSON(jsn = { self.tpe : jsn }, pi = self.ri, tpe = C.tFCI) # no ACPI CSE.dispatcher.createResource(fci)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/FCNT.py
FCNT.py
# # ANI.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: mgmtObj:areaNwkInfo # from .MgmtObj import * from Constants import Constants as C import Utils defaultAreaNwkType = '' class ANI(MgmtObj): def __init__(self, jsn=None, pi=None, create=False): super().__init__(jsn, pi, C.tsANI, C.mgdANI, create=create) if self.json is not None: self.setAttribute('ant', defaultAreaNwkType, overwrite=False)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/ANI.py
ANI.py
# # SWR.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: mgmtObj:Software # from .MgmtObj import * from Constants import Constants as C import Utils statusUninitialized = 0 statusSuccessful = 1 statusFailure = 2 statusInProcess = 3 defaultSoftwareName = 'unknown' defaultVersion = '0.0' defaultURL = 'unknown' defaultStatus = { 'acn' : '', 'sus' : statusUninitialized } class SWR(MgmtObj): def __init__(self, jsn=None, pi=None, create=False): super().__init__(jsn, pi, C.tsSWR, C.mgdSWR, create=create) if self.json is not None: self.setAttribute('vr', defaultVersion, overwrite=False) self.setAttribute('swn', defaultSoftwareName, overwrite=False) self.setAttribute('url', defaultURL, overwrite=False) self.setAttribute('ins', defaultStatus, overwrite=True) self.setAttribute('acts', defaultStatus, overwrite=True) self.setAttribute('in', False, overwrite=True) self.setAttribute('un', False, overwrite=True) self.setAttribute('act', False, overwrite=True) self.setAttribute('dea', False, overwrite=True)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/SWR.py
SWR.py
# # MEM.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: mgmtObj:Memory # from .MgmtObj import * from Constants import Constants as C import Utils defaultMemoryAvailable = 0 defaultMemTotal = 0 class MEM(MgmtObj): def __init__(self, jsn=None, pi=None, create=False): super().__init__(jsn, pi, C.tsMEM, C.mgdMEM, create=create) if self.json is not None: self.setAttribute('mma', defaultMemoryAvailable, overwrite=False) self.setAttribute('mmt', defaultMemTotal, overwrite=False)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/MEM.py
MEM.py
# # FWR.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: mgmtObj:Firmware # from .MgmtObj import * from Constants import Constants as C import Utils statusUninitialized = 0 statusSuccessful = 1 statusFailure = 2 statusInProcess = 3 defaultFirmwareName = 'unknown' defaultVersion = '0.0' defaultURL = 'unknown' defaultUDS = { 'acn' : '', 'sus' : statusUninitialized } class FWR(MgmtObj): def __init__(self, jsn=None, pi=None, create=False): super().__init__(jsn, pi, C.tsFWR, C.mgdFWR, create=create) if self.json is not None: self.setAttribute('vr', defaultVersion, overwrite=False) self.setAttribute('fwn', defaultFirmwareName, overwrite=False) self.setAttribute('url', defaultURL, overwrite=False) self.setAttribute('uds', defaultUDS, overwrite=True) self.setAttribute('ud', False, overwrite=True)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/FWR.py
FWR.py
# # CNT_OL.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: oldest (virtual resource) # from Constants import Constants as C import Utils, CSE from .Resource import * from Logging import Logging class CNT_OL(Resource): def __init__(self, jsn=None, pi=None, create=False): super().__init__(C.tsCNT_OL, jsn, pi, C.tCNT_OL, create=create, inheritACP=True, readOnly=True, rn='ol') # Enable check for allowed sub-resources def canHaveChild(self, resource): return super()._canHaveChild(resource, []) def asJSON(self, embedded=True, update=False, noACP=False): pi = self['pi'] Logging.logDebug('Oldest CIN from CNT: %s' % pi) (pr, _) = CSE.dispatcher.retrieveResource(pi) # get parent rs = pr.contentInstances() # ask parent for all CIN if len(rs) == 0: # In case of none return None return rs[0].asJSON(embedded=embedded, update=update, noACP=noACP) # result is sorted, so take, and return first
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/CNT_OL.py
CNT_OL.py
# # EVL.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: mgmtObj:EventLog # from .MgmtObj import * from Constants import Constants as C import Utils lgtSystem = 1 lgtSecurity = 2 lgtEvent = 3 lgtTrace = 4 lgTPanic = 5 lgstStarted = 1 lgstStopped = 2 lgstUnknown = 3 lgstNotPresent = 4 lgstError = 5 defaultLogTypeId = lgtSystem defaultLogStatus = lgstUnknown class EVL(MgmtObj): def __init__(self, jsn=None, pi=None, create=False): super().__init__(jsn, pi, C.tsEVL, C.mgdEVL, create=create) if self.json is not None: self.setAttribute('lgt', defaultLogTypeId, overwrite=False) self.setAttribute('lgd', '', overwrite=False) self.setAttribute('lgst', defaultLogStatus, overwrite=False) self.setAttribute('lga', False, overwrite=True) self.setAttribute('lgo', False, overwrite=True)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/EVL.py
EVL.py
# # CNT_LA.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: latest (virtual resource) # from Constants import Constants as C import CSE, Utils from .Resource import * from Logging import Logging class CNT_LA(Resource): def __init__(self, jsn=None, pi=None, create=False): super().__init__(C.tsCNT_LA, jsn, pi, C.tCNT_LA, create=create, inheritACP=True, readOnly=True, rn='la') # Enable check for allowed sub-resources def canHaveChild(self, resource): return super()._canHaveChild(resource, []) def asJSON(self, embedded=True, update=False, noACP=False): pi = self['pi'] Logging.logDebug('Latest CIN from CNT: %s' % pi) (pr, _) = CSE.dispatcher.retrieveResource(pi) # get parent rs = pr.contentInstances() # ask parent for all CIN if len(rs) == 0: # In case of none return None return rs[-1].asJSON(embedded=embedded, update=update, noACP=noACP) # result is sorted, so take, and return last
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/CNT_LA.py
CNT_LA.py
# # CNT.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: Container # from Logging import Logging from Configuration import Configuration from Constants import Constants as C import Utils, CSE from .Resource import * class CNT(Resource): def __init__(self, jsn=None, pi=None, create=False): super().__init__(C.tsCNT, jsn, pi, C.tCNT, create=create) if self.json is not None: self.setAttribute('mni', Configuration.get('cse.cnt.mni'), overwrite=False) self.setAttribute('mbs', Configuration.get('cse.cnt.mbs'), overwrite=False) self.setAttribute('cni', 0, overwrite=False) self.setAttribute('cbs', 0, overwrite=False) # Enable check for allowed sub-resources def canHaveChild(self, resource): return super()._canHaveChild(resource, [ C.tCNT, C.tCIN, C.tFCNT, C.tSUB ]) def activate(self, originator): super().activate(originator) # register latest and oldest virtual resources Logging.logDebug('Registering latest and oldest virtual resources for: %s' % self.ri) # add latest r = Utils.resourceFromJSON({}, pi=self.ri, acpi=self.acpi, tpe=C.tCNT_LA) CSE.dispatcher.createResource(r) # add oldest r = Utils.resourceFromJSON({}, pi=self.ri, acpi=self.acpi, tpe=C.tCNT_OL) CSE.dispatcher.createResource(r) # TODO Error checking above return (True, C.rcOK) # Get all content instances of a resource and return a sorted (by ct) list def contentInstances(self): return sorted(CSE.dispatcher.subResources(self.ri, C.tCIN), key=lambda x: (x.ct)) # Handle the addition of new CIN. Basically, get rid of old ones. def childAdded(self, childResource, originator): super().childAdded(childResource, originator) if childResource.ty == C.tCIN: # Validate if child is CIN self.validate(originator) # Handle the removal of a CIN. def childRemoved(self, childResource, originator): super().childRemoved(childResource, originator) if childResource.ty == C.tCIN: # Validate if child was CIN self.validate(originator) # Validating the Container. This means recalculating cni, cbs as well as # removing ContentInstances when the limits are met. def validate(self, originator, create=False): if (res := super().validate(originator, create))[0] == False: return res # retrieve all children cs = self.contentInstances() # Check number of instances mni = self.mni cni = len(cs) i = 0 l = cni while cni > mni and i < l: # remove oldest CSE.dispatcher.deleteResource(cs[i]) cni -= 1 i += 1 self['cni'] = cni # check size cs = self.contentInstances() # get CINs again mbs = self.mbs cbs = 0 for c in cs: # Calculate cbs cbs += c['cs'] i = 0 l = len(cs) while cbs > mbs and i < l: # remove oldest cbs -= cs[i]['cs'] CSE.dispatcher.deleteResource(cs[i]) i += 1 self['cbs'] = cbs # TODO: support maxInstanceAge # Some CNT resource may have been updated, so store the resource CSE.dispatcher.updateResource(self, doUpdateCheck=False) # To avoid recursion, dont do an update check return (True, C.rcOK)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/CNT.py
CNT.py
# # ANDI.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: mgmtObj:areaNwkDeviceInfo # from .MgmtObj import * from Constants import Constants as C import Utils defaultAreaNwkType = '' class ANDI(MgmtObj): def __init__(self, jsn=None, pi=None, create=False): super().__init__(jsn, pi, C.tsANDI, C.mgdANDI, create=create) if self.json is not None: self.setAttribute('dvd', defaultAreaNwkType, overwrite=False) self.setAttribute('dvt', '', overwrite=False) self.setAttribute('awi', '', overwrite=False)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/ANDI.py
ANDI.py
# # CSEBase.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: CSEBase # from Constants import Constants as C from Configuration import Configuration from .Resource import * class CSEBase(Resource): def __init__(self, jsn=None, create=False): super().__init__(C.tsCSEBase, jsn, '', C.tCSEBase, create=create) if self.json is not None: self.setAttribute('ri', 'cseid', overwrite=False) self.setAttribute('rn', 'cse', overwrite=False) self.setAttribute('csi', 'cse', overwrite=False) self.setAttribute('rr', False, overwrite=False) self.setAttribute('srt', C.supportedResourceTypes, overwrite=False) self.setAttribute('csz', C.supportedContentSerializations, overwrite=False) self.setAttribute('srv', C.supportedReleaseVersions, overwrite=False) self.setAttribute('poa', [ Configuration.get('http.address') ], overwrite=False) self.setAttribute('cst', Configuration.get('cse.type'), overwrite=False) # Enable check for allowed sub-resources def canHaveChild(self, resource): return super()._canHaveChild(resource, [ C.tACP, C.tAE, C.tCSR, C.tCNT, C.tFCNT, C.tGRP, C.tNOD, C.tSUB ]) def validate(self, originator, create=False): if (res := super().validate(originator, create))[0] == False: return res # Update the hcl attribute in the hosting node nl = self['nl'] _nl_ = self.__node__ if nl is not None or _nl_ is not None: if nl != _nl_: if _nl_ is not None: (n, _) = CSE.dispatcher.retrieveResource(_nl_) if n is not None: n['hcl'] = None # remve old link CSE.dispatcher.updateResource(n) self[self._node] = nl (n, _) = CSE.dispatcher.retrieveResource(nl) if n is not None: n['hcl'] = self['ri'] CSE.dispatcher.updateResource(n) self[self._node] = nl return (True, C.rcOK)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/CSEBase.py
CSEBase.py
# # CSR.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: RemoteCSE # from Constants import Constants as C from Configuration import Configuration from .Resource import * class CSR(Resource): def __init__(self, jsn=None, pi=None, create=False): super().__init__(C.tsCSR, jsn, pi, C.tCSR, create=create) if self.json is not None: self.setAttribute('csi', 'cse', overwrite=False) self.setAttribute('rr', False, overwrite=False)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/CSR.py
CSR.py
# # DVI.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: mgmtObj:DeviceInfo # from .MgmtObj import * from Constants import Constants as C import Utils defaultDeviceType = 'unknown' defaultModel = "unknown" defaultManufacturer = "unknown" defaultDeviceLabel = "unknown serial id" class DVI(MgmtObj): def __init__(self, jsn=None, pi=None, create=False): super().__init__(jsn, pi, C.tsDVI, C.mgdDVI, create=create) if self.json is not None: self.setAttribute('dty', defaultDeviceType, overwrite=False) self.setAttribute('mod', defaultModel, overwrite=False) self.setAttribute('man', defaultManufacturer, overwrite=False) self.setAttribute('dlb', defaultDeviceLabel, overwrite=False)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/DVI.py
DVI.py
# # SUB.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: Subscription # import random, string from Constants import Constants as C import Utils, CSE from .Resource import * # LIMIT: Only http(s) requests in nu or POA is supported yet class SUB(Resource): def __init__(self, jsn=None, pi=None, create=False): super().__init__(C.tsSUB, jsn, pi, C.tSUB, create=create) if self.json is not None: self.setAttribute('nct', C.nctAll, overwrite=False) # LIMIT TODO: only this notificationContentType is supported now self.setAttribute('enc/net', [ C.netResourceUpdate ], overwrite=False) # TODO expirationCounter # TODO notificationForwardingURI # TODO subscriberURI # Enable check for allowed sub-resources def canHaveChild(self, resource): return super()._canHaveChild(resource, []) def activate(self, originator): # super().activate(originator) # if not (res := self.validate(originator))[0]: # return res if not (result := super().activate(originator))[0]: return result res = CSE.notification.addSubscription(self) return (res, C.rcOK if res else C.rcTargetNotSubscribable) def deactivate(self, originator): super().deactivate(originator) return CSE.notification.removeSubscription(self) def update(self, jsn, originator): (res, rc) = super().update(jsn, originator) if not res: return (res, rc) res = CSE.notification.updateSubscription(self) return (res, C.rcOK if res else C.rcTargetNotSubscribable) def validate(self, originator, create=False): if (res := super().validate(originator, create))[0] == False: return res Logging.logDebug('Validating subscription: %s' % self['ri']) # Check necessary attributes if (nu := self['nu']) is None or not isinstance(nu, list): Logging.logDebug('"nu" attribute missing for subscription: %s' % self['ri']) return (False, C.rcInsufficientArguments) # TODO check other attributes return (True, C.rcOK)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/SUB.py
SUB.py
# # GRP.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: Group # from Constants import Constants as C import Utils from .Resource import * class GRP(Resource): def __init__(self, jsn=None, pi=None, fcntType=None, create=False): super().__init__(C.tsGRP, jsn, pi, C.tGRP, create=create) if self.json is not None: self.setAttribute('mt', C.tMIXED, overwrite=False) self.setAttribute('ssi', False, overwrite=True) self.setAttribute('cnm', 0, overwrite=False) # calculated later self.setAttribute('mid', [], overwrite=False) self.setAttribute('mtv', False, overwrite=True) self.setAttribute('csy', C.csyAbandonMember, overwrite=False) # These attributes are not provided by default: mnm (no default), macp (no default) # optional set: spty, gn, nar # Enable check for allowed sub-resources def canHaveChild(self, resource): return super()._canHaveChild(resource, [ C.tSUB, C.tGRP_FOPT ]) def activate(self, originator, create=False): # super().activate(originator) # if not (result := self.validate(originator))[0]: if not (result := super().activate(originator, create))[0]: return result # add fanOutPoint ri = self['ri'] Logging.logDebug('Registering fanOutPoint resource for: %s' % ri) if not (res := CSE.dispatcher.createResource( Utils.resourceFromJSON({ 'pi' : ri }, acpi=self['acpi'],tpe=C.tGRP_FOPT), self, originator))[0]: return res return (True, C.rcOK) def validate(self, originator, create=False): if (res := super().validate(originator, create))[0] == False: return res if (ret := CSE.group.validateGroup(self, originator))[0]: self['mtv'] = True # validaed CSE.dispatcher.updateResource(self, doUpdateCheck=False) # To avoid recursion, dont do an update check else: self['mtv'] = False # not validateed return ret
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/GRP.py
GRP.py
# # CIN.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: ContentInstance # from Constants import Constants as C from .Resource import * import Utils class CIN(Resource): def __init__(self, jsn=None, pi=None, create=False): super().__init__(C.tsCIN, jsn, pi, C.tCIN, create=create, inheritACP=True, readOnly = True) if self.json is not None: self.setAttribute('con', '', overwrite=False) self.setAttribute('cs', len(self['con'])) # Enable check for allowed sub-resources. No Child for CIN def canHaveChild(self, resource): return super()._canHaveChild(resource, [])
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/CIN.py
CIN.py
# # AE.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: Application Entity # from Constants import Constants as C import Utils from .Resource import * class AE(Resource): def __init__(self, jsn=None, pi=None, create=False): super().__init__(C.tsAE, jsn, pi, C.tAE, create=create) if self.json is not None: self.setAttribute('aei', Utils.uniqueAEI(), overwrite=False) self.setAttribute('rr', False, overwrite=False) # Enable check for allowed sub-resources def canHaveChild(self, resource): return super()._canHaveChild(resource, [ C.tACP, C.tCNT, C.tFCNT, C.tGRP, C.tSUB ]) def validate(self, originator, create=False): if (res := super().validate(originator), create)[0] == False: return res # Update the hcl attribute in the hosting node nl = self['nl'] _nl_ = self.__node__ if nl is not None or _nl_ is not None: if nl != _nl_: ri = self['ri'] # Remove from old node first if _nl_ is not None: (n, _) = CSE.dispatcher.retrieveResource(_nl_) if n is not None: hael = n['hael'] if hael is not None and isinstance(hael, list) and ri in hael: hael.remove(ri) CSE.dispatcher.updateResource(n) self[self._node] = nl # Add to new node (n, _) = CSE.dispatcher.retrieveResource(nl) if n is not None: hael = n['hael'] if hael is None: n['hael'] = [ ri ] else: if isinstance(hael, list): hael.append(ri) n['hael'] = hael CSE.dispatcher.updateResource(n) self[self._node] = nl return (True, C.rcOK)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/AE.py
AE.py
# # FCNT_OL.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: oldest (virtual resource) for flexContainer # from Constants import Constants as C import CSE, Utils from .Resource import * from Logging import Logging class FCNT_OL(Resource): def __init__(self, jsn=None, pi=None, create=False): super().__init__(C.tsFCNT_OL, jsn, pi, C.tFCNT_OL, create=create, inheritACP=True, readOnly=True, rn='ol') # Enable check for allowed sub-resources def canHaveChild(self, resource): return super()._canHaveChild(resource, []) def asJSON(self, embedded=True, update=False, noACP=False): pi = self['pi'] Logging.logDebug('Oldest FCI from FCNT: %s' % pi) (pr, _) = CSE.dispatcher.retrieveResource(pi) # get parent rs = pr.flexContainerInstances() # ask parent for all FCIs if len(rs) == 0: # In case of none return None return rs[0].asJSON(embedded=embedded, update=update, noACP=noACP) # result is sorted, so take, and return first
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/FCNT_OL.py
FCNT_OL.py
# # Resource.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # Base class for all resources # from Logging import Logging from Constants import Constants as C from Configuration import Configuration import Utils, CSE import datetime, random # Future TODO: Check RO/WO etc for attributes (list of attributes per resource?) class Resource(object): _rtype = '__rtype__' _srn = '__srn__' _node = '__node__' def __init__(self, tpe, jsn=None, pi=None, ty=None, create=False, inheritACP=False, readOnly=False, rn=None): self.tpe = tpe self.readOnly = readOnly self.inheritACP = inheritACP self.json = {} if jsn is not None: if tpe in jsn: self.json = jsn[tpe].copy() else: self.json = jsn.copy() else: pass # TODO Exception? if self.json is not None: if self.tpe is None: # and self._rtype in self: self.tpe = self.__rtype__ self.setAttribute('ri', Utils.uniqueRI(self.tpe), overwrite=False) # override rn if given if rn is not None: self.setAttribute('rn', rn, overwrite=True) # Check uniqueness of ri. otherwise generate a new one. Only when creating # TODO: could be a BAD REQUEST? if create: while Utils.isUniqueRI(ri := self.attribute('ri')) == False: Logging.logWarn("RI: %s is already assigned. Generating new RI." % ri) self.setAttribute('ri', Utils.uniqueRI(self.tpe), overwrite=True) # Create an RN if there is none self.setAttribute('rn', Utils.uniqueRN(self.tpe), overwrite=False) # Set some more attributes ts = Utils.getResourceDate() self.setAttribute('ct', ts, overwrite=False) self.setAttribute('lt', ts, overwrite=False) self.setAttribute('et', Utils.getResourceDate(Configuration.get('cse.expirationDelta')), overwrite=False) self.setAttribute('st', 0, overwrite=False) if pi is not None: self.setAttribute('pi', pi, overwrite=False) if ty is not None: self.setAttribute('ty', ty) # ## Note: ACPI is set in activate() # # Remove empty / null attributes from json self.json = {k: v for (k, v) in self.json.items() if v is not None } # determine and add the srn self[self._srn] = Utils.structuredPath(self) self[self._rtype] = self.tpe # Default encoding implementation. Overwrite in subclasses def asJSON(self, embedded=True, update=False, noACP=False): # remove (from a copy) all internal attributes before printing jsn = self.json.copy() for k in [ self._rtype, self._srn, self._node]: if k in jsn: del jsn[k] if noACP: if 'acpi' in jsn: del jsn['acpi'] if update: for k in [ 'ri', 'ty', 'pi', 'ct', 'lt', 'st', 'rn', 'mgd']: del jsn[k] return { self.tpe : jsn } if embedded else jsn # This method is called to to activate a resource. This is not always the # case, e.g. when a resource object is just used temporarly. # NO notification on activation/creation! # Implemented in sub-classes. def activate(self, originator): Logging.logDebug('Activating resource: %s' % self.ri) if not (result := self.validate(originator, create=True))[0]: return result # Note: CR is set in RegistrationManager # Handle ACPI assignments here if self.inheritACP: self.delAttribute('acpi') else: if self.ty != C.tAE: # Don't handle AE's here. This is done in the RegistrationManager #adminACPIRI = Configuration.get('cse.adminACPI') defaultACPIRI = Configuration.get('cse.defaultACPI') if self.acpi is None: self.setAttribute('acpi', [ defaultACPIRI ]) # Set default ACPIRIs #self.setAttribute('acpi', [ adminACPIRI, defaultACPIRI ]) # Set admin and default ACPIRIs # else: # if not adminACPIRI in self.acpi: # self.acpi.append(adminACPIRI) self.setAttribute(self._rtype, self.tpe, overwrite=False) return (True, C.rcOK) # Deactivate an active resource. # Send notification on deletion def deactivate(self, originator): Logging.logDebug('Deactivating and removing sub-resources: %s' % self.ri) # First check notification because the subscription will be removed # when the subresources are removed CSE.notification.checkSubscriptions(self, C.netResourceDelete) # Remove subresources rs = CSE.dispatcher.subResources(self.ri) for r in rs: self.childRemoved(r, originator) CSE.dispatcher.deleteResource(r, originator) # Update this resource with (new) fields. # Call validate() afterward to react on changes. def update(self, jsn=None, originator=None): if jsn is not None: if self.tpe not in jsn: Logging.logWarn("Update types don't match") return (False, C.rcContentsUnacceptable) j = jsn[self.tpe] # get structure under the resource type specifier for key in j: # Leave out some attributes if key in ['ct', 'lt', 'pi', 'ri', 'rn', 'st', 'ty']: continue self[key] = j[key] # copy new value # - state and lt if 'st' in self.json: # Update the state self['st'] += 1 if 'lt' in self.json: # Update the lastModifiedTime self['lt'] = Utils.getResourceDate() # Do some extra validations, if necessary if not (res := self.validate(originator))[0]: return res # Check subscriptions CSE.notification.checkSubscriptions(self, C.netResourceUpdate) return (True, C.rcOK) # Child was added to the resource. def childAdded(self, childResource, originator): CSE.notification.checkSubscriptions(self, C.netCreateDirectChild, childResource) # Child was removed from the resource. def childRemoved(self, childResource, originator): CSE.notification.checkSubscriptions(self, C.netDeleteDirectChild, childResource) # MUST be implemented by each class def canHaveChild(self, resource): raise NotImplementedError('canHaveChild()') # Is be called from child class def _canHaveChild(self, resource, allowedChildResourceTypes): from .Unknown import Unknown # Unknown imports this class, therefore import only here return resource['ty'] in allowedChildResourceTypes or isinstance(resource, Unknown) # Validate a resource. Usually called within activate() or # update() methods. def validate(self, originator=None, create=False): Logging.logDebug('Validating resource: %s' % self.ri) if (not Utils.isValidID(self.ri) or not Utils.isValidID(self.pi) or not Utils.isValidID(self.rn)): Logging.logDebug('Invalid ID ri: %s, pi: %s, rn: %s)' % (self.ri, self.pi, self.rn)) return (False, C.rcContentsUnacceptable) return (True, C.rcOK) ######################################################################### # # Attribute handling # def setAttribute(self, name, value, overwrite=True): Utils.setXPath(self.json, name, value, overwrite) def attribute(self, key, default=None): if '/' in key: # search in path return Utils.findXPath(self.json, key, default) if self.hasAttribute(key): return self.json[key] return default def hasAttribute(self, key): # TODO check sub-elements as well return key in self.json def delAttribute(self, key): if self.hasAttribute(key): del self.json[key] def __setitem__(self, key, value): self.setAttribute(key, value) def __getitem__(self, key): return self.attribute(key) def __delitem__(self, key): self.delAttribute(key) def __contains__(self, key): return self.hasAttribute(key) def __getattr__(self, name): return self.attribute(name) ######################################################################### # # Misc utilities # def __str__(self): return str(self.asJSON()) def __eq__(self, other): return self.ri == other.ri def isModifiedSince(self, other): return self.lt > other.lt def retrieveParentResource(self): (parentResource, _) = CSE.dispatcher.retrieveResource(self.pi) return parentResource
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/Resource.py
Resource.py
# # RBO.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: mgmtObj:Reboot # from .MgmtObj import * from Constants import Constants as C import Utils class RBO(MgmtObj): def __init__(self, jsn=None, pi=None, create=False): super().__init__(jsn, pi, C.tsRBO, C.mgdRBO, create=create) if self.json is not None: self.setAttribute('rbo', False, overwrite=True) self.setAttribute('far', False, overwrite=True)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/RBO.py
RBO.py
# # NOD.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: mgmtObj:Node # import random, string from Constants import Constants as C import Utils, CSE from .Resource import * # TODO Support cmdhPolicy # TODO Support storage class NOD(Resource): def __init__(self, jsn=None, pi=None, create=False): super().__init__(C.tsNOD, jsn, pi, C.tNOD, create=create) if self.json is not None: self.setAttribute('ni', Utils.uniqueID(), overwrite=False) # Enable check for allowed sub-resources def canHaveChild(self, resource): return super()._canHaveChild(resource, [ C.tMGMTOBJ, C.tSUB ])
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/NOD.py
NOD.py
# # FCI.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: FlexContainerInstance # from Constants import Constants as C from .Resource import * import Utils class FCI(Resource): def __init__(self, jsn=None, pi=None, fcntType=None, create=False): super().__init__(fcntType, jsn, pi, C.tFCI, create=create, inheritACP=True, readOnly=True) # Enable check for allowed sub-resources. No Child for CIN def canHaveChild(self, resource): return super()._canHaveChild(resource, [])
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/FCI.py
FCI.py
# # MgmtObj.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: ManagementObject (base class for specializations) # from .Resource import * import Utils class MgmtObj(Resource): def __init__(self, jsn, pi, mgmtObjType, mgd, create=False): super().__init__(mgmtObjType, jsn, pi, C.tMGMTOBJ, create=create) if self.json is not None: self.setAttribute('mgd', mgd, overwrite=True) # Enable check for allowed sub-resources def canHaveChild(self, resource): return super()._canHaveChild(resource, [ C.tSUB ])
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/MgmtObj.py
MgmtObj.py
# # DVC.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: mgmtObj:DeviceCapability # from .MgmtObj import * from Constants import Constants as C import Utils class DVC(MgmtObj): def __init__(self, jsn=None, pi=None, create=False): super().__init__(jsn, pi, C.tsDVC, C.mgdDVC, create=create) if self.json is not None: self.setAttribute('can', 'unknown', overwrite=False) self.setAttribute('att', False, overwrite=False) self.setAttribute('cas', { "acn" : "unknown", "sus" : 0 }, overwrite=False) self.setAttribute('cus', False, overwrite=False)
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/DVC.py
DVC.py
# # FCNT_LA.py # # (c) 2020 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # ResourceType: latest (virtual resource) for flexContainer # from Constants import Constants as C import CSE, Utils from .Resource import * from Logging import Logging class FCNT_LA(Resource): def __init__(self, jsn=None, pi=None, create=False): super().__init__(C.tsFCNT_LA, jsn, pi, C.tFCNT_LA, create=create, inheritACP=True, readOnly=True, rn='la') # Enable check for allowed sub-resources def canHaveChild(self, resource): return super()._canHaveChild(resource, []) def asJSON(self, embedded=True, update=False, noACP=False): pi = self['pi'] Logging.logDebug('Latest FCI from FCNT: %s' % pi) (pr, _) = CSE.dispatcher.retrieveResource(pi) # get parent rs = pr.flexContainerInstances() # ask parent for all FCIs if len(rs) == 0: # In case of none return None return rs[-1].asJSON(embedded=embedded, update=update, noACP=noACP) # result is sorted, so take, and return last
ACME-oneM2M-CSE
/ACME%20oneM2M%20CSE-0.3.0.tar.gz/ACME oneM2M CSE-0.3.0/acme/resources/FCNT_LA.py
FCNT_LA.py