当前位置: 首页>>代码示例>>Python>>正文


Python Node.save方法代码示例

本文整理汇总了Python中chef.Node.save方法的典型用法代码示例。如果您正苦于以下问题:Python Node.save方法的具体用法?Python Node.save怎么用?Python Node.save使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在chef.Node的用法示例。


在下文中一共展示了Node.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: destroy_node

# 需要导入模块: from chef import Node [as 别名]
# 或者: from chef.Node import save [as 别名]
 def destroy_node(self, node):
     """
     Destroys a node provisioned by razor
     :param node: Node to destroy
     :type node: ChefNode
     """
     cnode = Node(node.name, node.environment.local_api)
     in_use = node['in_use']
     if in_use == "provisioning" or in_use == 0:
         # Return to pool if the node is clean
         cnode['in_use'] = 0
         cnode['archive'] = {}
         cnode.chef_environment = "_default"
         cnode.save()
     else:
         # Remove active model if the node is dirty
         active_model = cnode['razor_metadata']['razor_active_model_uuid']
         try:
             if node.feature_in('controller'):
                 # rabbit can cause the node to not actually reboot
                 kill = ("for i in `ps -U rabbitmq | tail -n +2 | "
                         "awk '{print $1}' `; do kill -9 $i; done")
                 node.run_cmd(kill)
             node.run_cmd("shutdown -r now")
             self.api.remove_active_model(active_model)
             Client(node.name).delete()
             cnode.delete()
             sleep(15)
         except:
             util.logger.error("Node unreachable. "
                               "Manual restart required:{0}".
                               format(str(node)))
开发者ID:cjoelrun,项目名称:monster,代码行数:34,代码来源:razor.py

示例2: build_computes

# 需要导入模块: from chef import Node [as 别名]
# 或者: from chef.Node import save [as 别名]
def build_computes(computes):
    # Run computes
    print "Making the compute nodes..."
    for compute in computes:
        compute_node = Node(compute)
        compute_node['in_use'] = "compute"
        compute_node.run_list = ["role[qa-single-compute]"]
        compute_node.save()

        print "Updating server...this may take some time"
        update_node(compute_node)

        if compute_node['platform_family'] == 'rhel':
            print "Platform is RHEL family, disabling iptables"
            disable_iptables(compute_node)

        # Run chef client twice
        print "Running chef-client on compute node: %s, this may take some time..." % compute
        run1 = run_chef_client(compute_node)
        if run1['success']:
            print "First chef-client run successful...starting second run..."
            run2 = run_chef_client(compute_node)
            if run2['success']:
                print "Second chef-client run successful..."
            else:
                print "Error running chef-client for compute %s" % compute
                print run2
                sys.exit(1)
        else:
            print "Error running chef-client for compute %s" % compute
            print run1
            sys.exit(1)
开发者ID:carriercomm,项目名称:rpcsqa,代码行数:34,代码来源:chef_helper.py

示例3: chef_instance

# 需要导入模块: from chef import Node [as 别名]
# 或者: from chef.Node import save [as 别名]
 def chef_instance(self, deployment, name, flavor="2GBP"):
     """
     Builds an instance with desired specs and inits it with chef
     :param client: compute client object
     :type client: novaclient.client.Client
     :param deployment: deployement to add to
     :type deployment: ChefDeployment
     :param name: name for instance
     :type name: string
     :param flavor: desired flavor for node
     :type flavor: string
     :rtype: ChefNode
     """
     image = deployment.os_name
     server, password = self.build_instance(name=name, image=image,
                                            flavor=flavor)
     run_list = ",".join(util.config[str(self)]['run_list'])
     run_list_arg = ""
     if run_list:
         run_list_arg = "-r {0}".format(run_list)
     command = 'knife bootstrap {0} -u root -P {1} -N {2} {3}'.format(
         server.accessIPv4, password, name, run_list_arg)
     run_cmd(command)
     node = Node(name, api=deployment.environment.local_api)
     node.chef_environment = deployment.environment.name
     node['in_use'] = "provisioning"
     node['ipaddress'] = server.accessIPv4
     node['password'] = password
     node['uuid'] = server.id
     node['current_user'] = "root"
     node.save()
     return node
