Beispiel #1
0
 def associate_defns(self, site_id, group_id, def_type, def_ids, auth, op_level=None):
     error_desc = ''
     site = self.manager.getSite(site_id)
     group = self.manager.getGroup(auth, group_id)
     group_list = self.manager.getGroupList(auth, site_id)
     def_id_list = def_ids.split(',')
     for def_id in def_id_list:
         new_sd = DBSession.query(StorageDef).filter_by(id=def_id).first()
         node = None
         sp_ids = group_id
         try:
             self.sync_manager.add_defn(new_sd, site, group, node, auth, to_unicode(constants.STORAGE), constants.ATTACH, 'ADD_STORAGE_DEF', self.storage_manager, self.manager, op_level, sp_ids)
         except Exception as ex:
             error_desc = to_str(ex)
             print_traceback()
             LOGGER.error(to_str(ex).replace("'", ''))
             add_mode = True
             try:
                 self.sync_manager.remove_defn(new_sd, site, group, node, auth, to_unicode(constants.STORAGE), constants.DETACH, 'REMOVE_STORAGE_DEF', self.storage_manager, self.manager, add_mode, group_list, op_level)
             except Exception as ex1:
                 print_traceback()
                 LOGGER.error(to_str(ex1).replace("'", ''))
                 raise Exception(to_str(ex1))
             if error_desc:
                 raise Exception(error_desc)
     return {'success':True,'msg':'Storage Added'}
Beispiel #2
0
 def on_add_node(self, nodeId, groupId, site_id, auth, def_manager):
     op = constants.ATTACH
     if not(nodeId or groupId):
         return None
     defn_list = []
     errs = []
     sync_manager = SyncDef()
     defType = def_manager.getType()
     sp_defns = DBSession.query(SPDefLink).filter_by(group_id=to_unicode(groupId))
     if sp_defns:
         for eachdefn in sp_defns:
             defn = def_manager.get_defn(eachdefn.def_id)
             if defn:
                 defn_list.append(defn)
                 status = to_unicode(constants.OUT_OF_SYNC)
                 details = None
                 sync_manager.add_node_defn(nodeId, defn.id, defType, status, details)
     node = DBSession.query(ManagedNode).filter_by(id=nodeId).first()
     if node:
         update_status = True
         try:
             sync_manager.sync_node(defn_list, node, groupId, site_id, auth, defType, op, def_manager, update_status, errs)
         except Exception as ex:
             if errs:
                 if len(errs)>0:
                     LOGGER.error('Error in syncing definition while adding node: ' + to_str(errs))
Beispiel #3
0
 def set_transient_state(self, defn, transient_state, op, site_id=None, group_id=None, node_id=None):
     scope = defn.scope
     if op==constants.SCOPE_LEVEL:
         if scope == constants.SCOPE_S:
             def_link = DBSession.query(ServerDefLink).filter_by(server_id=node_id, def_id=defn.id).first()
         else:
             if scope == constants.SCOPE_SP:
                 def_link = DBSession.query(SPDefLink).filter_by(group_id=group_id, def_id=defn.id).first()
             else:
                 if scope == constants.SCOPE_DC:
                     def_link = DBSession.query(DCDefLink).filter_by(site_id=site_id, def_id=defn.id).first()
         if def_link:
             if transient_state:
                 def_link.transient_state = to_unicode(transient_state)
             else:
                 def_link.transient_state = None
             LOGGER.info('Transient state of ' + to_str(defn.name) + ' is changed to ' + to_str(transient_state) + ' at definition scope level')
     if op==constants.NODE_LEVEL:
         def_link = DBSession.query(ServerDefLink).filter_by(server_id=node_id, def_id=defn.id).first()
         if def_link:
             if transient_state:
                 def_link.transient_state = to_unicode(transient_state)
             else:
                 def_link.transient_state = None
             LOGGER.info('Transient state of ' + to_str(defn.name) + ' is changed to ' + to_str(transient_state) + ' at node level')
