Skip to content
This repository
tree: 1ed3b91f4e
Fetching contributors…

Cannot retrieve contributors at this time

file 282 lines (229 sloc) 7.279 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
# Copyright (c) 2009-2012 VMware, Inc.

module Bosh::Director
  class Config

    class << self
      include DnsHelper

      CONFIG_OPTIONS = [
        :base_dir,
        :cloud_options,
        :db,
        :dns,
        :dns_db,
        :dns_domain_name,
        :event_log,
        :logger,
        :max_tasks,
        :max_threads,
        :name,
        :process_uuid,
        :redis_options,
        :result,
        :revision,
        :task_checkpoint_interval,
        :uuid,
        :current_job,
        :encryption
      ]

      CONFIG_OPTIONS.each do |option|
        attr_accessor option
      end

      def clear
        CONFIG_OPTIONS.each do |option|
          self.instance_variable_set("@#{option}".to_sym, nil)
        end

        Thread.list.each do |thr|
          thr[:bosh] = nil
        end

        @blobstore = nil
        @compiled_package_cache = nil
        @nats = nil
        @nats_rpc = nil
        @cloud = nil
      end

      def configure(config)
        @base_dir = config["dir"]
        FileUtils.mkdir_p(@base_dir)

        # checkpoint task progress every 30 secs
        @task_checkpoint_interval = 30

        @logger = Logger.new(config["logging"]["file"] || STDOUT)
        @logger.level = Logger.const_get(config["logging"]["level"].upcase)
        @logger.formatter = ThreadFormatter.new

        # Event logger supposed to be overridden per task,
        # the default one does nothing
        @event_log = EventLog.new

        # by default keep only last 500 tasks in disk
        @max_tasks = config.fetch("max_tasks", 500).to_i

        @max_threads = config.fetch("max_threads", 32).to_i

        self.redis_options= {
          :host => config["redis"]["host"],
          :port => config["redis"]["port"],
          :password => config["redis"]["password"],
          :logger => @logger
        }

        state_json = File.join(@base_dir, "state.json")
        File.open(state_json, File::RDWR|File::CREAT, 0644) do |file|
          file.flock(File::LOCK_EX)
          state = Yajl::Parser.parse(file.read) || {}
          @uuid = state["uuid"] ||= SecureRandom.uuid
          file.rewind
          file.write(Yajl::Encoder.encode(state))
          file.flush
          file.truncate(file.pos)
        end

        @revision = get_revision

        @logger.info("Starting BOSH Director: #{VERSION} (#{@revision})")

        @process_uuid = SecureRandom.uuid
        @nats_uri = config["mbus"]

        @cloud_options = config["cloud"]
        @blobstore_options = config["blobstore"]

        @compiled_package_cache_options = config["compiled_package_cache"]
        @name = config["name"] || ""

        @blobstore = nil
        @compiled_package_cache = nil

        @db = configure_db(config["db"])
        @dns = config["dns"]
        @dns_domain_name = "bosh"
        if @dns
          @dns_db = configure_db(@dns["db"]) if @dns["db"]
          @dns_domain_name = canonical(@dns["domain_name"]) if @dns["domain_name"]
        end

        @encryption = config["encryption"]

        Bosh::Clouds::Config.configure(self)

        @lock = Monitor.new
      end

      def use_compiled_package_cache?
        !@compiled_package_cache_options.nil?
      end

      def get_revision
        Dir.chdir(File.expand_path("../../../../..", __FILE__))
        revision_command = "(cat REVISION 2> /dev/null || " +
            "git show-ref --head --hash=8 2> /dev/null || " +
            "echo 00000000) | head -n1"
        `#{revision_command}`.strip
      end

      def configure_db(db_config)
        patch_sqlite if db_config["database"].index("sqlite://") == 0

        connection_options = {}
        [:max_connections, :pool_timeout].each do |key|
          connection_options[key] = db_config[key.to_s]
        end

        db = Sequel.connect(db_config["database"], connection_options)
        db.logger = @logger
        db.sql_log_level = :debug
        db
      end

      def blobstore
        @lock.synchronize do
          if @blobstore.nil?
            provider = @blobstore_options["provider"]
            options = @blobstore_options["options"]
            @blobstore = Bosh::Blobstore::Client.create(provider, options)
          end
        end
        @blobstore
      end

      def compiled_package_cache_blobstore
        @lock.synchronize do
          if @compiled_package_cache_blobstore.nil? && use_compiled_package_cache?
            provider = @compiled_package_cache_options["provider"]
            options = @compiled_package_cache_options["options"]
            @compiled_package_cache_blobstore = Bosh::Blobstore::Client.create(provider, options)
          end
        end
        @compiled_package_cache_blobstore
      end

      def cloud_type
        if @cloud_options
          @cloud_options["plugin"]
        end
      end

      def cloud
        @lock.synchronize do
          if @cloud.nil?
            plugin = @cloud_options["plugin"]
            properties = @cloud_options["properties"]
            @cloud = Bosh::Clouds::Provider.create(plugin, properties)
          end
        end
        @cloud
      end

      def logger=(logger)
        @logger = logger
        if @redis_options
          @redis_options[:logger] = @logger
        end
        if redis?
          redis.client.logger = @logger
        end
      end

      def job_cancelled?
        @current_job.task_checkpoint if @current_job
      end
      alias_method :task_checkpoint, :job_cancelled?

      def redis_options=(options)
        @redis_options = options
      end

      def cloud_options=(options)
        @lock.synchronize do
          @cloud_options = options
          @cloud = nil
        end
      end

      def nats
        @lock.synchronize do
          if @nats.nil?
            @nats = NATS.connect(:uri => @nats_uri, :autostart => false)
          end
        end
        @nats
      end

      def nats_rpc
        @lock.synchronize do
          if @nats_rpc.nil?
            @nats_rpc = NatsRpc.new
          end
        end
        @nats_rpc
      end

      def redis
        threaded[:redis] ||= Redis.new(@redis_options)
      end

      def redis?
        !threaded[:redis].nil?
      end

      def dns_enabled?
        !@dns_db.nil?
      end

      def encryption?
        @encryption
      end

      def threaded
        Thread.current[:bosh] ||= {}
      end

      def patch_sqlite
        return if @patched_sqlite
        @patched_sqlite = true

        require "sequel"
        require "sequel/adapters/sqlite"

        Sequel::SQLite::Database.class_eval do
          def connect(server)
            opts = server_opts(server)
            opts[:database] = ':memory:' if blank_object?(opts[:database])
            db = ::SQLite3::Database.new(opts[:database])
            db.busy_handler do |retries|
              Bosh::Director::Config.logger.debug "SQLITE BUSY, retry ##{retries}"
              sleep(0.1)
              retries < 20
            end

            connection_pragmas.each { |s| log_yield(s) { db.execute_batch(s) } }

            class << db
              attr_reader :prepared_statements
            end
            db.instance_variable_set(:@prepared_statements, {})

            db
          end
        end
      end

    end

  end
end
Something went wrong with that request. Please try again.