def findkeyvaluedict(self, keystr): if (nrm_config["debug"] > 9): utils.nprint("OSCARS: PCE findkeyvaluedict") for keyv in keystr: value = keystr[keyv] if (nrm_config["debug"] > 9): utils.nprint("#KD=", keyv) self.assign(keyv, value)
def sslinfo(): if (nrm_config["debug"] > 0): utils.nprint("SVC: SSLINFO_DN:", request.environ.get('HTTP_X_SSL_CLIENT_S_DN')) #utils.nprint("SSL_0: ", request.__dict__) #utils.nprint("SSL_1: ", request.headers) #utils.nprint("SSL_2: ", request.environ) udn = request.environ.get('HTTP_X_SSL_CLIENT_S_DN') vuser = "******" with mydb_session() as s: results = sensenrm_db.validate_user(s, udn) if results: vuser = "******" return """ MRM-info: {} Version-info: {} NRMHost: {} SSL-Verified: {} SSL-DN: {} IP: {} AUTHZ-USER: {} """.format(title_info, version_info, request.environ.get('HTTP_X_MYHOST'), request.environ.get('HTTP_X_SSL_CLIENT_VERIFY'), request.environ.get('HTTP_X_SSL_CLIENT_S_DN'), request.environ.get('HTTP_X_REAL_IP'), vuser)
def get_token(self, uid, upasswd): if (nrm_config["debug"] > 7): utils.nprint("OSCARS: GetToken") # if oscars_config["default_user"] == None: # raise Exception('Cannot get oscars_config["default_user"]. Edit sensenrm_config.py for oscars_config.default_user') # else: # defaultuser = oscars_config["default_user"] # if oscars_config["default_passwd"] == None: # raise Exception('Cannot get oscars_config["default_passwd"]. Edit sensenrm_config.py for oscars_config.default_passwd') # else: # defaultpasswd = oscars_config["default_passwd"] resp = requests.post(self._surl('/api/account/login'), json={ 'username': uid, 'password': upasswd }, verify=False) if (nrm_config["debug"] > 7): utils.nprint("OSCARS: GetToken DONE: ", resp.status_code) if resp.status_code != 200: if (nrm_config["debug"] > 3): utils.nprint("OSCARS: Token FAILED:", resp._content.decode("utf-8")) raise Exception('OSCARS: Cannot GetToken: {}'.format( resp.status_code)) if (nrm_config["debug"] > 6): utils.nprint("OSCARS: Token_UID: ", uid) utils.nprint("OSCARS: Token:", resp._content.decode("utf-8")) return str(resp._content.decode("utf-8"))
def setLastTime(self): with mydb_session() as s: #last_time = self.get_delayed_time(0) last_time = datetime.now() if (nrm_config["debug"]>2): utils.nprint("MODEL: Set last time: ", last_time) sensenrm_db.update_sys_value(s, "last_model_time", last_time)
def put(self, deltaid): if (nrm_config["debug"] > 3): utils.nprint("SVC: CANCEL PUT ID=", deltaid) utils.nprint("SVC: CANCEL_SSL_DN:", request.environ.get('HTTP_X_SSL_CLIENT_S_DN')) udn = request.environ.get('HTTP_X_SSL_CLIENT_S_DN') with mydb_session() as s: results = sensenrm_db.validate_user(s, udn) if results: status, resp = nrmcancel.cancel(deltaid, udn, "") if status == 200: if (nrm_config["debug"] > 3): utils.nprint("SVC: CANCEL_OK:", status) return {'result': "CANCELED"}, status elif status == 400: if (nrm_config["debug"] > 3): utils.nprint("SVC: CANCELLED_with_400:", status) return {'result': "CANCELED"}, 200 else: if (nrm_config["debug"] > 3): utils.nprint("SVC: CANCEL_FAILED:", status) return {'result': "FAILED", 'mesg': str(resp)}, status else: return { 'result': str("FAILED"), 'mesg': str("UNAUTHORIZED_USER") }, 403 return {'result': True}, 200
def get_delayed_time(self, delay_hours): mytime1 = datetime.now(self.utc) if delay_hours != 0: future_date = mytime1 + timedelta(hours=delay_hours) mytime1 = future_date if (nrm_config["debug"] > 7): utils.nprint("DELTA: new DELAYED time=", mytime1) ''' adays = int((mytime1.hour+delay_hours) / 24) amonth=0 year=0 days=0 months=0 daycomp = 30 if (mytime1.month == 2): daycomp = 28 if (mytime1.day+adays > daycomp): amonth=1 days=mytime1.day + adays - daycomp else: days=mytime1.day + adays if ((mytime1.month+amonth) > 12): year=1 months = mytime1.month + amonth - 12 else: months = mytime1.month + amonth hours = delay_hours - 24*(int(delay_hours/24)) if (nrm_config["debug"]>7): utils.nprint("DELTA: DELAYED time=", mytime1.hour) utils.nprint("DELTA: DELAYED input=", delay_hours) utils.nprint("DELTA: DELAYED days=", days) utils.nprint("DELTA: DELAYED hours=", hours) mytime1=datetime(mytime1.year+year, months, days, mytime1.hour+hours, mytime1.minute, mytime1.second, tzinfo=self.utc) ''' return mytime1
def __init__(self): self.obj=" " #self.last_time = self.get_delayed_time(-1) if "l3vpn_model_insert" in nrm_service: utils.nprint(("nrm_service_L3VPN_insert:" + nrm_service["l3vpn_model_insert"])) self.l3vpnPath = nrm_service["l3vpn_model_insert"] else: utils.nprint("nrm_service_L3VPN_insert_does_not_exist")
def convert_str_to_datetime(self, mystr): if (nrm_config["debug"] > 6): utils.nprint("DELTA: convert_time: ", mystr) date_with_tz = mystr date_str, tz = date_with_tz[:-5], date_with_tz[-5:] dt_utc = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%f") dt = dt_utc.replace(tzinfo=self.FixedOffset(tz)) return dt
def __init__(self): if (nrm_config["debug"] > 3): utils.nprint("SVC: DELTAS INIT") self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('id', type=str, location='json') self.reqparse.add_argument('lastModified', type=str, location='json') self.reqparse.add_argument('modelId', type=str, location='json') self.reqparse.add_argument('reduction', type=str, location='json') self.reqparse.add_argument('addition', type=str, location='json') super(DeltasAPI, self).__init__()
def get_unixtime_from_deltatime(date_with_tz): date_str, tz = date_with_tz[:-5], date_with_tz[-5:] dt_utc = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%f") dt = dt_utc.replace(tzinfo=FixedOffset(tz)) if (nrm_config["debug"] > 9): utils.nprint("OSCARS: datetime=", dt) myutime1 = get_unixtime_from_datetime(dt) if (nrm_config["debug"] > 9): utils.nprint("OSCARS: unixtime=", myutime1) return myutime1
def writeModel(self, nrm_uuid, modelcontent): timed_file = datetime.fromtimestamp(time.mktime(datetime.now().timetuple())).strftime('%Y%m%d-%H%M%S') output_file = self.basePath+"/model_" + str(timed_file) + "_" + str(nrm_uuid) + ".txt" if (nrm_config["debug"]>3): utils.nprint("MODEL: OUTPUT_PATH=", output_file) fo = open(output_file, 'w') fo.write(modelcontent) fo.close() return True
def getDelta(self, nrm_uuid): inputdelta = basePath + "/delta_" + nrm_uuid + ".txt" if not os.path.isfile(inputdelta): if (nrm_config["debug"] > 7): utils.nprint("SUMM: no such delta input file: ", nrm_uuid, " in ", basePath) exit() fi = fileinput.FileInput(inputdelta) deltacontent = fi.readline() return deltacontent
def json_parser(self, jstr): for key in jstr: valuestr = jstr[key] myjunction = nrm_junction(key) if (nrm_config["debug"] > 9): utils.nprint("#KEY=", key) if (type(valuestr) is dict): myjunction.findkeyvaluedict(valuestr) else: if (nrm_config["debug"] > 9): utils.nprint("#VALUE=", valuestr) self.junctions.append(myjunction) return self.junctions
def findkeyvaluelist(self, keystr): if (len(keystr) == 0): if (nrm_config["debug"] > 9): utils.nprint("VL=0") else: keystri = iter(keystr) for value in keystri: if (type(value) is dict): self.findkeyvaluedict(value) elif (type(value) is list): self.findkeyvaluelist(value) else: if (nrm_config["debug"] > 9): utils.nprint("VL=", value)
def info(): if (nrm_config["debug"] > 2): #utils.nprint("SVC: INFO_1: ", request.__dict__) utils.nprint("SVC: INFO_2: ", request.headers) #utils.nprint("SVC: INFO_3: ", request.environ) return """ MRM-info: {} Version-info: {} NRMHost: {} IP: {} """.format(title_info, version_info, request.environ.get('HTTP_X_MYHOST'), request.environ.get('HTTP_X_REAL_IP'))
def writeAvail(self, mytime, acontent): timed_file = datetime.fromtimestamp( time.mktime(datetime.now().timetuple())).strftime('%Y%m%d-%H%M%S') output_file = log_config["basepath"] + "/avail_" + str( timed_file) + "_" + str(mytime) + ".txt" if (nrm_config["debug"] > 2): utils.nprint("OSCARS: AVAIL_OUTPUT_PATH=", output_file) fo = open(output_file, 'w') fo.write(acontent) fo.close() return True
def get(self): if (nrm_config["debug"] > 3): utils.nprint("SVC: ALL_DELTAS GET: ", request.environ.get('HTTP_X_SSL_CLIENT_S_DN')) udn = request.environ.get('HTTP_X_SSL_CLIENT_S_DN') with mydb_session() as s: isauthz = sensenrm_db.validate_user(s, udn) if isauthz: alldeltas = sensenrm_db.get_all_active_deltas(s, udn) rstatus = 200 return {'deltas': str(alldeltas)}, rstatus else: return {'deltas': str("UNAUTHORIZED_USER")}, 403
def get_commit(self, connid, groupid): with mydb_session() as s: thisToken = sensenrm_db.get_group_token(s, groupid) if (thisToken is None): raise Exception( 'OSCARS: COMMIT Cannot get Token : {}'.format(groupid)) myheaders = {'authentication': thisToken} if (nrm_config["debug"] > 7): utils.nprint("OSCARS: COMMIT_ID=", connid) resp = requests.post(self._surl('/protected/conn/commit'), connid, verify=False, headers=myheaders) if (nrm_config["debug"] > 7): utils.nprint("OSCARS: COMMIT DONE: ", resp.status_code) if resp.status_code != 200: if (nrm_config["debug"] > 3): utils.nprint("OSCARS: COMMIT FAILED: ", resp._content.decode("utf-8")) raise Exception('OSCARS Cannot COMMIT: {}'.format( resp.status_code)) if (nrm_config["debug"] > 3): utils.nprint("OSCARS: COMMIT: ", resp._content.decode("utf-8")) return resp.status_code, resp._content.decode("utf-8")
def get_bandwidth(devicename): for a in flist: ja = a.id.split(':')[0] if (devicename == ja): if (nrm_config["debug"] > 7): utils.nprint("OSCARS: HELD devicename_found=", a.port_urn) return (int)( swdict[a.port_urn + ":" + str(a.vlan_id)].reservedbw / 1000000) if (nrm_config["debug"] > 7): utils.nprint("OSCARS: HELD devicename_not_found=", devicename) # it should not be here return -1
def get_conn_id(self, groupid): # e.g. groupid = "default" with mydb_session() as s: thisToken = sensenrm_db.get_group_token(s, groupid) if (thisToken is None): raise Exception( 'OSCARS: ConnID Cannot get Token : {}'.format(groupid)) myheaders = {'authentication': thisToken} if (nrm_config["debug"] > 7): utils.nprint("OSCARS: ConnID") resp = requests.get(self._surl('/protected/conn/generateId'), verify=False, headers=myheaders) if (nrm_config["debug"] > 7): utils.nprint("OSCARS: ConnID DONE: ", resp.status_code) if resp.status_code != 200: if (nrm_config["debug"] > 3): utils.nprint("OSCARS: ConnID FAILED: ", resp._content.decode("utf-8")) raise Exception('OSCARS: Cannot GetConnID : {}'.format( resp.status_code)) if (nrm_config["debug"] > 3): utils.nprint("OSCARS: ConnID: ", str(resp._content, "utf-8")) #utils.nprint("ConnID TYPE: ", type(resp._content)) with mydb_session() as s: sensenrm_db.insert_conn(s, resp._content.decode("utf-8"), groupid) return str(resp._content.decode("utf-8"))
def findkeyvaluelistza(self, keystr): if (nrm_config["debug"] > 9): utils.nprint("OSCARS: PCE findkeyvaluelistza") if (len(keystr) == 0): if (nrm_config["debug"] > 9): utils.nprint("#VLza=") else: if (nrm_config["debug"] > 9): utils.nprint("#MYLISTza: ", keystr) keystri = iter(keystr) for value in keystri: if (nrm_config["debug"] > 9): utils.nprint("#KL2za=", value) for keyv in value: myurnvalue = value[keyv] if (nrm_config["debug"] > 9): utils.nprint("#LISTza: ", keyv, "=", myurnvalue) self.zaEro.append(str(myurnvalue))
def get_delayed_time(self, delay_days): tZERO = timedelta(0) class UTC(tzinfo): def utcoffset(self, dt): return tZERO def tzname(self, dt): return "UTC" def dst(self, dt): return tZERO utc = UTC() mytime1=datetime.now(utc) if delay_days != 0: future_date = mytime1 + timedelta(days=delay_days) if (nrm_config["debug"]>3): utils.nprint("MODEL: new Delayed days=", future_date) mytime1 = future_date return mytime1
def assign(self, key, value): def azEro(): if (nrm_config["debug"] > 9): utils.nprint("#azEro=", value) self.findkeyvaluelistaz(value) def zaEro(): if (nrm_config["debug"] > 9): utils.nprint("#zaEro=", value) self.findkeyvaluelistza(value) def cost(): if (nrm_config["debug"] > 9): utils.nprint("#cost", value) self.cost = float(value) def azAvailable(): if (nrm_config["debug"] > 9): utils.nprint("#azAvailable", value) self.azAvailable = int(value) def zaAvailable(): if (nrm_config["debug"] > 9): utils.nprint("#zaAvailable", value) self.zaAvailable = int(value) def azBaseline(): if (nrm_config["debug"] > 9): utils.nprint("#azBaseline", value) self.azBaseline = int(value) def zaBaseline(): if (nrm_config["debug"] > 9): utils.nprint("#zaBaseline", value) self.zaBaseline = int(value) options = { "cost": cost, "azEro": azEro, "zaEro": zaEro, "azAvailable": azAvailable, "zaAvailable": zaAvailable, "azBaseline": azBaseline, "zaBaseline": zaBaseline, } if key in options: # OLD: if options.has_key(key): options[key]() else: if (nrm_config["debug"] > 9): utils.nprint("OSCARS: PCE assign NONE")
def put(self): if (nrm_config["debug"] > 3): utils.nprint("SVC: ALL_CANCEL PUT: ", request.environ.get('HTTP_X_SSL_CLIENT_S_DN')) udn = request.environ.get('HTTP_X_SSL_CLIENT_S_DN') with mydb_session() as s: results = sensenrm_db.validate_user(s, udn) if results: status, allids = nrmcancel.cancelall(udn) if (nrm_config["debug"] > 3): utils.nprint("SVC: ALL_CANCEL:", status) return {'result': str(status), 'deltas': str(allids)}, 200 else: return { 'result': str("FAILED"), 'mesg': str("UNAUTHORIZED_USER") }, 403 return {'result': False}, 201
def floor(): if (nrm_config["debug"] > 9): utils.nprint("#floor=", value) self.vlanr.floor = value if (self.vlanr.floor is 0): if (nrm_config["debug"] > 9): utils.nprint("##floor=ZERO?") else: if (self.vlanr.ceiling is not 0): self.vlanRanges.append(self.vlanr) self.vlanr = nrm_vlanRange() if (nrm_config["debug"] > 9): utils.nprint("##floor=", self.vlanr.floor) else: if (nrm_config["debug"] > 9): utils.nprint("##floor_ceiling=HUH?")
def getAvailOK(self): tZERO = timedelta(0) class UTC(tzinfo): def utcoffset(self, dt): return tZERO def tzname(self, dt): return "UTC" def dst(self, dt): return tZERO utc = UTC() #t21 = datetime.now(utc) t21 = datetime.now() t21 = t21.replace(microsecond=0) with mydb_session() as s: last_time = sensenrm_db.get_sys_lasttime(s) model_change = sensenrm_db.get_sys_lastchange(s) if (nrm_config["debug"]>2): utils.nprint("MODEL: current time: ", t21) utils.nprint("MODEL: Since last time: ", last_time) tdiff = t21 - last_time if (nrm_config["debug"]>2): utils.nprint("MODEL: Avail in: ", (nrm_service["poll_duration"]*60) - tdiff.total_seconds()) #if tdiff.total_seconds() < (nrm_service["poll_duration"]*60): if (model_change == 1) or (tdiff.total_seconds() > (nrm_service["poll_duration"]*60)): return True else: return False
def get_info(self): if (nrm_config["debug"] > 7): utils.nprint("OSCARS: Info") resp = requests.get(self._surl('/api/topo/version'), verify=False) if (nrm_config["debug"] > 7): utils.nprint("OSCARS: Info DONE: ", resp.status_code) if resp.status_code != 200: if (nrm_config["debug"] > 3): utils.nprint("OSCARS: Info FAILED:", resp._content.decode("utf-8")) raise Exception('OSCARS: Cannot get_info: {}'.format( resp.status_code)) if (nrm_config["debug"] > 6): utils.nprint("OSCARS: Info:", resp._content.decode("utf-8")) return str(resp._content.decode("utf-8"))
def __init__(self): # current=true&summary=false&encode=false if (nrm_config["debug"] > 3): utils.nprint("SVC:MODELS INIT") #request.environ.get('HTTP_X_MYHOST') #request.environ.get('HTTP_X_SSL_CLIENT_VERIFY') #request.environ.get('HTTP_X_SSL_CLIENT_S_DN') #request.environ.get('HTTP_X_REAL_IP') utils.nprint("SVC: MODEL_SSL_DN:", request.environ.get('HTTP_X_SSL_CLIENT_S_DN')) utils.nprint("SVC: MODEL_SSL_IP:", request.environ.get('HTTP_X_REAL_IP')) #udn = request.environ.get('HTTP_X_SSL_CLIENT_S_DN') #with mydb_session() as s: # results = sensenrm_db.validate_user(s, udn) # if results: # self.reqparse = reqparse.RequestParser() # self.reqparse.add_argument('current', type = str, default = "true") # self.reqparse.add_argument('summary', type = str, default = "false") # self.reqparse.add_argument('encode', type = str, default = "false") # self.models = nrmmodels.getModel() # if (nrm_config["debug"]>3): utils.nprint("SVC: MODELS INIT DONE") # else: # self.models = "UNAUTHORIZED_USER" super(ModelsAPI, self).__init__()
def ceiling(): if (nrm_config["debug"] > 9): utils.nprint("#ceiling=", value) self.vlanr.ceiling = value if (self.vlanr.ceiling is 0): if (nrm_config["debug"] > 9): utils.nprint("##ceiling=ZERO?") else: if (self.vlanr.floor is not 0): self.vlanRanges.append(self.vlanr) self.vlanr = nrm_vlanRange() if (nrm_config["debug"] > 9): utils.nprint("##ceiling", self.vlanr.ceiling) else: if (nrm_config["debug"] > 9): utils.nprint("##ceiling_floor=ZERO")
def get(self): if (nrm_config["debug"] > 3): utils.nprint("SVC: MODELS GET") udn = request.environ.get('HTTP_X_SSL_CLIENT_S_DN') with mydb_session() as s: results = sensenrm_db.validate_user(s, udn) if results: mymodels, status = nrmmodels.getModel() #mymodels,last_modtime,status = nrmmodels.getModel() if (nrm_config["debug"] > 3): utils.nprint("SVC: MODELS INIT DONE") if status: if (nrm_config["debug"] > 3): utils.nprint("SVC: MODELS RETURNED") #if (nrm_config["debug"]>9): utils.nprint(mymodels) return marshal(mymodels, model_fields) #mycontent = marshal(mymodels, model_fields) #myresp = make_response(jsonify(mycontent)) #myresp.status_code = 200 #return myresp else: if (nrm_config["debug"] > 3): utils.nprint("SVC: MODELS NO_CHANGES HERE") return marshal(mymodels, model_fields) #return {'model': str("NO_CHANGES")}, 304 #my_lasttime = time_rfc1123_from_datetime(last_modtime) #mymodels = [{"id":str(""),"href":str(""),"creationTime":str(time_rfc1123()),"model":str("")}] #mycontent = marshal(mymodels, model_fields) #myresp = make_response(jsonify(mycontent)) #myresp.headers["Last-Modified"] = str(my_lasttime) #myresp.headers["content-type"] = "application/json" #myresp.status_code = 200 ##myresp.status_code = 304 #return myresp else: mymodels = "UNAUTHORIZED_USER" if (nrm_config["debug"] > 3): utils.nprint("SVC: MODELS 403 INVALID_USER") return {'model': str("UNAUTHORIZED_USER")}, 403