Beispiel #4
0
    def create_vmw_server_pool(self, auth, name, actual_name, moid, vcenter_id, parent_ent=None):
        msg = ''
        entityType = to_unicode(constants.SERVER_POOL)
        sp = None
        update_name = False
        sp_ent = auth.get_entity_by_entity_attributes(self.get_entity_attributes_dict(vcenter_id, moid), entityType)
        if not sp_ent:
            dup_ent = auth.get_entity_by_name(name, entityType=entityType)
            if dup_ent:
                msg += '\nERROR: Could not import Server Pool:%s. It is already exist,please choose different name' % name
                return (msg, None, None)

        if sp_ent:
            update_name = self.can_update_managed_object_name(auth, name, actual_name, sp_ent.name)
            msg += '\nServer Pool: %s already exist' % name
            sp = DBSession.query(VMWServerGroup).filter(VMWServerGroup.id == sp_ent.entity_id).first()
            if sp:
                if update_name:
                    sp.name = name
        if not sp:
            msg += '\nCreating Server Pool: %s' % name
            sp = VMWServerGroup(name)
        DBSession.add(sp)
        if not sp_ent:
            cntx = {'external_manager_id': vcenter_id, 'external_id': moid}
            sp_ent = self.add_vcenter_entity(auth, cntx, sp.name, sp.id, to_unicode(constants.SERVER_POOL), parent_ent)
        else:
            if not update_name:
                name = None
            auth.update_entity(sp_ent, name=name, parent=parent_ent)
        return (msg, sp, sp_ent)
Beispiel #5
0
 def update_disks_size(self, auth):
     from stackone.model.availability import AvailState
     sites = DBSession.query(Site)
     if sites:
         for eachsite in sites:
             site_entity = auth.get_entity(eachsite.id)
             group_entities = auth.get_entities(to_unicode(constants.SERVER_POOL), site_entity)
             for eachgroup in group_entities:
                 group = DBSession.query(ServerGroup).filter_by(id=eachgroup.entity_id).first()
                 if group:
                     group_entity = auth.get_entity(group.id)
                     node_entities = auth.get_entities(to_unicode(constants.MANAGED_NODE), group_entity)
                     for eachnode in node_entities:
                         node = DBSession.query(ManagedNode).filter_by(id=eachnode.entity_id).first()
                         is_node_up = True
                         objAvailState = DBSession.query(AvailState).filter_by(entity_id=node.id).first()
                         if objAvailState:
                             avail_state = objAvailState.avail_state
                             if avail_state == node.DOWN:
                                 is_node_up = False
                         if is_node_up:
                             server_def_link = DBSession.query(ServerDefLink).filter_by(server_id=node.id)
                             if server_def_link:
                                 for each_link in server_def_link:
                                     defn = DBSession.query(StorageDef).filter_by(id=each_link.def_id).first()
                                     if defn:
                                         if defn.type == constants.NFS or defn.type == constants.OCFS or defn.type == constants.CIFS or defn.type == constants.GFS:
                                             scan_result = self.test_storage_def(auth, node, group, eachsite, defn)
                                             self.update_size(defn, scan_result)
Beispiel #6
0
 def add_role(self, rolename, roledesc, type):
     rolename = to_unicode(rolename)
     roledesc = to_unicode(roledesc)
     role = self.user_info.get_role(rolename)
     if role == None:
         result = self.model_controller.add_role(rolename, roledesc, type, None, True)
     else:
         result = dict(False, 'The role with rolename ' + rolename + ' already exists')
     return result
Beispiel #7
0
 def add_node_defn(self, node_id, def_id, def_type, status, details):
     row = DBSession.query(ServerDefLink).filter_by(server_id=node_id, def_id=def_id).first()
     if not row:
         node_defn = ServerDefLink()
         node_defn.server_id = to_unicode(node_id)
         node_defn.def_type = to_unicode(def_type)
         node_defn.def_id = def_id
         node_defn.status = to_unicode(status)
         node_defn.details = to_unicode(details)
         node_defn.dt_time = datetime.now()
         DBSession.add(node_defn)
Beispiel #8
0
 def is_selected(self, auth, external_id, external_manager_id, type, parent_ent=None):
     entityType = None
     if type in ('HostSystem',):
         entityType = to_unicode(constants.MANAGED_NODE)
     elif type in ('ClusterComputeResource', 'Folder'):
         entityType = to_unicode(constants.SERVER_POOL)
     elif type in ('Datacenter',):
         entityType = to_unicode(constants.DATA_CENTER)
     ent = auth.get_entity_by_entity_attributes(self.get_entity_attributes_dict(external_manager_id, external_id), entityType, parent_ent)
     if ent:
         return True
     return False