开发者ID:CharlesKimpolo,项目名称:monster,代码行数:34,代码来源:openstack.py

示例4: _is_node_busy_and_reserve_it

# 需要导入模块: from chef import Node [as 别名]
# 或者: from chef.Node import save [as 别名]
def _is_node_busy_and_reserve_it(node_id, api, controller_requestor='gcc'):
    settings = get_current_registry().settings
    seconds_block_is_busy = int(settings.get('chef.seconds_block_is_busy'))
    time_to_exp = datetime.timedelta(seconds=seconds_block_is_busy)
    node = ChefNode(node_id, api)
    current_use_node = node.attributes.get(USE_NODE, {})
    current_use_node_control = current_use_node.get('control', None)
    current_use_node_exp_date = current_use_node.get('exp_date', None)
    if current_use_node_exp_date:
        current_use_node_exp_date = json.loads(current_use_node_exp_date, object_hook=json_util.object_hook)
        current_use_node_exp_date = current_use_node_exp_date.astimezone(pytz.utc).replace(tzinfo=None)
        now = datetime.datetime.now()
        if now - current_use_node_exp_date > time_to_exp:
            current_use_node_control = None
    if current_use_node_control == controller_requestor:
        return (node, False)
    elif current_use_node_control is None:
        exp_date = datetime.datetime.utcnow() + time_to_exp
        node.attributes.set_dotted(USE_NODE, {'control': controller_requestor,
                                              'exp_date': json.dumps(exp_date, default=json_util.default)})
        node.save()
        node2 = ChefNode(node.name, api)  # second check
        current_use_node2 = node2.attributes.get(USE_NODE, {})
        current_use_control2 = current_use_node2.get('control', None)
        if current_use_control2 == controller_requestor:
            return (node2, False)
    return (node, True)
开发者ID:Emergya,项目名称:gecoscc-ui,代码行数:29,代码来源:utils.py

示例5: post

# 需要导入模块: from chef import Node [as 别名]
# 或者: from chef.Node import save [as 别名]
    def post(self):
        node_id = self.request.POST.get('node_id')
        if node_id is None:
            return {'ok': False, 'message': 'Missing node ID'}

        settings = get_current_registry().settings
        api = get_chef_api(settings, self.request.user)

        # create chef client
        chef_client = ChefClient(node_id, api)
        if chef_client.exists:
            return {'ok': False, 'message': 'This client already exists'}

        chef_client = ChefClient.create(node_id, api)
        
        # Prepare the API for this client
        chef_url = settings.get('chef.url')
        chef_version = settings.get('chef.version')
        chef_ssl_verify = settings.get('chef.ssl.verify')
        if chef_ssl_verify == 'False' or chef_ssl_verify == 'True':
            chef_ssl_verify = bool(chef_ssl_verify)
        api = ChefAPI(chef_url, str(chef_client.private_key), node_id, chef_version, ssl_verify = False)

 
        # create chef node
        chef_node = ChefNode(node_id, api)
        if chef_node.exists:
            return {'ok': False, 'message': 'This node already exists'}
        chef_node.save()

        return {'ok': True, 'message': 'Node and client have been added',
                'client_private_key': chef_client.private_key}
开发者ID:gecos-team,项目名称:gecoscc-ui,代码行数:34,代码来源:register_chef_node.py

示例6: build_dir_server

