Class: Spider::AppManager

Inherits:
Object show all
Defined in:
lib/spiderfw/setup/app_manager.rb

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Method Details

+ (Object) get_apps(apps, options = {})



63
64
65
66
67
68
# File 'lib/spiderfw/setup/app_manager.rb', line 63

def self.get_apps(apps, options={})
    specs = resolve(apps, options)
    manager = self.new
    manager.install(specs, options)
    return specs
end

+ (Boolean) git_available?



15
16
17
18
19
20
21
22
# File 'lib/spiderfw/setup/app_manager.rb', line 15

def self.git_available?
    begin
        require 'git'
        return true
    rescue LoadError => exc
        return false
    end
end

+ (Boolean) installed?(app)



8
9
10
11
12
13
# File 'lib/spiderfw/setup/app_manager.rb', line 8

def self.installed?(app)
    require 'spiderfw/home'
    Spider.init_base
    @home_apps ||= Spider.home.apps
    @home_apps[app]
end

+ (Object) post_run(specs, options = {})



175
176
177
178
# File 'lib/spiderfw/setup/app_manager.rb', line 175

def self.post_run(specs, options={})
    #require 'bundler'
    #Bundler::Installer.install(options[:home_path], Bundler.definitions, {})
end

+ (Object) resolve(apps, options = {})



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
# File 'lib/spiderfw/setup/app_manager.rb', line 32

def self.resolve(apps, options={})
    specs = []
    url = options[:url]
    unless url
        require 'spiderfw/spider'
        Spider.init_base
        url = Spider.config.get('app_server.url')
    end
    install = []
    update = []
    res = {:install => install, :update => update}
    return res if apps.empty?
    require 'spiderfw/setup/app_server_client'
    client = Spider::AppServerClient.new(url)
    if options[:no_deps]
        specs = client.get_specs(apps)
    else
        specs = client.get_deps(apps, :no_optional => !options[:optional])
    end
    specs.each do |spec|
        if prev = installed?(spec.app_id)
            if (options[:refresh] && options[:refresh].include?(spec.app_id) ) || (prev[:spec] && prev[:spec].version < spec.version)
                update << spec
            end
        else
            install << spec
        end
    end
    return res
end

+ (Object) tmp_path(home_path)



24
25
26
# File 'lib/spiderfw/setup/app_manager.rb', line 24

def self.tmp_path(home_path)
    tmp_path = File.join(home_path, 'tmp', 'app_update')
end

Instance Method Details

- (Object) do_install(spec, options)



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/spiderfw/setup/app_manager.rb', line 99

def do_install(spec, options)
    app_path = File.join(@home_path, "apps/#{spec.app_id}")
    raise "App #{spec.app_id} is already installed" if File.exists?(app_path)
    use_git = false
    if spec.git_repo && options[:use_git]
        use_git = true
    end
    if use_git && !self.class.git_available?
        Spider.output _("Can't install app #{spec.id} via git, since git gem is not available") % spec.app_id, :ERROR
    end
    if use_git
        git_install(spec, options)
    else
        pack_install(spec, options)
    end
end

- (Object) do_update(spec, options)



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/spiderfw/setup/app_manager.rb', line 117

def do_update(spec, options)
    use_git = false
    if spec.git_repo && !options[:no_git]
        app_path = File.join(@home_path, "apps/#{spec.app_id}")
        use_git = true if File.directory?(File.join(app_path, '.git'))
    end
    if use_git && !self.class.git_available?
        Spider.output _("Can't update app #{spec.id} via git, since git gem is not available") % spec.app_id, :ERROR
    end
    if use_git
        git_update(spec, options)
    else
        pack_update(spec, options)
    end
end

- (Object) git_install(spec, options = {})



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/spiderfw/setup/app_manager.rb', line 244

def git_install(spec, options={})
    require 'git'
    if ::File.exist?("apps/#{spec.id}")
        Spider.output _("%s already installed, skipping") % spec.id
        return
    end
    repo = Git.open(@home_path)
    repo_url = spec.git_repo_rw || spec.git_repo
    Spider.output _("Fetching %s from %s") % [spec.app_id, repo_url]

    if options[:ssh_user] && repo_url =~ /ssh:\/\/([^@]+@)?(.+)/
        repo_url = "ssh://#{options[:ssh_user]}@#{$2}"
    end

    ENV['GIT_WORK_TREE'] = nil
    Dir.chdir(@home_path) do
        `git submodule add #{repo_url} apps/#{spec.id}`
        `git submodule init`
        `git submodule update`
    end
    repo.add(['.gitmodules', "apps/#{spec.id}"])
    repo.commit(_("Added app %s") % spec.id) 
end

- (Object) git_update(spec, options = {})



304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/spiderfw/setup/app_manager.rb', line 304

