2011-11-04 88 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 
}