# 需要导入模块: from chef import Node [as 别名]
# 或者: from chef.Node import save [as 别名]
def build_dir_server(dir_server):
    # We dont support 389 yet, so exit if it is not ldap
    if results.dir_version != 'openldap':
        print "%s as a directory service is not yet supported...exiting" % results.dir_version
        sys.exit(1)

    # Build directory service node
    dir_node = Node(dir_server)
    ip = dir_node['ipaddress']
    root_pass = razor.get_active_model_pass(dir_node['razor_metadata'].to_dict()['razor_active_model_uuid'])['password']
    dir_node['in_use'] = 'directory-server'
    dir_node.run_list = ["role[qa-%s-%s]" % (results.dir_version, results.os)]
    dir_node.save()

    print "Updating server...this may take some time"
    update_node(dir_node)

    # if redhat platform, disable iptables
    if dir_node['platform_family'] == 'rhel':
        print "Platform is RHEL family, disabling iptables"
        disable_iptables(dir_node)

    # Run chef-client twice
    print "Running chef-client for directory service node...this may take some time..."
    run1 = run_chef_client(dir_node)
    if run1['success']:
        print "First chef-client run successful...starting second run..."
        run2 = run_chef_client(dir_node)
        if run2['success']:
            print "Second chef-client run successful..."
        else:
            print "Error running chef-client for directory node %s" % dir_node
            print run2
            sys.exit(1)
    else:
        print "Error running chef-client for directory node %s" % dir_node
        print run1
        sys.exit(1)

    # Directory service is set up, need to import config
    if run1['success'] and run2['success']:
        if results.dir_version == 'openldap':
            scp_run = run_remote_scp_cmd(ip, 'root', root_pass, '/var/lib/jenkins/source_files/ldif/*.ldif')
            if scp_run['success']:
                ssh_run = run_remote_ssh_cmd(ip, 'root', root_pass, 'ldapadd -x -D \"cn=admin,dc=dev,dc=rcbops,dc=me\" -f base.ldif [email protected]')
        elif results.dir_version == '389':
            # Once we support 389, code here to import needed config files
            print "389 is not yet supported..."
            sys.exit(1)
        else:
            print "%s is not supported...exiting" % results.dir_version
            sys.exit(1)

    if scp_run['success'] and ssh_run['success']:
        print "Directory Service: %s successfully set up..." % results.dir_version
    else:
        print "Failed to set-up Directory Service: %s..." % results.dir_version
        sys.exit(1)
开发者ID:carriercomm,项目名称:rpcsqa,代码行数:60,代码来源:chef_helper.py

示例7: clear_pool

# 需要导入模块: from chef import Node [as 别名]
# 或者: from chef.Node import save [as 别名]
def clear_pool(chef_nodes, environment):
    for n in chef_nodes:
        name = n['name']
        node = Node(name)
        if node.chef_environment == environment:
            if "recipe[network-interfaces]" not in node.run_list:
                erase_node(name)
            else:
                node.chef_environment = "_default"
                node.save()
开发者ID:carriercomm,项目名称:rpcsqa,代码行数:12,代码来源:chef_helper.py

示例8: build

# 需要导入模块: from chef import Node [as 别名]
# 或者: from chef.Node import save [as 别名]
    def build(self):
        """ Builds the node
        """

        # clear run_list
        self.run_list = []
        node = ChefNode(self.name, self.environment.local_api)
        node.run_list = []
        node.save()
        super(Chef, self).build()
开发者ID:cjoelrun,项目名称:monster,代码行数:12,代码来源:chef_node.py

示例9: __setitem__

# 需要导入模块: from chef import Node [as 别名]
# 或者: from chef.Node import save [as 别名]
 def __setitem__(self, item, value):
     """
     Node can set chef attributes
     """
     lnode = CNode(self.name, api=self.environment.local_api)
     lnode[item] = value
     lnode.save()
     if self.environment.remote_api:
         rnode = CNode(self.name, api=self.environment.remote_api)
         rnode[item] = value
         rnode.save()
开发者ID:AsherBond,项目名称:jenkins-build,代码行数:13,代码来源:Nodes.py

示例10: destroy

# 需要导入模块: from chef import Node [as 别名]
# 或者: from chef.Node import save [as 别名]
 def destroy(self):
     cnode = CNode(self.name)
     if self['in_use'] == "provisioned":
         # Return to pool if the node is clean
         cnode.chef_environment = "_default"
         cnode.save()
     else:
         # Remove active model if the node is dirty
         active_model = cnode['razor_metadata']['razor_active_model_uuid']
         self.razor.remove_active_model(active_model)
         self.run_cmd("reboot 0")
         CClient(self.name).delete()
         cnode.delete()
         sleep(15)
