这段代码干了什么：import os
import datetime
from collections import deque
import fcntl
from multiprocessing import shared_memory
import json
import logging

class APILoop:
    def __init__(self, filename, max_keys=10):
        """
        初始化APILoop类
        :param filename: API key文件路径
        :param max_keys: 迭代器中保持的最大key数量
        """
        self.filename = filename
        self.max_keys = max_keys
        self.api_keys = deque(maxlen=max_keys)
        self.all_keys = set()
        self.current_index = 0

        # 创建共享内存来存储已使用的 API keys
        self.shm_name = "api_keys_shm"
        try:
            self.shm = shared_memory.SharedMemory(name=self.shm_name, create=True, size=1024)
        except FileExistsError:
            self.shm = shared_memory.SharedMemory(name=self.shm_name)
        
        self.used_keys = set()
        self._load_used_keys()

        # 配置日志
        logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
        self.logger = logging.getLogger(__name__)

        # 加载API keys
        self._load_api_keys()

    def _load_used_keys(self):
        data = self.shm.buf.tobytes().decode().strip('\x00')
        if data:
            self.used_keys = set(json.loads(data))

    def _save_used_keys(self):
        data = json.dumps(list(self.used_keys))
        self.shm.buf[:len(data)] = data.encode()

    def _load_api_keys(self):
        if not os.path.exists(self.filename):
            raise FileNotFoundError(f"文件 {self.filename} 不存在。")

        with open(self.filename, 'r', encoding='utf-8') as file:
            fcntl.flock(file.fileno(), fcntl.LOCK_SH)
            lines = [line.strip() for line in file if line.strip() and "用完余额" not in line]
            fcntl.flock(file.fileno(), fcntl.LOCK_UN)
        
        self.all_keys = set(lines) - self.used_keys
        self._fill_api_keys()
        self.logger.error(f"正在使用的API keys: {list(self.api_keys)}")
        self.logger.error(f"当前可用api数量为: {len(self.all_keys)}")

    def _fill_api_keys(self):
        available_keys = list(self.all_keys - set(self.api_keys))
        for key in available_keys:
            if len(self.api_keys) < self.max_keys:
                self.api_keys.append(key)
            else:
                break

    def get_api_key(self):
        if not self.api_keys:
            self._load_api_keys()
            if not self.api_keys:
                raise ValueError("没有可用的API keys。")

        key = self.api_keys[0]
        self.api_keys.rotate(-1)
        self.logger.error(f"使用API key: {key}")
        return key

    def mark_api_key_as_used(self, api_key):
        if api_key not in self.all_keys and api_key not in self.used_keys:
            raise ValueError(f"API key {api_key} 不存在。")

        self.used_keys.add(api_key)
        self._save_used_keys()

        if api_key in self.all_keys:
            self.all_keys.remove(api_key)
        if api_key in self.api_keys:
            self.api_keys.remove(api_key)

        self._fill_api_keys()
        self.logger.error(f"更新后正在使用的API keys: {list(self.api_keys)}")
        self.logger.info(f"当前可用api数量为: {len(self.all_keys)}")

        if not self.all_keys:
            self._reset_all_keys()

        self._update_file(api_key)

    def _reset_all_keys(self):
        with open(self.filename, 'r', encoding='utf-8') as file:
            fcntl.flock(file.fileno(), fcntl.LOCK_SH)
            self.all_keys = set(line.strip() for line in file if line.strip() and "用完余额" not in line)
            fcntl.flock(file.fileno(), fcntl.LOCK_UN)
        self.all_keys -= self.used_keys
        self._fill_api_keys()

    @staticmethod
    def _current_timestamp():
        return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    def _update_file(self, used_api_key):
        temp_filename = f"{self.filename}.temp"
        with open(self.filename, 'r', encoding='utf-8') as input_file, \
             open(temp_filename, 'w', encoding='utf-8') as output_file:
            fcntl.flock(input_file.fileno(), fcntl.LOCK_EX)
            for line in input_file:
                if line.strip() == used_api_key:
                    timestamp = self._current_timestamp()
                    output_file.write(f"{line.strip()}  于{timestamp}时用完余额\n")
                else:
                    output_file.write(line)
            fcntl.flock(input_file.fileno(), fcntl.LOCK_UN)
        
        os.replace(temp_filename, self.filename)

    def __del__(self):
        self.shm.close()
        try:
            self.shm.unlink()
        except:
            pass

# 使用示例:
# api_loop = APILoop("小海api每个1.2刀.txt")
# api_key = api_loop.get_api_key()
# print(f"获取的API key: {api_key}")
# api_loop.mark_api_key_as_used(api_key)