Beispiel #9
0
 def save_email_setup_details(self, desc, servername, port, useremail, password, secure):
     SiteRecord = DBSession.query(Site).filter(Site.name == 'Data Center').first()
     if SiteRecord:
         site_id = SiteRecord.id
         EmailRecord = DBSession.query(EmailSetup).filter(EmailSetup.site_id == site_id).filter(EmailSetup.mail_server == servername).first()
         if EmailRecord:
             return dict(success=True, msg='Duplicaate Record found in list')
         else:
             email_setup_obj = EmailSetup(servername, desc, port, secure, site_id, useremail, password)
             DBSession.add(email_setup_obj)
             emailsetupid = email_setup_obj.getEmailSetupId()
             EmailManager().add_entity(to_unicode(servername), emailsetupid, to_unicode(constants.EMAIL), None)
             return dict(success=True, msg='New Record Added Sucessfully')
Beispiel #10
0
 def add_defn(self, defn, site, group, node, auth, defType, op, action_op, def_manager, grid_manager, op_level, sp_ids=None, scan_result=None, csep_id=None):
     scope = op_level
     if scope == constants.SCOPE_S:
         entityId = node.id
     elif scope == constants.SCOPE_SP:
         entityId = group.id
     elif scope == constants.SCOPE_DC:
         entityId = site.id
     elif scope == constants.SCOPE_CP:
         entityId = csep_id
     ent = auth.get_entity(entityId)
     if not auth.has_privilege(action_op, ent):
         raise Exception(constants.NO_PRIVILEGE)
     if scope == constants.SCOPE_SP:
         if not PrivilegeOps.check_child_privileges(auth, action_op, ent):
             raise Exception(constants.NO_CHILD_PRIVILEGE % ('Servers', 'Server Pool'))
     DBSession.add(defn)
     nw_id = defn.id
     if site:
         def_manager.SaveScanResult(defn.id, grid_manager, scan_result, site.id)
     def_manager.RemoveScanResult(scan_result)
     errs = []
     details = {}
     status = to_unicode(constants.OUT_OF_SYNC)
     if scope == constants.SCOPE_DC:
         oos_count = 0
         status = to_unicode(constants.IN_SYNC)
         self.add_site_defn(site.id, defn.id, defType, status, oos_count)
         def_manager.manage_defn_to_groups(site, group, sp_ids, defn, defType, op, def_manager, auth, errs, grid_manager)
     elif scope == constants.SCOPE_SP:
         def_manager.manage_defn_to_groups(site, group, sp_ids, defn, defType, op, def_manager, auth, errs, grid_manager)
     elif scope == constants.SCOPE_S:
         self.add_node_defn(node.id, defn.id, defType, status, details)
         update_status = True
         #def_manager.add_private_ip_pool(defn)
         self.sync_node_defn(auth, node, group.id, site.id, defn, defType, op, def_manager, update_status, errs)
         
     elif scope == constants.SCOPE_CP:
         oos_count = 0
         status = to_unicode(constants.IN_SYNC)
         self.add_csep_defn(csep_id, defn.id, defType, status, oos_count)
         def_manager.manage_defn_to_groups(site, group, sp_ids, defn, defType, op, def_manager, auth, errs, grid_manager, csep_id)
         details['defn_id'] = defn.id
         if node:
             details['node_id'] = node.id
     def_manager.on_defn_creation(auth,**details)
     def_manager.Recompute(defn)
     if errs:
         if len(errs) > 0:
             LOGGER.error('Error:' + to_str(errs))
     return (errs, nw_id)
