2022-09-05 17:46:38 +02:00
|
|
|
// Copyright (C) 2022 NHR@FAU, University Erlangen-Nuremberg.
|
|
|
|
// All rights reserved.
|
|
|
|
// Use of this source code is governed by a MIT-style
|
|
|
|
// license that can be found in the LICENSE file.
|
2022-09-07 12:24:45 +02:00
|
|
|
package schema
|
2022-09-05 17:46:38 +02:00
|
|
|
|
|
|
|
import (
|
2022-09-20 07:05:01 +02:00
|
|
|
"embed"
|
2022-09-13 15:22:20 +02:00
|
|
|
"encoding/json"
|
2022-09-05 17:46:38 +02:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2022-09-20 10:27:23 +02:00
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
2022-09-05 17:46:38 +02:00
|
|
|
|
2022-09-13 15:22:20 +02:00
|
|
|
"github.com/ClusterCockpit/cc-backend/pkg/log"
|
|
|
|
"github.com/santhosh-tekuri/jsonschema/v5"
|
2022-09-05 17:46:38 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type Kind int
|
|
|
|
|
|
|
|
const (
|
|
|
|
Meta Kind = iota + 1
|
|
|
|
Data
|
2022-09-19 16:16:05 +02:00
|
|
|
Config
|
2022-09-07 12:24:45 +02:00
|
|
|
ClusterCfg
|
2022-09-05 17:46:38 +02:00
|
|
|
)
|
|
|
|
|
2022-09-20 07:05:01 +02:00
|
|
|
//go:embed schemas/*
|
|
|
|
var schemaFiles embed.FS
|
|
|
|
|
2022-09-13 15:22:20 +02:00
|
|
|
func Validate(k Kind, r io.Reader) (err error) {
|
2022-09-20 10:27:23 +02:00
|
|
|
jsonschema.Loaders["embedfs"] = func(s string) (io.ReadCloser, error) {
|
|
|
|
f := filepath.Join("schemas", strings.Split(s, "//")[1])
|
|
|
|
return schemaFiles.Open(f)
|
|
|
|
}
|
2022-09-05 17:46:38 +02:00
|
|
|
var s *jsonschema.Schema
|
|
|
|
|
|
|
|
switch k {
|
|
|
|
case Meta:
|
2022-09-20 10:27:23 +02:00
|
|
|
s, err = jsonschema.Compile("embedfs://job-meta.schema.json")
|
2022-09-05 17:46:38 +02:00
|
|
|
case Data:
|
2022-09-20 10:27:23 +02:00
|
|
|
s, err = jsonschema.Compile("embedfs://job-data.schema.json")
|
2022-09-07 12:24:45 +02:00
|
|
|
case ClusterCfg:
|
2022-09-20 10:27:23 +02:00
|
|
|
s, err = jsonschema.Compile("embedfs://cluster.schema.json")
|
2022-09-19 16:16:05 +02:00
|
|
|
case Config:
|
2022-09-20 10:27:23 +02:00
|
|
|
s, err = jsonschema.Compile("embedfs://config.schema.json")
|
2022-09-05 17:46:38 +02:00
|
|
|
default:
|
2023-01-19 16:59:14 +01:00
|
|
|
return fmt.Errorf("SCHEMA/VALIDATE > unkown schema kind: %v", k)
|
2022-09-05 17:46:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-09-13 15:22:20 +02:00
|
|
|
var v interface{}
|
|
|
|
if err := json.NewDecoder(r).Decode(&v); err != nil {
|
2023-01-23 18:48:06 +01:00
|
|
|
log.Errorf("Failed to decode %v", err)
|
2022-09-05 17:46:38 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-09-13 15:22:20 +02:00
|
|
|
if err = s.Validate(v); err != nil {
|
2023-01-19 16:59:14 +01:00
|
|
|
return fmt.Errorf("SCHEMA/VALIDATE > %#v", err)
|
2022-09-13 15:22:20 +02:00
|
|
|
}
|
|
|
|
|
2022-09-05 17:46:38 +02:00
|
|
|
return nil
|
|
|
|
}
|