开发者ID:AsherBond,项目名称:jenkins-build,代码行数:16,代码来源:Nodes.py

示例11: _is_node_busy_and_reserve_it

# 需要导入模块: from chef import Node [as 别名]
# 或者: from chef.Node import save [as 别名]
def _is_node_busy_and_reserve_it(node_id, api, controller_requestor='gcc'):
    '''
    Check if the node is busy, else try to get it and write in control and expiration date in the field USE_NODE.
    '''
    settings = get_current_registry().settings
    seconds_block_is_busy = int(settings.get('chef.seconds_block_is_busy'))
    time_to_exp = datetime.timedelta(seconds=seconds_block_is_busy)

    time_get = time.time()
    node = ChefNode(node_id, api)
    time_get = time.time() - time_get

    current_use_node = node.attributes.get(USE_NODE, {})
    current_use_node_control = current_use_node.get('control', None)
    current_use_node_exp_date = current_use_node.get('exp_date', None)
    if current_use_node_exp_date:
        current_use_node_exp_date = json.loads(current_use_node_exp_date, object_hook=json_util.object_hook)
        current_use_node_exp_date = current_use_node_exp_date.astimezone(pytz.utc).replace(tzinfo=None)
        now = datetime.datetime.now()
        if now - current_use_node_exp_date > time_to_exp:
            current_use_node_control = None
    if current_use_node_control == controller_requestor:
        return (node, False)
    elif current_use_node_control is None:
        exp_date = datetime.datetime.utcnow() + time_to_exp
        node.attributes.set_dotted(USE_NODE, {'control': controller_requestor,
                                              'exp_date': json.dumps(exp_date, default=json_util.default)})
        node.save()

        smart_lock_sleep_parameter = settings.get('chef.smart_lock_sleep_factor', 3)
        seconds_sleep_is_busy = time_get * int(smart_lock_sleep_parameter)
        time.sleep(seconds_sleep_is_busy)

        node2 = ChefNode(node.name, api)  # second check
        current_use_node2 = node2.attributes.get(USE_NODE, {})
        current_use_control2 = current_use_node2.get('control', None)
        if current_use_control2 == controller_requestor:
            return (node2, False)
    return (node, True)
开发者ID:System25,项目名称:gecoscc-ui,代码行数:41,代码来源:utils.py

示例12: build_controller

# 需要导入模块: from chef import Node [as 别名]
# 或者: from chef.Node import save [as 别名]
def build_controller(controller, ha=False, ha_num=0):
    controller_node = Node(controller)

    # Check for ha
    if ha:
        print "Making %s the ha-controller%s node" % (controller, ha_num)
        controller_node['in_use'] = "ha-controller%s" % ha_num
        controller_node.run_list = ["role[qa-ha-controller%s]" % ha_num]
    else:
        print "Making %s the controller node" % controller
        controller_node['in_use'] = "controller"
        controller_node.run_list = ["role[qa-single-controller]"]
    # save node
    controller_node.save()

    print "Updating server...this may take some time"
    update_node(controller_node)

    if controller_node['platform_family'] == 'rhel':
        print "Platform is RHEL family, disabling iptables"
        disable_iptables(controller_node)

    # Run chef-client twice
    print "Running chef-client for controller node...this may take some time..."
    run1 = run_chef_client(controller_node)
    if run1['success']:
        print "First chef-client run successful...starting second run..."
        run2 = run_chef_client(controller_node)
        if run2['success']:
            print "Second chef-client run successful..."
        else:
            print "Error running chef-client for controller %s" % controller
            print run2
            sys.exit(1)
    else:
        print "Error running chef-client for controller %s" % controller
        print run1
        sys.exit(1)
开发者ID:carriercomm,项目名称:rpcsqa,代码行数:40,代码来源:chef_helper.py

示例13: command

