首页 > 其他分享 >解决 K8sApi 部署后报 Unknown apiVersionKind apps/v1/Deployment is it registered?

解决 K8sApi 部署后报 Unknown apiVersionKind apps/v1/Deployment is it registered?

时间:2024-03-14 11:13:15浏览次数:22  
标签:apiVersionKind String preBuiltApiGroups Unknown registered static io put k8s

该功能在本地调试时是正常的, 部署到服务器时报错。

Jdk11 + SpringBoot 2.7.5, 依赖:

        <dependency>
            <groupId>io.kubernetes</groupId>
            <artifactId>client-java</artifactId>
            <version>20.0.0</version>
        </dependency>

在执行: (V1Deployment)Yaml.load(yamlContent) 时报错: Unknown apiVersionKind apps/v1/Deployment is it registered?

经分析 /mnt/app/mvn-repo/io/kubernetes/client-java/20.0.0/client-java-20.0.0-sources.jar!/io/kubernetes/client/util/ModelMapper.java getClassNamesFromPackage 方法有问题,原代码如下:

private static List<String> getClassNamesFromPackage(ClassLoader classLoader, String pkg) throws IOException {
    ArrayList<String> names = new ArrayList<>();
    String packageName = pkg.replace(".", "/");
    URL packageURL = classLoader.getResource(packageName);

    if (packageURL.getProtocol().equals("jar")) {
      processJarPackage(packageURL, packageName, pkg, names);
    } else {
      processFilePackage(packageURL, pkg, names);
    }
    return names;
  }
  
  private static void processJarPackage(URL packageURL, String packageName, String pkg, ArrayList<String> names) throws IOException {
    String jarFileName = URLDecoder.decode(packageURL.getFile(), "UTF-8");
    JarFile jf = null;
    // jar: client in repository; nested: client in a fat jar
    if (jarFileName.startsWith("jar:") || jarFileName.startsWith("nested:")) {
      jf = ((JarURLConnection) packageURL.openConnection()).getJarFile();
    }
    // file: client is a file in target (unit test)
    if (jarFileName.startsWith("file:") ) {
      jarFileName = jarFileName.substring(5, jarFileName.indexOf("!"));
      jf = new JarFile(jarFileName);
    }
    if (jf == null) {
      logger.error("Loading classes from jar with error packageURL: {}", jarFileName);
      return;
    }
    logger.info("Loading classes from jar {}", jarFileName);
    Enumeration<JarEntry> jarEntries = jf.entries();
    while (jarEntries.hasMoreElements()) {
      processJarEntry(jarEntries.nextElement(), packageName, pkg, names);
    }
    jf.close();
  }
  
    private static void processJarEntry(JarEntry jarEntry, String packageName, String pkg, ArrayList<String> names) {
    String entryName = jarEntry.getName();
    if (entryName.startsWith(packageName) && entryName.length() > packageName.length() + 5) {
      entryName = entryName.substring(packageName.length() + 1, entryName.lastIndexOf('.'));
      names.add(pkg + "." + entryName);
    }
  }

image