Beispiel #11
0
 def get_valid_sd(self, type, options, scope, added_manually=False):
     creds_req = False
     creds = {}
     conn_options = {}
     if type == constants.iSCSI:
         creds_req = True
         creds['username'] = options.get('username')
         creds['password'] = options.get('password')
         conn_options['server'] = options.get('portal')
         conn_options['target'] = options.get('target')
         conn_options['options'] = options.get('options')
         conn_options['username'] = options.get('username')
         conn_options['password'] = options.get('password')
     if type == constants.NFS:
         conn_options['server'] = options.get('server')
         conn_options['share'] = options.get('share')
         conn_options['mount_point'] = options.get('mount_point')
         conn_options['mount_options'] = options.get('mount_options')
     if type == constants.AOE:
         conn_options['interface'] = options.get('interface')
     if type == constants.LVM:
         conn_options['volume_group'] = options.get('volume_group')
     if type == constants.CIFS:
         conn_options['server'] = options.get('server')
         conn_options['windows_share'] = options.get('windows_share')
         conn_options['mount_point'] = options.get('mount_point')
         conn_options['windows_username'] = options.get('windows_username')
         conn_options['windows_password'] = options.get('windows_password')
         conn_options['domain'] = options.get('domain')
     if type == constants.GFS:
         conn_options['device'] = options.get('device')
         conn_options['mount_point'] = options.get('mount_point')
     if type == constants.OCFS:
         conn_options['device'] = options.get('device')
         conn_options['mount_point'] = options.get('mount_point')
     if type == constants.FC:
         conn_options['host_adapter'] = options.get('host_adapter')
         conn_options['bus_channel'] = options.get('bus_channel')
         conn_options['target'] = options.get('target')
         conn_options['lun'] = options.get('lun')
     conn_options['added_manually'] = added_manually
     new_sd = StorageDef(None, to_unicode(options.get('name')), type, to_unicode(options.get('description')), conn_options, scope, creds_req)
     if creds_req == True:
         new_sd.set_creds(creds)
     if options['total_cap']!='null':
         options['total_cap'] = str(options.get('total_cap')).strip()
         if options['total_cap']:
             total_cap = str(options.get('total_cap'))
             if not total_cap:
                 total_cap=0
     return new_sd
Beispiel #12
0
 def set_standby(self, standby=False):
     if standby == False or standby == None:
         self.standby_status = None
     else:
         if standby == True:
             self.standby_status = to_unicode(self.STANDBY)
     return None
Beispiel #13
0
    def add_rep(self, entity, parent):
        propagate = True
        import tg
        is_granular = tg.config.get(constants.GRANULAR_USER_MODEL)

        if is_granular!='True':
            propagate = False
        else:
            is_granular = True
        role_ids = []
        if propagate  and (self.user is not None or self.groups is not None):
            roles = self.get_user_roles()
            r = DBHelper().find_by_name(Role, to_unicode(constants.DEFAULT_ROLES[0]))
            if r not in roles:
                roles.append(r)

            role_ids=[role.id for role in roles]
        reps = self.get_all_rep(parent, role_ids,is_granular)
        for rep in reps:
            new_rep = RoleEntityPrivilege()
            new_rep.privilege = rep.privilege
            prop = True
            if is_granular and rep.role.id not in role_ids:
                prop = rep.propagate
            new_rep.propagate = prop
            new_rep.role = rep.role
            new_rep.entity = entity
            DBHelper().add(new_rep)
Beispiel #14
0
 def getCandidateData(self, auth, ctx, standby=False):
     sp = auth.get_entity(self._group.id)
     child_ents = auth.get_entities(to_unicode(constants.MANAGED_NODE), parent=sp)
     if ctx.exclude_ids is not None:
         ctx.exclude_ids.append(ctx.node_id)
     else:
         ctx.exclude_ids = []
         ctx.exclude_ids.append(ctx.node_id)
     LOGGER.error('exclude_ids======' + str(ctx.exclude_ids))
     ids = [child_ent.entity_id for child_ent in child_ents if child_ent.entity_id not in ctx.exclude_ids]
     nodelist = DBHelper().filterby(ManagedNode,[], [ManagedNode.id.in_(ids)])
     load_time = self._group.getGroupVarValue('SERVER_LOAD_TIME')
     try:
         load_time = int(load_time)
     except Exception as e:
         load_time = 0
     list = []
     LOGGER.error('Begining initial placement on ' + self._group.name)
     for n in nodelist:
         if n.is_maintenance():
             LOGGER.info('Node %s in Maintenance mode' % n.hostname)
         count_check = self.checkVmLimit(n.id, self._group)
         if count_check == True:
             if n.is_standby() == standby and self.filter_node(n,ctx) and n.current_state.avail_state == ManagedNode.UP and not n.is_maintenance():
                 metrics = n.get_raw_metrics(load_time)
                 cpu_info = n.get_cpu_info()
                 nr_cpus = int(cpu_info.get(constants.key_cpu_count , 1))
                 vcpus = n.get_vcpu_count()
                 free_mem = int(n.get_memory_info().get(constants.key_memory_free,0))
                 list.append((metrics['VM_TOTAL_CPU(%)'], metrics['VM_TOTAL_MEM(%)'], vcpus / nr_cpus, n.get_VM_count(), -free_mem, n, n.hostname))
     LOGGER.error('Capable nodes:\n ' + to_str(list))
     LOGGER.error('Finishing initial placement on ' + self._group.name)
     if len(list) == 0:
         return None
     return min(list)