# 需要导入模块: from chef import Node [as 别名]
# 或者: from chef.Node import save [as 别名]
    def command(self):
        # Initialization
        sanitized = False
        computers = set()
        self.api = _get_chef_api(self.settings.get('chef.url'),
                            toChefUsername(self.options.chef_username),
                            self.options.chef_pem, False, self.settings.get('chef.version'))

        self.auth_user = self.db.adminusers.find_one({'username': self.options.chef_username})
        if self.auth_user is None:
            logger.error('The administrator user must exist in MongoDB')
            sys.exit(1)

        self.db = self.pyramid.db
        
        # Get local_admin_users_res (Local Administrators) policy
        logger.info('Getting Local Administrators (local_admin_users_res) policy ...')
        policy   = self.db.policies.find_one({'slug':'local_admin_users_res'})
        schema   = policy['schema']
        policyId = policy['_id']
        
        logger.info('schema   = %s'%str(schema))
        logger.info('Id.policy = %s'%str(policyId))

        # Searching nodes with the Local Administrators policy
        # Query Fields of an Embedded Document (Mongo documentation)
        # Example:
        # db.nodes.find({"policies.58c8122a0dfd425b0894d5b6":{$exists:true}})
        logger.info('Searching nodes with the Local Administrators policy...')
        field = 'policies.' + str(policyId)
        filters  = {field:{'$exists':True}}
        nodes = self.db.nodes.find(filters)
  
        # Validating data and, where appropiate, fixing
        for node in nodes:
            instance = node['policies'][unicode(policyId)]

            logger.info('Node name = %s, _id = %s'%(node['name'],str(node['_id'])))
            logger.info('Instance before validate method: %s'%str(instance))
            while True:
                try:
                    validate(instance, schema)
                    break
                except ValidationError as e: 
                     logger.warning('Validation error on instance = %s'%str(e.message))
                     # Sanitize instance
                     self.sanitize(e, instance)
                     sanitized = True

            if sanitized:
                # Setting false sanitized for next iteration
                sanitized = False
                logger.info('Sanitized instance: %s'%str(instance))

                # Update mongo
                self.db.nodes.update({'_id': node['_id']},{'$set':{field:instance}})

                # Affected nodes
                if node['type'] == 'ou':
                    result = list(self.db.nodes.find({'path': get_filter_nodes_belonging_ou(node['_id']),'type': 'computer'},{'_id':1}))
                    logger.info('OU computers = %s'%str(result))
                elif node['type'] == 'group':
                    result = list(self.db.nodes.find({'_id':{'$in':node['members']},'type':'computer'},{'_id':1}))
                    logger.info('GROUP computers = %s'%str(result))
                elif node['type'] == 'computer':
                    result = [node]
                    logger.info('COMPUTER computers = %s'%str(result))

                [computers.add(str(n['_id'])) for n in result]


        # Removing unused local_admin_remove_list attribute in chef nodes
        for node_id in ChefNode.list():
            node = ChefNode(node_id, self.api)
            logger.info('Checking node: %s'%(node_id))
            attr_dotted = policy['path'] + '.local_admin_remove_list'
            logger.info('Atttribute dotted path: %s'%(attr_dotted))
            if node.attributes.has_dotted(attr_dotted):
                logger.info("Remove 'local_admin_remove_list' attribute!")
                try:
                    logger.info("node.attributes = %s" % str(node.attributes['gecos_ws_mgmt']['misc_mgmt']['local_admin_users_res'].to_dict()))
                    delete_dotted(node.attributes, attr_dotted)
                    node.save()
                except:
                    logger.warn("Problem deleting local_admin_remove_list value from node: %s"%(node_id))
                    logger.warn("You may be trying to delete a default attribute instead normal attribute: %s"%(node_id))

        for computer in computers:
            logger.info('computer = %s'%str(computer))
            computer = self.db.nodes.find_one({'_id': ObjectId(computer)})
            apply_policies_to_computer(self.db.nodes, computer, self.auth_user, api=self.api, initialize=False, use_celery=False)
                   
        logger.info('Finished.')
开发者ID:joroca,项目名称:gecoscc-ui,代码行数:95,代码来源:check_local_admin_policy.py

示例14: command

