def _try_allocate(self, context, segment_id, network_id):
LOG.info("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (network_id, segment_id, self.segment_type))<EOL>filter_dict = {<EOL>"<STR_LIT>": segment_id,<EOL>"<STR_LIT>": self.segment_type,<EOL>"<STR_LIT>": False<EOL>}<EOL>available_ranges = db_api.segment_allocation_range_find(<EOL>context, scope=db_api.ALL, **filter_dict)<EOL>available_range_ids = [r["<STR_LIT:id>"] for r in available_ranges]<EOL>try:<EOL><INDENT>with context.session.begin(subtransactions=True):<EOL><INDENT>filter_dict = {<EOL>"<STR_LIT>": True,<EOL>"<STR_LIT>": segment_id,<EOL>"<STR_LIT>": self.segment_type,<EOL>"<STR_LIT>": available_range_ids<EOL>}<EOL>allocations = db_api.segment_allocation_find(<EOL>context, lock_mode=True, **filter_dict).limit(<NUM_LIT:100>).all()<EOL>if allocations:<EOL><INDENT>allocation = random.choice(allocations)<EOL>update_dict = {<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": network_id<EOL>}<EOL>allocation = db_api.segment_allocation_update(<EOL>context, allocation, **update_dict)<EOL>LOG.info("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (allocation["<STR_LIT:id>"], network_id, segment_id,<EOL>self.segment_type))<EOL>return allocation<EOL><DEDENT><DEDENT><DEDENT>except Exception:<EOL><INDENT>LOG.exception("<STR_LIT>")<EOL><DEDENT>LOG.info("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (network_id, segment_id, self.segment_type))<EOL>
Find a deallocated network segment id and reallocate it.

        NOTE(morgabra) This locks the segment table, but only the rows
        in use by the segment, which is pretty handy if we ever have
        more than 1 segment or segment type.