Beispiel #15
0
 def add_vcenter_entity(self, auth, context_dict, ent_name, ent_id, ent_type, parent_ent):
     external_manager_id = context_dict.get('external_manager_id')
     external_id = context_dict.get('external_id')
     ent_cntx_dict = self.get_entity_context_dict(external_manager_id=external_manager_id, external_id=external_id)
     ent = auth.add_entity(ent_name, ent_id, to_unicode(ent_type), parent_ent, context=ent_cntx_dict)
     ent_attr_dict = self.get_entity_attributes_dict(external_manager_id=external_manager_id, external_id=external_id)
     self.add_entity_attributes(ent, ent_attr_dict)
     return ent
Beispiel #16
0
 def has_privilege(self, opname, entity=None):
     op = DBHelper().find_by_name(Operation, to_unicode(opname))
     if op is None or entity is None:
         return False
     ops = self.get_ops(entity, op)
     if len(ops) > 0:
         return True
     return False
Beispiel #17
0
 def __init__(self, mail_server, desc, port, use_secure, site_id, useremail, password):
     self.id = getHexID()
     self.mail_server = to_unicode(mail_server)
     self.description = desc
     self.port = port
     self.use_secure = use_secure
     self.site_id = site_id
     self.credential = Credential(self.id, u'', user_email=useremail, password=password)
Beispiel #18
0
 def get_entity_type(self, klass_name):
     from psphere.managedobjects import Datacenter
     from psphere.managedobjects import ClusterComputeResource
     from psphere.managedobjects import HostSystem
     from psphere.managedobjects import ComputeResource
     from psphere.managedobjects import VirtualMachine
     from psphere.managedobjects import Folder
     TYPE_MAP = {Datacenter.__name__: to_unicode(constants.DATA_CENTER), ClusterComputeResource.__name__: to_unicode(constants.SERVER_POOL), Folder.__name__: to_unicode(constants.SERVER_POOL), HostSystem.__name__: to_unicode(constants.MANAGED_NODE), ComputeResource.__name__: to_unicode(constants.MANAGED_NODE), VirtualMachine.__name__: to_unicode(constants.DOMAIN)}
     return TYPE_MAP.get(klass_name)
Beispiel #19
0
 def isVMRunningInPool(self, auth, group_id):
     returnVal = False
     ent = auth.get_entity(group_id)
     nodes = auth.get_entities(to_unicode(constants.MANAGED_NODE), parent=ent)
     for eachnode in nodes:
         returnVal = self.isVMRunningOnServer(auth, eachnode.entity_id)
         if returnVal == True:
             break
     return returnVal
Beispiel #20
0
 def check_privilege(self, opname, entities):
     op = DBHelper().find_by_name(Operation, to_unicode(opname))
     if op is None:
         return False
     for ent in entities:
         ops = self.get_ops(ent, op)
         if len(ops) == 0:
             return False
     return True
Beispiel #21
0
 def getNodeList(self,auth):
     ent=auth.get_entity(self.id)
     nodelist={}
     if ent is not None:
         child_ents=auth.get_entities(to_unicode(constants.MANAGED_NODE),parent=ent)
         ids = [child_ent.entity_id for child_ent in child_ents]
         nodes= DBHelper().filterby(ManagedNode,[],[ManagedNode.id.in_(ids)])
         for node in nodes:
             nodelist[node.id]=node
     return nodelist
Beispiel #22
0
 def add_csep_defn(self, csep_id, def_id, def_type, status, oos_count):
     row = DBSession.query(CSEPDefLink).filter_by(csep_id=csep_id, def_id=def_id).first()
     if not row:
         CPDL = CSEPDefLink()
         CPDL.csep_id = csep_id
         CPDL.def_type = def_type
         CPDL.def_id = def_id
         CPDL.status = to_unicode(status)
         CPDL.oos_count = oos_count
         CPDL.dt_time = datetime.now()
         DBSession.add(CPDL)
Beispiel #23
0
 def add_site_defn(self, site_id, def_id, def_type, status, oos_count):
     row = DBSession.query(DCDefLink).filter_by(site_id=site_id, def_id=def_id).first()
     if not row:
         DCDL = DCDefLink()
         DCDL.site_id = site_id
         DCDL.def_type = def_type
         DCDL.def_id = def_id
         DCDL.status = to_unicode(status)
         DCDL.oos_count = oos_count
         DCDL.dt_time = datetime.now()
         DBSession.add(DCDL)