# 需要导入模块: from chef import Node [as 别名]
# 或者: from chef.Node import save [as 别名]
    def command(self):
        from gecoscc.api.chef_status import USERS_OLD, USERS_OHAI
        # Initialization
        self.api = _get_chef_api(self.settings.get('chef.url'),
                            toChefUsername(self.options.chef_username),
                            self.options.chef_pem, False, self.settings.get('chef.version'))

        self.db = self.pyramid.db

        # Check administrator user
        auth_user = self.db.adminusers.find_one({'username': self.options.chef_username})
        if auth_user is None:
            logger.error('The administrator user must exist in MongoDB')
            sys.exit(1)

        # Recorriendo todos los nodos 
        for node_id in ChefNode.list():
            node = ChefNode(node_id, self.api)
            logger.info('Checking node: %s'%(node_id))
            
            try:
                if node.attributes.get_dotted(USERS_OLD):
                    delete_dotted(node.attributes, USERS_OLD)
                    node.save()
            except KeyError:
                logger.warn("Not found attribute: %s"%(USERS_OLD))
            except:
                logger.warn("Problem deleting users_old attribute from node: %s"%(node_id))

            # Updating users list    
            computer = self.db.nodes.find_one({'node_chef_id': node_id, 'type':'computer'})
            if not computer:
                logger.error('This node does not exist (mongodb)')
                continue
 
            chef_node_usernames = set([d['username'] for d in  node.attributes.get_dotted(USERS_OHAI)])
            gcc_node_usernames  = set([d['name'] for d in self.db.nodes.find({
                                       'type':'user',
                                       'computers': {'$in': [computer['_id']]}
                                    },
                                    {'_id':0, 'name':1})
                                 ])


            users_recalculate_policies = []
            users_remove_policies = []

            # Users added/removed ?
            if set.symmetric_difference(chef_node_usernames, gcc_node_usernames):
                logger.info("Users added/removed found.")

                # Add users or vinculate user to computer if already exists
                addusers = set.difference(chef_node_usernames, gcc_node_usernames)
                for add in addusers:
                    logger.info("Added user: %s"%(add))
                    user = self.db.nodes.find_one({'name': add, 'type': 'user', 'path': get_filter_in_domain(computer)})

                    if not user:
                        user_model = User()
                        user = user_model.serialize({'name': add,
                                                     'path': computer.get('path', ''),
                                                     'type': 'user',
                                                     'lock': computer.get('lock', ''),
                                                     'source': computer.get('source', '')})

                        user = update_computers_of_user(self.db, user, self.api)

                        del user['_id']
                        user_id = self.db.nodes.insert(user)
                        user = self.db.nodes.find_one({'_id': user_id})
                        users_recalculate_policies.append(user)

                    else:
                        computers = user.get('computers', [])
                        if computer['_id'] not in computers:
                            computers.append(computer['_id'])
                            self.db.nodes.update({'_id': user['_id']}, {'$set': {'computers': computers}})
                            users_recalculate_policies.append(user)
                            add_computer_to_user(computer['_id'], user['_id'])

                # Removed users
                delusers = set.difference(gcc_node_usernames, chef_node_usernames)
                for delete in delusers:
                    logger.info("Deleted user: %s"%(delete))
                    user = self.db.nodes.find_one({'name': delete,
                                                   'type': 'user',
                                                   'path': get_filter_in_domain(computer)})
                    computers = user['computers'] if user else []
                    if computer['_id'] in computers:
                        users_remove_policies.append(deepcopy(user))
                        computers.remove(computer['_id'])
                        self.db.nodes.update({'_id': user['_id']}, {'$set': {'computers': computers}})

                for user in users_recalculate_policies:
                    apply_policies_to_user(self.db.nodes, user, auth_user)

                for user in users_remove_policies:
                    remove_policies_of_computer(user, computer, auth_user)
开发者ID:joroca,项目名称:gecoscc-ui,代码行数:100,代码来源:remove_users_old.py

示例15: command

# 需要导入模块: from chef import Node [as 别名]
# 或者: from chef.Node import save [as 别名]

