service/src/service/environment.cr

112 lines
2.2 KiB
Crystal
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

require "specparser"
class Environment
enum Type
Prefix
RootFileSystem
end
getter name : String
getter type : Type = Type::Prefix
getter files = Array(ServiceDefinition::FileDefinition).new
# The place well put services data and configuration.
@root : String?
def initialize()
initialize "root"
end
def initialize(@name, type = "prefix")
@type = Type.parse type
@files = Array(ServiceDefinition::FileDefinition).new
# FIXME: Should this *really* be here?
# FIXME: $ENVIRONMENT_ROOT
@files << ServiceDefinition::FileDefinition.new "/srv/${ENVIRONMENT}",
"environment root",
creation_command: "mkdir -p /srv/${ENVIRONMENT} && chmod a+rwt /srv/${ENVIRONMENT}",
deletion_command: "rmdir /srv/${ENVIRONMENT}"
end
def initialize(@name, specs : SpecParser)
assignments = specs.assignments
assignments["type"].try &.as_s.tap do |type|
@type = Type.parse type
end
specs.sections.select(&.name.==("check")).each do |check|
@files << ServiceDefinition::FileDefinition.new check
end
end
def root
@root || "#{SERVED_DATA_DIRECTORY}/#{@name}"
end
class_getter root = Environment.new
class_getter all = [@@root] of Environment
def self.load(path)
return unless Dir.exists? path
Dir.each_child path do |child|
unless child.match /\.spec$/
next
end
file_path = "#{path}/#{child}"
begin
name = File.basename(child, ".spec")
specs = SpecParser.parse File.read(file_path)
environment = Environment.new name, specs
rescue e
STDERR << "error loading #{file_path}: " << e << "\n"
# FIXME: Print stacktrace? Debug mode?
next
end
@@all << environment
end
end
def write(dir : String)
File.write "#{dir}/#{@name}.spec", to_spec
end
def remove(dir : String)
File.delete "#{dir}/#{@name}.spec"
end
def to_spec
[
"type: #{@type.to_s}"
].join("\n") + "\n"
end
def self.get(name)
_def = @@all.find &.name.==(name)
if _def.nil?
raise ::Service::Exception.new "Environment '#{name}' does not exist."
end
_def
end
def get_provider(token)
Service.all.find do |service|
service.environment == self && service.provides? token
end.try &.id
end
def to_s
"#{name} (#{type.to_s.downcase})"
end
end