2011-11-04 91 views
4

我做了一个非常大的脚本来感觉我的初始数据到我的rails应用程序中。我的CSV和10000张图像中有大约3000行。用rails执行大脚本

后,也许300上传我得到这个消息:

/usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.9/lib/active_support/core_ext/kernel/agnostics.rb:7:in ``': Cannot allocate memory - identify -format %wx%h '/tmp/stream20111104-14788-1hsumv7.jpg[0]' (Errno::ENOMEM) 

我上传脚本:

if (row[28] != nil) 
    hotelalbum = HotelAlbumPhoto.find_or_create_by_title(h.title) 
    hotelalbum.description = "Album photo de l'hotel " + h.title.capitalize 
    hotelalbum.hotel_id = h.id 
    hotelalbum.save 

    files = Dir.glob('IMAGES/' + row[28].gsub(/\\/,'/') + '/*.jpg') 
    i =0 
    for file in files 
     i += 1 
     photopath = File.expand_path('../../import', __FILE__) + '/' + file 
     photoname = file.split('/').last 
     if (i==1) 
     hotelalbum.thumbnail = open(photopath) 
     hotelalbum.save 
     end 
     if (i==1) 
     h.thumbnail = open(photopath) 
     end 
     photo = HotelImage.find_or_create_by_image_file_name_and_hotel_album_photo_id(photoname,hotelalbum.id) 
     if (photo.image_file_size == nil || photo.image_file_name != photoname) 
      photo.image = open(photopath) 
      photo.activated = true 
      photo.alt = "Photo de l'hotel " + h.title 
      photo.save 
     else 
     puts photopath + ' already updated' 
     end 
    end 
end 

当我检查我的top命令的内存,我看到红宝石过程中使用更多的内存在每个上传。我如何管理这个?

谢谢大家帮忙

PS:我的服务器是虚拟机,拥有512MB显存,一种解决方案是inscrease这种记忆,但我希望能找到一个其他的。

+0

thoughtbot /回形针)? – tadman

+0

作为诊断的另一点,如果您禁用图像组件,它是否仍然存在内存问题? – tadman

回答

1

我不知道这个公开的功能定义在哪里,但我怀疑我没有看到相应的关闭...

更新更好的主意,改变photo.image = open(photopath)photo.image = File.read(photopath)

根据该文档,阅读:

Opens the file, optionally seeks to the given offset, then 
returns length bytes (defaulting to the rest of the file). 
read ensures the file is closed before returning. 
+0

似乎没有必要关闭......但你是对的,这很奇怪。 – Sebastien

+0

没有关闭,有可能文件句柄仍然在内存中,以及文件内容... – DGM

+0

你知道我该怎么关闭?谢谢 – Sebastien

0

看起来ImageMagick的的内存泄漏问题?也许这将有助于在处理大块大块或列表与in_groups_of,迫使垃圾收集GC.start每块后:你使用像[回形针]的附件管理器(https://github.com/

files.in_groups_of(100) {|chunk| 
    # process chunk 
    GC.start 
}