def git_update(spec, options={})
    require 'git'
    home_repo = Git.open(@home_path)
    app_path = File.join(@home_path, "apps", spec.id)
    app_repo = Git.open(app_path)
    Spider.output _("Updating %s from %s") % [spec.app_id, spec.git_repo]
    Dir.chdir(app_path) do
        app_repo.branch('master').checkout
    end
    response = err = nil
    Dir.chdir(app_path) do
        response = `git --git-dir='#{app_path}/.git' pull origin master`
    end
    require 'ruby-debug'
    if response =~ /Aborting/
        Spider.output err, :ERROR
        raise "Unable to update"
    end
    Dir.chdir(app_path) do
        app_repo.reset('HEAD', :hard => true)
        app_repo.branch('master').checkout
    end
    
    home_repo.add("apps/#{spec.id}")
    begin
        home_repo.commit(_("Updated app %s") % spec.id) 
    rescue => exc
        raise unless exc.message =~ /no changes added to commit/
    end
end

- (Object) install(specs, options)



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
# File 'lib/spiderfw/setup/app_manager.rb', line 71

def install(specs, options)
    options[:home_path] ||= Dir.pwd
    @home_path = options[:home_path]
    all_specs = specs[:install] + specs[:update]

    pre_run(all_specs, options)
    specs[:install].each do |spec|
        do_install(spec, options)
    end
    pre_update(specs[:update], options)
    begin
        specs[:update].each do |spec|
            do_update(spec, options)
        end
        post_update(specs[:update], options)
    rescue => exc
        rollback_update
        raise
    end
    unless options[:no_activate]
        require 'spiderfw/spider'
        specs_hash = {}
        all_specs.each{ |s| specs_hash[s.app_id] = s }
        Spider.activate_apps(specs[:install].map{ |s| s.app_id }, specs_hash)
    end
    Spider.output _("Install done.")
end

- (Object) pack_install(spec, options = {})



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/spiderfw/setup/app_manager.rb', line 268

def pack_install(spec, options={})
    require 'rubygems/package'
    client = AppServerClient.new(spec.app_server)
    print _("Fetching %s from server... ") % spec.app_id
    tmp_path = client.fetch_app(spec.app_id)
    Spider.output _("Fetched.")
    dest = File.join(@home_path, "apps/#{spec.app_id}")
    FileUtils.mkdir_p(dest)
    open tmp_path, Gem.binary_mode do |io|
        Gem::Package::TarReader.new(io) do |reader|
            reader.each do |entry|
                dest_path = File.join(dest, entry.full_name)
                if entry.directory?
                    FileUtils.mkdir(dest_path)
                elsif entry.file?
                    File.open(dest_path, 'w') do |f|
                        f << entry.read
                    end
                end
            end
        end
    end
    if File.directory?(File.join(@home_path, '.git'))
        begin
            require 'git'
        rescue LoadError
        end
        begin
            repo = Git.open(home_path)
            repo.add("apps/#{spec.id}")
            repo.commit(_("Added app %s") % spec.id)
        rescue => exc
        end
    end
end

- (Object) pack_update(spec, options = {})



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/spiderfw/setup/app_manager.rb', line 335

def pack_update(spec, options={})
    require 'fileutils'
    require 'date'
    require 'time'
    app_path = File.join(@home_path, "apps/#{spec.id}")
    tmp_path = self.tmp_path
    FileUtils.mkdir_p(tmp_path)
    tmp_app_path = File.join(tmp_path, "#{spec.id}-update-#{DateTime.now.strftime('%Y%m%d-%H%M')}")
    begin
        FileUtils.mv(app_path, tmp_app_path)
    rescue Errno::EACCES
        if RUBY_PLATFORM =~ /win32|mingw/
            Spider.output(
                _("Can't update #{spec.id} app: ensure you have no files or folders of this app open"), 
                :ERROR
            )
        else
            Spider.output exc, :ERROR
        end
        exit
    end
    begin
        pack_install(spec, options)
        FileUtils.rm_rf(tmp_app_path)
    rescue => exc
        Spider.output _("Update of %s failed") % spec.id, :ERROR
        Spider.output exc, :ERROR
        FileUtils.rm_rf(app_path)
        FileUtils.mv(tmp_app_path, app_path)
        raise
    end
end

- (Object) post_update(specs, options)



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
# File 'lib/spiderfw/setup/app_manager.rb', line 192

def post_update(specs, options)
    return if specs.empty?
    require 'spiderfw/home'
    Spider.init_base
    @done_tasks = {}
    specs.each do |spec|
        prev_spec = @previous_apps[spec.app_id]
        prev_v = prev_spec.version if prev_spec
        @done_tasks[spec.app_id] = setup(spec.app_id, prev_v, spec.version)
    end
    Spider.output _("Doing cleanup...")
    @done_tasks.each do |app, tasks|
        next unless tasks
        tasks.each do |task|
            begin
                task.do_cleanup
            rescue => exc
                Spider.logger.error("Cleanup failed for #{app}:")
                Spider.logger.error(exc)
            end
        end
    end
    if options[:clear_cache]
        Spider.output _("Clearing cache...")
        Spider::Template.cache.clear!
        Spider::Layout.clear_compiled_folder!
    end
    if options[:restart]
        Spider.output _("Restarting server...")
        Spider.restart!
    end
    Spider.output _("Post-update done")