#.........这里部分代码省略.........
        # Example:
        # db.nodes.find({"policies.58c8122a0dfd425b0894d5b6":{$exists:true}})
        logger.info('Searching for nodes with applied policy...')
        field = 'policies.' + str(policyId)
        filters  = {field:{'$exists':True}}
        nodes = self.db.nodes.find(filters)
  
        # Validating data and, where appropiate, fixing
        for node in nodes:
            instance = node['policies'][unicode(policyId)]
            logger.info("node = %s" % str(node))

            logger.info('-----------------------------------------------')
            logger.info('Node name = %s, mongo_id = %s'%(node['name'],str(node['_id'])))
            logger.info('Instance of the policy on the node: %s'%str(instance))
            while True:
                try:
                    validate(instance, schema)
                    break
                except ValidationError as e: 
                     logger.warn('Validation error on instance = %s'%str(e.message))
                     # Sanitize instance
                     self.sanitize(e, instance)
                     sanitized = True

            if sanitized:
                # Setting false sanitized for next iteration
                sanitized = False
                logger.info('Sanitized instance of the policy on the node AFTER calling the validate method: %s'%str(instance))

                # Update mongo
                logger.info('Updating instance in database (mongo) ...')
                self.db.nodes.update({'_id': node['_id']},{'$set':{field:instance}})

                logger.info('Recalculating policies in the node.')
                # Affected nodes
                if   node['type'] == 'ou':
                    ous.append(node)                                    
                elif node['type'] == 'group':                                             
                    groups.append(node)
                elif node['type'] == 'user':
                    users.append(node)

        # We only go through the highest level OUs. 
        # Therefore, we eliminate intermediate OUs and 
        # then do not recalculate the policies
        # for the same node several times.
        for ou in ous:
            parents = [ObjectId(oid) for oid in ou['path'].split(',') if oid != 'root']
            if any(o['_id'] in parents for o in ous):
                ous.remove(ou)

        # Users that are not under an OU or GROUP that have the migrated policy
        for user in users:
            parents = [ObjectId(oid) for oid in user['path'].split(',') if oid != 'root'] 
            if any(o['_id'] in parents for o in ous):
                users.remove(user)
            elif any(user['_id'] in group['members'] for group in groups):
                users.remove(user)

        # Recalculating policies for OU
        for ou in ous: 
            old = deepcopy(ou)
            del old["policies"][str(policyId)]
            object_changed(self.auth_user, 'ou', ou, old)

        # Recalculating policies for GROUP
        for group in groups:
            old = deepcopy(group)
            del old["policies"][str(policyId)]
            object_changed(self.auth_user, 'group', group, old)

        # Recalculating policies for USER
        for user in users:
            old = deepcopy(user)
            del old["policies"][str(policyId)]
            object_changed(self.auth_user, 'user', user, old)

        # Removing unused desktops_to_remove attribute in chef nodes
        logger.info('\n')
        logger.info('Removing unused desktops_to_remove attribute in chef nodes ...')
        for node_id in ChefNode.list():
            node = ChefNode(node_id, self.api)
            logger.info('Checking node: %s'%(node_id))
            field_chef = '%s.users' % policy['path']
            users = node.attributes.get_dotted(field_chef) if node.attributes.has_dotted(field_chef) else []
            for user in users:
                logger.debug("user = %s" % (user))
                attr_delete_path = '%s.%s.desktops_to_remove' % (field_chef, user)
                logger.debug('Atttribute dotted path: %s'%(attr_delete_path))
                if node.attributes.has_dotted(attr_delete_path):
                    logger.warn("Remove 'desktops_to_remove' attribute! for user %s" % (user))
                    try:
                        delete_dotted(node.attributes, attr_delete_path)
                        node.save()
                    except:
                        logger.warn("Problem deleting desktops_to_remove value from node: %s"%(node_id))
                        logger.warn("You may be trying to delete a default attribute instead normal attribute: %s"%(node_id))

        logger.info('Finished.')
开发者ID:joroca,项目名称:gecoscc-ui,代码行数:104,代码来源:check_user_apps_autostart_policy.py


注:本文中的chef.Node.save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。