原因是,在部署环境下, 扫描包时出错,扫描不到。修复如下:

    private static boolean inited = false;

    static void init() {
        if (inited) {
            return;
        }
        inited = true;
        initApiGroupMap();
        initApiVersionList();

        var names = findResources("classpath*:io/kubernetes/client/openapi/models/**/*.class");
        var modelMapperClass = ModelMapper.class;
        Field preBuiltField = null;
        try {
            preBuiltField = modelMapperClass.getDeclaredField("preBuiltClassesByGVK");
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }

        preBuiltField.setAccessible(true);

        Map<GroupVersionKind, Class<?>> preBuiltClassesByGVK = null;
        try {
            preBuiltClassesByGVK = (Map<GroupVersionKind, Class<?>>) preBuiltField.get(null);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        for (String classInfo : names) {
            Class<?> clazz = loadClass(classInfo, Yaml.class.getClassLoader());
            if (!KubernetesObject.class.isAssignableFrom(clazz)
                    && !KubernetesListObject.class.isAssignableFrom(clazz)) {
                continue;
            }

            Pair<String, String> groupAndOther = getApiGroup(clazz.getSimpleName());
            Pair<String, String> versionAndOther = getApiVersion(groupAndOther.getRight());

            String group = Strings.nullToEmpty(groupAndOther.getLeft());
            String version = versionAndOther.getLeft();
            String kind = versionAndOther.getRight();

            preBuiltClassesByGVK.put(new GroupVersionKind(group, version, kind), clazz);
        }
    }

    private static Pair<String, String> getApiGroup(String name) {
        return preBuiltApiGroups.entrySet().stream()
                .filter(e -> name.startsWith(e.getKey()))
                .map(e -> new ImmutablePair<>(e.getValue(), name.substring(e.getKey().length())))
                .findFirst()
                .orElse(new ImmutablePair<>(null, name));
    }

    private static Pair<String, String> getApiVersion(String name) {
        return preBuiltApiVersions.stream()
                .filter(v -> name.startsWith(v))
                .map(v -> new ImmutablePair<>(v.toLowerCase(), name.substring(v.length())))
                .findFirst()
                .orElse(new ImmutablePair<>(null, name));
    }

    private static Map<String, String> preBuiltApiGroups = new HashMap<>();

    private static void initApiGroupMap() {
        preBuiltApiGroups.put("Admissionregistration", "admissionregistration.k8s.io");
        preBuiltApiGroups.put("Apiextensions", "apiextensions.k8s.io");
        preBuiltApiGroups.put("Apiregistration", "apiregistration.k8s.io");
        preBuiltApiGroups.put("Apps", "apps");
        preBuiltApiGroups.put("Authentication", "authentication.k8s.io");
        preBuiltApiGroups.put("Authorization", "authorization.k8s.io");
        preBuiltApiGroups.put("Autoscaling", "autoscaling");
        preBuiltApiGroups.put("Batch", "batch");
        preBuiltApiGroups.put("Certificates", "certificates.k8s.io");
        preBuiltApiGroups.put("Core", "");
        preBuiltApiGroups.put("Extensions", "extensions");
        preBuiltApiGroups.put("Events", "events.k8s.io");
        preBuiltApiGroups.put("FlowControl", "flowcontrol.apiserver.k8s.io");
        preBuiltApiGroups.put("Networking", "networking.k8s.io");
        preBuiltApiGroups.put("Policy", "policy");
        preBuiltApiGroups.put("RbacAuthorization", "rbac.authorization.k8s.io");
        preBuiltApiGroups.put("Scheduling", "scheduling.k8s.io");
        preBuiltApiGroups.put("Settings", "settings.k8s.io");
        preBuiltApiGroups.put("Storage", "storage.k8s.io");
    }

    private static List<String> preBuiltApiVersions = new ArrayList<>();

    private static void initApiVersionList() {
        // Order important
        preBuiltApiVersions.add("V2beta1");
        preBuiltApiVersions.add("V2beta2");
        preBuiltApiVersions.add("V2alpha1");
        preBuiltApiVersions.add("V1beta2");
        preBuiltApiVersions.add("V1beta1");
        preBuiltApiVersions.add("V1alpha1");
        preBuiltApiVersions.add("V1");
        preBuiltApiVersions.add("V2");
    }

    private static Class<?> loadClass(String name, ClassLoader classLoader) {
        try {
            return Class.forName(name, false, classLoader);
        } catch (ClassNotFoundException e) {
            return null;
        }
    }

标签:apiVersionKind,String,preBuiltApiGroups,Unknown,registered,static,io,put,k8s
From: https://www.cnblogs.com/newsea/p/18072410

相关文章

  • java.net.UnknownHostException: api.weixin.qq.com解决办法
    java.net.UnknownHostException: api.weixin.qq.comat java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:175)at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)at java.net.Socket.connect(Socket.java:546)at sun.security.ssl.SSLSo......
  • TS-any vs unknown
    相同点:1.都是TS系统是顶层类型:any,unknown2.任何类型的值都可以赋值给该类型 any存在的问题:1.类型推断问题:any类型的变量不再进行类型检查,失去了TS的意义;所以对于那些类型不明显的变量,一定要显式声明类型,防止被推断为any2.污染问题:any类型的变量可以赋值给任意类型......
  • vscode 的sync的问题RequestFailed (UserDataSyncError) syncResource:unknown operat
    024-03-0708:58:24.361[error]RequestFailed(UserDataSyncError)syncResource:unknownoperationId:unknown:Connectionrefusedfortherequest'https://vscode-sync.trafficmanager.net/v1/manifest'.atu.D(c:\Debug\VSCode\resources\app\ou......
  • 「TFOI R1」Unknown Graph 题解
    这里是出题人题解。\(\text{SolutionOfProblemC:UnknownGraph.}\)题意还是很清晰的,这里就不再赘述题意了。首先如果没有\(q\)的限制,显然有一种贪心思想就是每个点每次选剩余入度最多的与之连边。但是因为限制,就无法保证贪心的正确性。那该怎么办呢?一个大提示:这题是......
  • Debug: tf_ditribute_strategy_worker.yaml: unknown field "spec.template.spec.node
    [ERROR:unknownfield"spec.template.spec.nodeAffinity"](base)maye@maye-Inspiron-5547:~/github_repository/tensorflow_ecosystem/distribution_strategy$kubectlapply-fmaye_template.yamlservice/dist-strat-example-worker-0createdservice/dis......
  • 解决MySQL设置时区时的错误Unknown or incorrect time zone: 'Asia/Shanghai'
    问题描述:在trino中配置了mysql.properties文件,但是通过trino客户端,执行命令showschemasfrommysql;查看数据库信息时报错:Errorlistingschemasforcatalogmysql:java.sql.SQLNonTransientConnectionException:Couldnotcreateconnectiontodatabaseserver.Attempted......
  • tar 解压文件时提示 Ignoring unknown extended header keyword
    在Linux上使用tar解压文件时出现下列提示:tar:Ignoringunknownextendedheaderkeyword'LIBARCHIVE.xattr.com.apple.quarantine'tar:Ignoringunknownextendedheaderkeyword'LIBARCHIVE.xattr.com.apple.provenance'tar:Ignoringunknownextendedhea......
  • archlinux xfce 出现[FAILED] Failed to mount /boot, systemctl status boot.mount出
    开机显示:[FAILED]Failedtomount/boot使用命令systemctlstatusboot.mount后出现mount:/boot:unknownfilesystemtype'vfat':pacman-Qilinux显示安装了6.7.arch3-1版本的内核而uname-a显示6.6.10-arch1-1版本的内核我的环境是archxfce+windows8.1个人原因......
  • MySQL修改安全策略时报错:ERROR 1193 (HY000): Unknown system variable ‘validate_pa
    我使用的版本是MySQL5.73,环境是LinuxCentOS7,其他版本不知道是否可行,望谅解。当我们想设置简单的密码的时候,看了别人发的如何修改安全策略的代码,如下:setglobalvalidate_password_policy=0;setglobalvalidate_password_length=1;但是当我们使用的时候,却报了这样一个......
  • MAC M1 ndk-build ERROR: Unknown host CPU architecture: arm64
    {https://blog.csdn.net/qq_35559358/article/details/125502740} 解决方法vi编辑ndk-build将里面的内容从   #!/bin/sh   DIR="$(cd"$(dirname"$0")"&&pwd)"   $DIR/build/ndk-build"$@"修改成   #!/bin/sh   DIR="$(c......