end

- (Object) pre_run(specs, options = {})



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
# File 'lib/spiderfw/setup/app_manager.rb', line 133

def pre_run(specs, options={})
    require 'rubygems'
    require 'rubygems/command.rb'
    require 'rubygems/dependency_installer.rb'
    unless options[:no_gems]
       gems = specs.map{ |s| s.gems_list }
       gems = gems.flatten.uniq
       gems.reject!{ |g| Spider.gem_available?(g) }
       unless gems.empty?
           Spider.output _("Installing the following needed gems:")
           Spider.output gems.inspect
           inst = Gem::DependencyInstaller.new
            gems.each do |g|
                inst.install g
            end
        end
        unless options[:no_optional_gems]
            gems = specs.map{ |s| s.gems_optional_list }
            gems = gems.flatten.uniq
            gems.reject!{ |g| Spider.gem_available?(g) }
            unless gems.empty?
                Spider.output _("Installing the following optional gems:")
                Spider.output gems.inspect
                inst = Gem::DependencyInstaller.new
                gems.each do |g|
                    begin
                        inst.install g
                    rescue => exc
                        Spider.output _("Unable to install optional gem %s:") % g
                        Spider.output exc, :ERROR
                    end
                end
            end
       end
        # unless Spider.gem_available?('bundler')
        #     puts _("Installing bundler gem")
        #     inst = Gem::DependencyInstaller.new
        #     inst.install 'bundler'
        # end
    end
end

- (Object) pre_update(specs, options = {})



180
181
182
183
184
185
186
187
188
189
190
# File 'lib/spiderfw/setup/app_manager.rb', line 180

def pre_update(specs, options={})
    tmp_path = File.join(self.tmp_path, "update-#{DateTime.now.strftime('%Y%m%d-%H%M')}")
    @backup_path = tmp_path
    FileUtils.mkdir_p(tmp_path)
    @previous_apps = {}
    specs.each do |spec|
        app_path = File.join(@home_path, 'apps', spec.id)
        FileUtils.cp_r(app_path, tmp_path)
        @previous_apps[spec.app_id] = App::AppSpec.load(File.join(app_path, "#{spec.id}.appspec"))
    end
end

- (Object) rollback_update



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/spiderfw/setup/app_manager.rb', line 226

def rollback_update
    Dir.new(@backup_path).each do |app|
        next if app[0].chr == '.'
        installed = File.join(@home_path, 'apps', app)
        FileUtils.rm_rf(installed) if File.exists?(installed)
        FileUtils.mv(File.join(@backup_path, app), installed)
    end
    if @done_tasks
        @done_tasks.each do |app, tasks|
            next unless tasks
            tasks.reverse.each do |task|
                task.down
            end
        end
    end
end

- (Object) setup(name, from = nil, to = nil)



368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/spiderfw/setup/app_manager.rb', line 368

def setup(name, from=nil, to=nil)
    require 'spiderfw/setup/setup_task'
    Spider.init
    Spider.load_app(name) unless Spider.apps[name]
    app = Spider.apps_by_short_name[name]
    path = app.setup_path
    unless to
        version = from
        from = nil
    end
    current = from || app.installed_version
    new_version = to || app.version
    return unless File.exist?(path)
    tasks = []
    if version
        tasks = ["#{@version}.rb"]
    else
        tasks = Dir.entries(path).reject{ |p| p[0].chr == '.'}.sort{ |a, b| 
            va = Gem::Version.new(File.basename(a, '.rb'))
            vb = Gem::Version.new(File.basename(b, '.rb'))
            va <=> vb
        }
        if from || to
            tasks.reject!{ |t|
                v = Gem::Version.new(File.basename(t, '.rb'))
                if from && v <= from
                    true
                elsif to && v > to
                    true
                else
                    false
                end
            }
        end
    end
    done_tasks = []
    
    tasks.each do |task|
        Spider.output _("Running setup task #{path+'/'+task}...")
        t = Spider::SetupTask.load("#{path}/#{task}")
        t.app = app
        begin
            done_tasks << t
            t.do_sync
            t.do_up
            Spider.output _("Setup task done")
        rescue => exc
            Spider.output exc, :ERROR
            done_tasks.reverse.each{ |dt| dt.do_down } # FIXME: rescue and log errors in down
            raise
        end
    end
    app.installed_version = app.version
    done_tasks
end

- (Object) tmp_path



28
29
30
# File 'lib/spiderfw/setup/app_manager.rb', line 28

def tmp_path
    self.class.tmp_path(@home_path)
end