def DBCreateNew(sUsername, sFullName, sAuthType, sPassword, sGeneratePW, sForcePasswordChange, sUserRole, sEmail, sStatus, sGroupArray): try: # TODO: All the password testing, etc. db = catocommon.new_conn() sNewID = catocommon.new_guid() if sAuthType == "local": if sPassword: if sPassword: result, msg = User.ValidatePassword(None, sPassword) if result: sEncPW = "'%s'" % catocommon.cato_encrypt(sPassword) else: return None, msg elif catocommon.is_true(sGeneratePW): sEncPW = "'%s'" % catocommon.cato_encrypt(catocommon.generate_password()) else: return None, "A password must be provided, or check the box to generate one." elif sAuthType == "ldap": sEncPW = " null" sSQL = "insert into users" \ " (user_id, username, full_name, authentication_type, force_change, email, status, user_role, user_password)" \ " values ('" + sNewID + "'," \ "'" + sUsername + "'," \ "'" + sFullName + "'," \ "'" + sAuthType + "'," \ "'" + sForcePasswordChange + "'," \ "'" + (sEmail if sEmail else "") + "'," \ "'" + sStatus + "'," \ "'" + sUserRole + "'," \ "" + sEncPW + "" \ ")" if not db.tran_exec_noexcep(sSQL): if db.error == "key_violation": return None, "A User with that Login ID already exists. Please select another." else: return None, db.error db.tran_commit() if sGroupArray: # if we can't create groups we don't actually fail... for tag in sGroupArray: sql = "insert object_tags (object_type, object_id, tag_name) values (1, '%s','%s')" % (sNewID, tag) if not db.exec_db_noexcep(sql): print "Error creating Groups for new user %s." % sNewID # now it's inserted... lets get it back from the db as a complete object for confirmation. u = User() u.FromID(sNewID) u.AddPWToHistory(sEncPW) return u, None except Exception, ex: raise ex
def DBCreateNew(args): """ Creates a new Asset from an Asset definition. Requires a credential object to be sent along. If not provided, the Asset is created with no credentials. As a convenience, any tags sent along will also be added. """ db = catocommon.new_conn() sAssetID = catocommon.new_guid() sCredentialID = None sStatus = args["Status"] if args["Status"] else "Active" # if a shared credential is provided... we'll look it up. # if we find it by ID or Name, we'll use it. # if not, we'll create it as a local credential if args.get("Credential"): c = Credential() # FromName throws an Exception if it doesn't exist try: # try the id, then name if no id, fail if neither work c.FromName(args["Credential"].get("ID", args["Credential"].get("Name"))) except Exception: # so let's build it from the info provided, and save it! c.FromDict(args["Credential"]) # an asset can only create a local credential, and uses the asset id as the credential name c.Name = sAssetID if c.Username or c.PrivateKey: result = c.DBCreateNew() if not result: return None, "Unable to create Credential." sCredentialID = c.ID sSQL = """insert into asset (asset_id, asset_name, asset_status, address, conn_string, db_name, port, credential_id) values (%s, %s, %s, %s, %s, %s, %s, %s)""" params = (sAssetID, args["Name"], sStatus, args.get("Address"), args.get("ConnString"), args.get("DBName"), args.get("Port"), sCredentialID) if not db.tran_exec_noexcep(sSQL, params): logger.error(db.error) if db.error == "key_violation": return None, "Asset Name [%s] already in use, choose another." % (args.get("Name")) else: return None, db.error db.tran_commit() db.close() # now it's inserted... lets get it back from the db as a complete object for confirmation. a = Asset() a.FromID(sAssetID) a.RefreshTags(args.get("Tags")) return a, None
def DBCreateNew(sAccountName, sAccountNumber, sProvider, sLoginID, sLoginPassword, sIsDefault): try: db = catocommon.new_conn() # if there are no rows yet, make this one the default even if the box isn't checked. if sIsDefault == "0": iExists = -1 sSQL = "select count(*) as cnt from cloud_account" iExists = db.select_col_noexcep(sSQL) if iExists == None: if db.error: db.tran_rollback() return None, "Unable to count Cloud Accounts: " + db.error if iExists == 0: sIsDefault = "1" sNewID = catocommon.new_guid() sPW = (catocommon.cato_encrypt(sLoginPassword) if sLoginPassword else "") sSQL = "insert into cloud_account" \ " (account_id, account_name, account_number, provider, is_default, login_id, login_password, auto_manage_security)" \ " values ('" + sNewID + "'," \ "'" + sAccountName + "'," \ "'" + sAccountNumber + "'," \ "'" + sProvider + "'," \ "'" + sIsDefault + "'," \ "'" + sLoginID + "'," \ "'" + sPW + "'," \ "0)" if not db.tran_exec_noexcep(sSQL): if db.error == "key_violation": sErr = "A Cloud Account with that name already exists. Please select another name." return None, sErr else: return None, db.error # if "default" was selected, unset all the others if sIsDefault == "1": sSQL = "update cloud_account set is_default = 0 where account_id <> '" + sNewID + "'" if not db.tran_exec_noexcep(sSQL): raise Exception(db.error) db.tran_commit() # now it's inserted... lets get it back from the db as a complete object for confirmation. ca = CloudAccount() ca.FromID(sNewID) # yay! return ca, None except Exception, ex: raise ex
def __init__(self): self.ID = catocommon.new_guid() self.Username = None self.Password = None self.SharedOrLocal = None self.Name = None self.Description = None self.Domain = None self.PrivilegedPassword = None self.PrivateKey = None
def __init__(self): self.ID = catocommon.new_guid() self.Name = None self.Description = None self.StormFileType = None self.StormFile = None self.IncludeTasks = False #used for export to xml self.DBExists = None self.OnConflict = "cancel" #the default behavior for all conflicts is to cancel the operation self.Actions = {}
def DrawRegistryItem(self, xe, sXPath): try: html = "" sEncrypt = xe.get("encrypt", "false") # if the node value is empty or encrypted, we still need something to click on to edit the value # if the value length after trimming is 0, # it only has nonprintable chars in it. So, it's empty as far as we are concerned. if xe.text is not None: sNodeValue = (xe.text if len(xe.text.strip()) > 0 else "(empty)") else: sNodeValue = "(empty)" # encrypted placeholder if sEncrypt == "true": sNodeValue = "(********)" # safe for html display sNodeValue = uiCommon.SafeHTML(sNodeValue) sNodeLabel = xe.tag sGroupID = catocommon.new_guid() html += "<div class=\"ui-widget-content ui-corner-tl ui-corner-bl registry_node\" xpath=\"" + sXPath + "\" id=\"" + sGroupID + "\">" html += "<span class=\"registry_node_label editable\" id=\"" + catocommon.new_guid() + "\">" + sNodeLabel + \ "</span> : <span class=\"registry_node_value editable\" id=\"" + catocommon.new_guid() + "\" encrypt=\"" + sEncrypt + "\">" + sNodeValue + "</span>\n" html += "<div class=\"registry_section_header_icons\">" # step header icons html += "<span class=\"registry_node_add_btn pointer\"" \ " xpath=\"" + sXPath + "\">" \ "<img style=\"width:10px; height:10px;\" src=\"static/images/icons/edit_add.png\"" \ " alt=\"\" title=\"Add another...\" /></span>" html += "<span class=\"ui-icon ui-icon-close forceinline registry_node_remove_btn pointer\" xpath_to_delete=\"" + sXPath + "\" id_to_remove=\"" + sGroupID + "\" title=\"Remove\"></span>" html += "</div>" html += "</div>" return html except Exception, ex: raise Exception(ex)
def FromDict(self, cred): try: for k, v in cred.items(): setattr(self, k, v) # if created by args, it may or may not have an ID. # but it needs one. if not self.ID: self.ID = catocommon.new_guid() except Exception, ex: raise ex
def FromArgs(self, sName, sDesc, sUsername, sPassword, sShared, sDomain, sPrivPassword): self.Name = sName self.Description = sDesc self.Username = sUsername self.Password = sPassword self.SharedOrLocal = sShared self.Domain = sDomain self.PrivilegedPassword = sPrivPassword # if created by args, it may or may not have an ID. # but it needs one. if not self.ID: self.ID = catocommon.new_guid()
def AddKeyPair(self, name, private_key, passphrase): if not name: return "KeyPair Name is Required." pk_clause = "'%s'" % (catocommon.cato_encrypt(private_key)) if private_key else "" pp_clause = "'%s'" % (catocommon.cato_encrypt(passphrase)) if passphrase else " null" sql = """insert into clouds_keypair (keypair_id, cloud_id, keypair_name, private_key, passphrase) values (%s, %s, %s, {0}, {1})""".format(pk_clause, pp_clause) db = catocommon.new_conn() db.exec_db(sql, (catocommon.new_guid(), self.ID, name)) db.close()
def DBCreateNew(sProvider, sAccountName, sLoginID, sLoginPassword, sAccountNumber, sDefaultCloud, sIsDefault="0"): db = catocommon.new_conn() # some sanity checks... # 1) is the provider valid? providers = CloudProviders(include_products=False, include_clouds=False) if sProvider not in providers.iterkeys(): raise InfoException("The specified Provider [%s] is not a valid Cloud Provider." % sProvider) # 2) if given, does the 'default cloud' exist c = Cloud() c.FromName(sDefaultCloud) if not c.ID: raise InfoException("The specified default Cloud [%s] is not defined." % sDefaultCloud) # if there are no rows yet, make this one the default even if the box isn't checked. if sIsDefault == "0": sSQL = "select count(*) as cnt from cloud_account" iExists = db.select_col(sSQL) if not iExists: sIsDefault = "1" sNewID = catocommon.new_guid() sPW = (catocommon.cato_encrypt(sLoginPassword) if sLoginPassword else "") sSQL = """insert into cloud_account (account_id, account_name, account_number, provider, is_default, default_cloud_id, login_id, login_password, auto_manage_security) values ('%s','%s','%s','%s','%s','%s','%s','%s',0)""" % (sNewID, sAccountName, sAccountNumber, sProvider, sIsDefault, c.ID, sLoginID, sPW) if not db.tran_exec_noexcep(sSQL): if db.error == "key_violation": raise InfoException("A Cloud Account with that name already exists. Please select another name.") else: raise Exception(db.error) # if "default" was selected, unset all the others if sIsDefault == "1": sSQL = "update cloud_account set is_default = 0 where account_id <> %s" db.tran_exec_noexcep(sSQL, (sNewID)) db.tran_commit() db.close() # now it's inserted... lets get it back from the db as a complete object for confirmation. ca = CloudAccount() ca.FromID(sNewID) # yay! return ca
def DBCreateNew(sCloudName, sProvider, sAPIUrl, sAPIProtocol): try: sSQL = "" sNewID = catocommon.new_guid() sSQL = "insert into clouds (cloud_id, cloud_name, provider, api_url, api_protocol)" \ " values ('" + sNewID + "'," + "'" + sCloudName + "'," + "'" + sProvider + "'," + "'" + sAPIUrl + "'," + "'" + sAPIProtocol + "')" db = catocommon.new_conn() if not db.exec_db_noexcep(sSQL): if db.error == "key_violation": return None, "A Cloud with that name already exists. Please select another name." else: return None, db.error #now it's inserted and in the session... lets get it back from the db as a complete object for confirmation. c = Cloud() c.FromID(sNewID) #yay! return c, None except Exception, ex: raise ex
def GetToken(self): """ returns the Users token if it exists, and an empty string if not """ sql = "select token from api_tokens where user_id = %s" db = catocommon.new_conn() token = db.select_col(sql, (self.ID)) db.close() if not token: # generate a new one token = catocommon.new_guid() now_ts = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') sql = """insert into api_tokens (user_id, token, created_dt) values ('{0}', '{1}', str_to_date('{2}', '%%Y-%%m-%%d %%H:%%i:%%s')) on duplicate key update token='{1}', created_dt=str_to_date('{2}', '%%Y-%%m-%%d %%H:%%i:%%s') """.format(self.ID, token, now_ts) db = catocommon.new_conn() db.exec_db(sql) db.close() return token
def DBCreateNew(sCloudName, sProvider, sAPIUrl, sAPIProtocol, sRegion="", sDefaultAccount=""): db = catocommon.new_conn() sNewID = catocommon.new_guid() sRegion = "'%s'" % sRegion if sRegion else "null" # some sanity checks... # 1) is the provider valid? providers = CloudProviders(include_products=False, include_clouds=False) if sProvider not in providers.iterkeys(): raise InfoException("The specified Provider [%s] is not a valid Cloud Provider." % sProvider) # 2) if given, does the 'default cloud account' exist if sDefaultAccount: ca = CloudAccount() ca.FromName(sDefaultAccount) if not ca.ID: raise InfoException("The specified default Cloud Account [%s] is not defined." % sDefaultAccount) sDefaultAccount = ca.ID sDefaultAccount = "'%s'" % sDefaultAccount if sDefaultAccount else "null" sSQL = """insert into clouds (cloud_id, cloud_name, provider, api_url, api_protocol, region, default_account_id) values ('%s', '%s', '%s', '%s', '%s', %s, %s)""" % (sNewID, sCloudName, sProvider, sAPIUrl, sAPIProtocol, sRegion, sDefaultAccount) if not db.exec_db_noexcep(sSQL): if db.error == "key_violation": raise InfoException("A Cloud with that name already exists. Please select another name.") else: raise Exception(db.error) # now it's inserted and in the session... lets get it back from the db as a complete object for confirmation. c = Cloud() c.FromID(sNewID) c.GetDefaultAccount() # yay! db.close() return c
def DBCreateNew(sName, sEcotemplateID, sAccountID, sDescription="", sStormStatus="", sParameterXML="", sCloudID=""): try: if not sName or not sEcotemplateID or not sAccountID: return None, "Name, Ecotemplate and Cloud Account are required Ecosystem properties." db = catocommon.new_conn() sID = catocommon.new_guid() sSQL = "insert into ecosystem (ecosystem_id, ecosystem_name, ecosystem_desc, account_id, ecotemplate_id," \ " storm_file, storm_status, storm_parameter_xml, storm_cloud_id, created_dt, last_update_dt)" \ " select '" + sID + "'," \ " '" + sName + "'," \ + (" null" if not sDescription else " '" + catocommon.tick_slash(sDescription) + "'") + "," \ " '" + sAccountID + "'," \ " ecotemplate_id," \ " storm_file," \ + (" null" if not sStormStatus else " '" + catocommon.tick_slash(sStormStatus) + "'") + "," \ + (" null" if not sParameterXML else " '" + catocommon.tick_slash(sParameterXML) + "'") + "," \ + (" null" if not sCloudID else " '" + sCloudID + "'") + "," \ " now(), now()" \ " from ecotemplate where ecotemplate_id = '" + sEcotemplateID + "'" if not db.exec_db_noexcep(sSQL): if db.error == "key_violation": return None, "An Ecosystem with that name already exists. Please select another name." else: return None, db.error #now it's inserted and in the session... lets get it back from the db as a complete object for confirmation. e = Ecosystem() e.FromID(sID) #yay! return e, None except Exception, ex: raise Exception(ex)
def __init__(self): self.ID = catocommon.new_guid()
def DrawRegistryNode(self, xeNode, sXPath): try: html = "" sNodeLabel = xeNode.tag dictNodes = {} # if a node has children we'll draw it with some hierarchical styling. # AND ALSO if it's editable, even if it has no children, we'll still draw it as a container. if len(xeNode) > 0: sGroupID = catocommon.new_guid() html += "<div class=\"ui-widget-content ui-corner-bottom registry_section\" id=\"" + sGroupID + "\">" # this section html += " <div class=\"ui-state-default registry_section_header\" xpath=\"" + sXPath + "\">" # header html += " <div class=\"registry_section_header_title editable\" id=\"" + catocommon.new_guid() + "\">" + sNodeLabel + "</div>" html += "<div class=\"registry_section_header_icons\">" # step header icons html += "<span class=\"registry_node_add_btn pointer\"" \ " xpath=\"" + sXPath + "\">" \ "<img style=\"width:10px; height:10px;\" src=\"static/images/icons/edit_add.png\"" \ " alt=\"\" title=\"Add another...\" /></span>" html += "<span class=\"ui-icon ui-icon-close forceinline registry_node_remove_btn pointer\" xpath_to_delete=\"" + sXPath + "\" id_to_remove=\"" + sGroupID + "\" title=\"Remove\"></span>" html += "</div>" #end step header icons html += " </div>" # end header for xeChildNode in list(xeNode): sChildNodeName = xeChildNode.tag sChildXPath = sXPath + "/" + xeChildNode.tag # here's the magic... are there any children nodes here with the SAME NAME? # if so they need an index on the xpath if len(xeNode.findall(sChildNodeName)) > 1: # since the document won't necessarily be in perfect order, # we need to keep track of same named nodes and their indexes. # so, stick each array node up in a lookup table. # is it already in my lookup table? iLastIndex = 0 if dictNodes.has_key(sChildNodeName): # there, increment it and set it iLastIndex = dictNodes[sChildNodeName] + 1 dictNodes[sChildNodeName] = iLastIndex else: # not there, add it iLastIndex = 1 dictNodes[sChildNodeName] = iLastIndex sChildXPath = sChildXPath + "[" + str(iLastIndex) + "]" html += self.DrawRegistryNode(xeChildNode, sChildXPath) html += "</div>" # end section else: html += self.DrawRegistryItem(xeNode, sXPath) return html except Exception, ex: raise Exception(ex)
class Ecosystem(object): ID = catocommon.new_guid() Name = None Description = None StormFile = None AccountID = None EcotemplateID = None EcotemplateName = None #no referenced objects just yet, just the name and ID until we need more. ParameterXML = None CloudID = None StormStatus = None CreatedDate = None LastUpdate = None NumObjects = 0 def FromArgs(self, sName, sDescription, sEcotemplateID, sAccountID): if not sName or not sEcotemplateID or not sAccountID: raise Exception("Error building Ecosystem: Name, Ecotemplate and Cloud Account are required.") self.Name = sName self.Description = sDescription self.EcotemplateID = sEcotemplateID self.AccountID = sAccountID @staticmethod def DBCreateNew(sName, sEcotemplateID, sAccountID, sDescription="", sStormStatus="", sParameterXML="", sCloudID=""): try: if not sName or not sEcotemplateID or not sAccountID: return None, "Name, Ecotemplate and Cloud Account are required Ecosystem properties." db = catocommon.new_conn() sID = catocommon.new_guid() sSQL = "insert into ecosystem (ecosystem_id, ecosystem_name, ecosystem_desc, account_id, ecotemplate_id," \ " storm_file, storm_status, storm_parameter_xml, storm_cloud_id, created_dt, last_update_dt)" \ " select '" + sID + "'," \ " '" + sName + "'," \ + (" null" if not sDescription else " '" + catocommon.tick_slash(sDescription) + "'") + "," \ " '" + sAccountID + "'," \ " ecotemplate_id," \ " storm_file," \ + (" null" if not sStormStatus else " '" + catocommon.tick_slash(sStormStatus) + "'") + "," \ + (" null" if not sParameterXML else " '" + catocommon.tick_slash(sParameterXML) + "'") + "," \ + (" null" if not sCloudID else " '" + sCloudID + "'") + "," \ " now(), now()" \ " from ecotemplate where ecotemplate_id = '" + sEcotemplateID + "'" if not db.exec_db_noexcep(sSQL): if db.error == "key_violation": return None, "An Ecosystem with that name already exists. Please select another name." else: return None, db.error #now it's inserted and in the session... lets get it back from the db as a complete object for confirmation. e = Ecosystem() e.FromID(sID) #yay! return e, None except Exception, ex: raise Exception(ex) finally:
def DBCreateNew(username, fullname, role, password, generatepw, authtype="local", forcechange=1, email=None, status=1, expires=None, groups=None): # TODO: All the password testing, etc. db = catocommon.new_conn() # all sorts of validation if re.match("^[\a-zA-Z0-9_.-@]+$", username) is None: raise Exception("Usernames cannot contain spaces or any characters other than letters, numbers or these chars [_.@-].") newid = catocommon.new_guid() authtype = authtype if authtype else "local" forcechange = 0 if forcechange == 0 or forcechange == "0" else 1 email = email if email else "" encpw = None if authtype == "local": if password: result, msg = User.ValidatePassword(None, password) if result: encpw = catocommon.cato_encrypt(password) else: raise Exception(msg) elif catocommon.is_true(generatepw): encpw = catocommon.cato_encrypt(catocommon.generate_password()) else: raise Exception("A password must be provided, or check the box to generate one.") if role not in ("Administrator", "Developer", "User"): raise Exception("Role must be 'Administrator', 'Developer', or 'User'.") pw2insert = "'%s'" % encpw if encpw else " null" ex2insert = ("str_to_date('{0}', '%%m/%%d/%%Y')".format(expires) if expires else " null") sql = """insert into users (user_id, username, full_name, authentication_type, force_change, email, status, user_role, user_password, expiration_dt) values ('%s', '%s', '%s', '%s', %s, '%s', '%s', '%s', %s, %s)""" % (newid, username, fullname, authtype, forcechange, email, status, role, pw2insert, ex2insert) if not db.tran_exec_noexcep(sql): if db.error == "key_violation": raise Exception("A User with that Login ID already exists. Please select another.") else: raise Exception(db.error) db.tran_commit() if groups: # if we can't create groups we don't actually fail... sql = "select group_concat(tag_name order by tag_name separator ',') as tags from tags" alltags = db.select_col_noexcep(sql) if alltags: alltags = alltags.split(",") for tag in groups: if tag in alltags: sql = "insert object_tags (object_type, object_id, tag_name) values (1, '%s','%s')" % (newid, tag) if not db.exec_db_noexcep(sql): logger.error("Error creating Groups for new user %s." % newid) # now it's inserted... lets get it back from the db as a complete object for confirmation. u = User() u.FromID(newid) u.AddPWToHistory(encpw) db.close() return u
def wmSaveKeyPair(self): try: sKeypairID = uiCommon.getAjaxArg("sKeypairID") sAccountID = uiCommon.getAjaxArg("sAccountID") sName = uiCommon.getAjaxArg("sName") sPK = uiCommon.getAjaxArg("sPK") sPP = uiCommon.getAjaxArg("sPP") if not sName: return "KeyPair Name is Required." sPK = uiCommon.unpackJSON(sPK) bUpdatePK = False if sPK: bUpdatePK = True bUpdatePP = False if sPP and sPP != "!2E4S6789O": bUpdatePP = True if not sKeypairID: # empty id, it's a new one. sPKClause = "" if bUpdatePK: sPKClause = "'" + catocommon.cato_encrypt(sPK) + "'" sPPClause = "null" if bUpdatePP: sPPClause = "'" + catocommon.cato_encrypt(sPP) + "'" sSQL = "insert into cloud_account_keypair (keypair_id, account_id, keypair_name, private_key, passphrase)" \ " values ('" + catocommon.new_guid() + "'," \ "'" + sAccountID + "'," \ "'" + sName.replace("'", "''") + "'," \ + sPKClause + "," \ + sPPClause + \ ")" else: sPKClause = "" if bUpdatePK: sPKClause = ", private_key = '" + catocommon.cato_encrypt( sPK) + "'" sPPClause = "" if bUpdatePP: sPPClause = ", passphrase = '" + catocommon.cato_encrypt( sPP) + "'" sSQL = "update cloud_account_keypair set" \ " keypair_name = '" + sName.replace("'", "''") + "'" \ + sPKClause + sPPClause + \ " where keypair_id = '" + sKeypairID + "'" if not self.db.exec_db_noexcep(sSQL): uiCommon.log(self.db.error) return self.db.error return "" except Exception: uiCommon.log_nouser(traceback.format_exc(), 0) return traceback.format_exc()
def wmSaveKeyPair(self): try: sKeypairID = uiCommon.getAjaxArg("sKeypairID") sAccountID = uiCommon.getAjaxArg("sAccountID") sName = uiCommon.getAjaxArg("sName") sPK = uiCommon.getAjaxArg("sPK") sPP = uiCommon.getAjaxArg("sPP") if not sName: return "KeyPair Name is Required." sPK = uiCommon.unpackJSON(sPK) bUpdatePK = False if sPK: bUpdatePK = True bUpdatePP = False if sPP and sPP != "!2E4S6789O": bUpdatePP = True if not sKeypairID: # empty id, it's a new one. sPKClause = "" if bUpdatePK: sPKClause = "'" + catocommon.cato_encrypt(sPK) + "'" sPPClause = "null" if bUpdatePP: sPPClause = "'" + catocommon.cato_encrypt(sPP) + "'" sSQL = "insert into cloud_account_keypair (keypair_id, account_id, keypair_name, private_key, passphrase)" \ " values ('" + catocommon.new_guid() + "'," \ "'" + sAccountID + "'," \ "'" + sName.replace("'", "''") + "'," \ + sPKClause + "," \ + sPPClause + \ ")" else: sPKClause = "" if bUpdatePK: sPKClause = ", private_key = '" + catocommon.cato_encrypt(sPK) + "'" sPPClause = "" if bUpdatePP: sPPClause = ", passphrase = '" + catocommon.cato_encrypt(sPP) + "'" sSQL = "update cloud_account_keypair set" \ " keypair_name = '" + sName.replace("'", "''") + "'" \ + sPKClause + sPPClause + \ " where keypair_id = '" + sKeypairID + "'" if not self.db.exec_db_noexcep(sSQL): uiCommon.log(self.db.error) return self.db.error return "" except Exception: uiCommon.log_nouser(traceback.format_exc(), 0) return traceback.format_exc()
def FromDict(self, cred): for k, v in cred.items(): setattr(self, k, v) if not self.ID: self.ID = catocommon.new_guid()
def DBCreateNew(sAssetName, sStatus, sDbName, sPort, sAddress, sConnString, tags, credential_update_mode, credential=None): """ Creates a new Asset. Requires a credential object to be sent along. If not provided, the Asset is created with no credentials. As a convenience, any tags sent along will also be added. """ try: db = catocommon.new_conn() sAssetID = catocommon.new_guid() if credential: c = Credential() c.FromDict(credential) sCredentialID = (c.ID if c.ID else "") # there are three CredentialType's # 1) 'selected' = user selected a different credential, just save the credential_id # 2) 'new' = user created a new shared or local credential # 3) 'existing' = same credential, just update the username,description ad password if credential_update_mode == "new": # if it's a local credential, the credential_name is the asset_id. # if it's shared, there will be a name. if c.SharedOrLocal == "1": c.Name = sAssetID result, msg = c.DBCreateNew() if not result: return None, msg elif credential_update_mode == "selected": # user selected a shared credential # remove the local credential if one exists sSQL = """delete from asset_credential where shared_or_local = 1 and credential_id in (select credential_id from asset where asset_id = '%s')""" % sAssetID if not db.tran_exec_noexcep(sSQL): return False, db.error sSQL = "insert into asset" \ " (asset_id, asset_name, asset_status, address, conn_string, db_name, port, credential_id)" \ " values (" \ "'" + sAssetID + "'," \ "'" + sAssetName + "'," \ "'" + sStatus + "'," \ "'" + sAddress + "'," \ "'" + sConnString + "'," \ "'" + sDbName + "'," + \ ("NULL" if sPort == "" else "'" + sPort + "'") + "," \ "'" + sCredentialID + "'" \ ")" if not db.tran_exec_noexcep(sSQL): print db.error if db.error == "key_violation": return None, "Asset Name '" + sAssetName + "' already in use, choose another." else: return None, db.error db.tran_commit() # now it's inserted... lets get it back from the db as a complete object for confirmation. a = Asset() a.FromID(sAssetID) a.RefreshTags(tags) return a, None except Exception, ex: raise ex