Beispiel #24
0
 def is_admin_role(self):
     r = DBHelper().find_by_name(Role, to_unicode(constants.DEFAULT_ROLES[0]))
     if self.user:
         if self.user.is_cloud():
             return self.user.has_cloudadmin_role()
         return self.user.has_role(r)
     if self.groups:
         for g in self.groups:
             g = DBSession.query(Group).filter(Group.group_id == g.group_id).first()
             if g and r.id ==g.role.id:
                 return True
         return False
Beispiel #25
0
    def populate_appliance_feeds(self):
        feeds = {}
        for c, c_info in self.catalogs.iteritems():
            print c, c_info
            if type(c_info) in [types.StringType, types.UnicodeType]:
                url = c_info
        try:
            feed_conf = self.fetch_catalog(c, url)
        except Exception as ex:
            feed_conf = self.get_conf_name(c)
            print "Error getting catalog ", c, url, ex
            print "Continue using the existing data"

        if not os.path.exists(feed_conf):
            print "Skipping : %s does not exist.", feed_conf

        feed = PyConfig(self.local_node, feed_conf)
        for k, v in feed.iteritems():
            feeds[k] = v
        a_feeds = []
        for k in feeds.iteritems():
            a_feed = ApplianceFeed(to_unicode(k))
            a_feed.feed_name = to_unicode(v["feed_name"])
            a_feed.feed_url = to_unicode(v["feed_url"])
            a_feed.provider_logo_url = to_unicode(v["logo_url"])
            a_feed.provider_name = to_unicode(v["provider"])
            a_feed.provider_url = to_unicode(v["provider_url"])
            a_feeds.append(a_feed)

        DBHelper().truncate(ApplianceFeed)
        DBHelper().add_all(a_feeds)
        return a_feeds
Beispiel #26
0
 def get_vlan_network_info(self, cidr, num_networks, network_size, vlan_start, interface, **msg):
     num_networks = int(num_networks)
     network_size = int(network_size)
     vlan_start = int(vlan_start)
     msg = "\nnum_networks:%s, network_size:%s, vlan_start:%s, cidr:%s, interface:%s " % (
         num_networks,
         network_size,
         vlan_start,
         cidr,
         interface,
     )
     print msg
     LOGGER.info(msg)
     if num_networks + vlan_start > 4094:
         raise ValueError("The sum between the number of networks and the vlan start cannot be greater than 4094")
     fixed_net = netaddr.IPNetwork(cidr)
     msg = "\nfixed_net:%s, num_networks*network_size:%s" % (len(fixed_net), num_networks * network_size)
     print msg
     LOGGER.info(msg)
     if len(fixed_net) < num_networks * network_size:
         raise ValueError(
             "The network range is not big enough to fit %(num_networks)s. Network size is %(network_size)s"
             % locals()
         )
     private_ip_bottom_reserve = int(tg.config.get("private_ip_bottom_reserve", 10))
     private_ip_top_reserve = int(tg.config.get("private_ip_top_reserve", 2))
     interface_str = "x"
     if interface:
         if_str = re.sub("\\D", "", interface)
         if if_str:
             interface_str = if_str
     result = []
     for index in range(num_networks):
         vlan = vlan_start + index
         start = index * network_size
         significant_bits = 32 - int(math.log(network_size, 2))
         cidr = "%s/%s" % (fixed_net[start], significant_bits)
         project_net = netaddr.IPNetwork(cidr)
         net = {}
         net["cidr"] = to_unicode(cidr)
         net["netmask"] = to_unicode(project_net.netmask)
         net["gateway"] = to_unicode(list(project_net)[1])
         net["broadcast"] = to_unicode(project_net.broadcast)
         net["vpn_private_address"] = to_unicode(list(project_net)[2])
         net["dhcp_start"] = to_unicode(list(project_net)[private_ip_bottom_reserve])
         net["dhcp_end"] = to_unicode(list(project_net)[private_ip_top_reserve * -1])
         net["vlan_id"] = vlan
         net["bridge"] = to_unicode("br%s_%s" % (interface_str, vlan))
         result.append(net)
     return result
Beispiel #27
0
    def heartbeat(self):
        if self.isRemote == False:
            return [self.UP, u'Localhost is always up']

        try:
            state = self.node_proxy.get_power_state()
        except VCenterDownError as ex:
            print '===ex1============',
            print ex
            return [self.current_state.avail_state, u'vCenter Down. ' + to_unicode(ex)]
        except urllib2.URLError as ex:
            print '===ex2============',
            print ex
            return [self.DOWN, u'Host not found. ' + to_unicode(ex)]
        except suds.WebFault as ex:
            print '===ex3============',
            print ex
            return [self.DOWN, u'Host not found. ' + to_unicode(ex)]
        except Exception as ex:
            print '===ex5=========',
            print ex
            return [self.DOWN, u'Host not found. ' + to_unicode(ex)]
        return self.get_power_state(state)
Beispiel #28
0
 def storage_def_test(self, auth, storage_id, nodeId, groupId, site_id, type, mode, opts, scope, show_available='true', vm_config_action=None, disk_option=None):
     if mode == 'SELECT':
         result = self.get_storage_disks_for_test(storage_id, show_available, vm_config_action, disk_option)
         return result
     try:
         self.storage_manager.RemoveScanResult()
         group = self.manager.getGroup(auth, groupId)
         managed_node = self.manager.getNode(auth, nodeId)
         if not managed_node:
             raise Exception('Managed Server not found.')
         
         try:
             managed_node.connect()
         except AuthenticationException as ex:
             if opts.has_key('username') and opts.has_key('password'):
                 managed_node.set_credentials(opts['username'], opts['password'])
                 try:
                     managed_node.connect()
                 except AuthenticationException as ex:
                     print_traceback()
                     LOGGER.error(to_str(ex).replace("'", ''))
                     return ("{success: false,msg: '", to_str(ex).replace("'", ''), "',error:'Not Authenticated'}")
             else:
                 return ("{success: false,msg: '", to_str(ex).replace("'", ''), "',error:'Not Authenticated'}")
         sd = None
         if mode == 'TEST' or mode == 'EDIT' or mode == 'SELECT':
             sd = self.storage_manager.get_sd(storage_id, site_id, groupId, to_unicode(constants.STORAGE))
         else:
             sd = self.get_valid_sd(type, opts, scope)
         if site_id:
             if site_id == 'data_center':
                 site = self.manager.getSiteByGroupId(group.id)
             else:
                 site = self.manager.getSite(site_id)
         else:
             site = self.manager.getSiteByGroupId(group.id)
         result = self.test_storage_def(auth, managed_node, group, site, sd)
         if result or  mode == 'NEW' or mode == 'EDIT':
             #if not mode == 'NEW' or mode == 'EDIT':
             try:
                 session[constants.SCAN_RESULT] = result
                 session.save()
             except Exception as ex:
                 print_traceback()
                 LOGGER.error('Error while keeping the scan result in session: ' + to_str(ex).replace("'", ''))
     except Exception as ex:
         print_traceback()
         LOGGER.error(to_str(ex).replace("'", ''))
         return dict(success=False, msg=to_str(ex).replace("'", ''))
     return result
Beispiel #29
0
 def getNodeList(self, auth, groupId=None):
     LOGGER.debug('In getNodeList')
     if groupId is None:
         return []
     ent = auth.get_entity(groupId)
     nodelist = []
     if ent is not None:
         child_ents = auth.get_entities(to_unicode(constants.MANAGED_NODE),parent = ent)
         node_ids = [child_ent.entity_id for child_ent in child_ents]
         nodelist = DBSession.query(ManagedNode)\
                     .filter(ManagedNode.id.in_(node_ids)).order_by(ManagedNode.standby_status.desc())\
                     .order_by(ManagedNode.hostname.asc()).all()
         return nodelist
     return []
Beispiel #30
0
 def task_fail_start(self, exception, conn):
     results = to_str(exception)
     self.curr_instance = datetime.now()
     res = TaskResult(self.task_id, self.curr_instance, self.FAILED, results)
     u = User.by_user_name(self.user_name)
     if u is None:
         u = User.by_user_name(u'admin')
     email = u.email_address
     notification = Notification(to_unicode(self.task_id), self.name, self.curr_instance, results, self.user_name, email)
     conn.merge(res)
     conn.add(notification)
     if not self.repeating and self.entity_id != None:
         UIUpdateManager().set_updated_tasks(self.task_id, self.user_name, self.entity_id)
     return None