Revision d4270a48

b/image_creator/os_type/windows.py
141 141
    @sysprep('Shrinking the last filesystem')
142 142
    def shrink(self):
143 143
        """Shrink the last filesystem. Make sure the filesystem is defragged"""
144
        pass
144

  
145
        # Query for the maximum number of reclaimable bytes
146
        cmd = (
147
            r'cmd /Q /C "SET SCRIPT=%TEMP%\QUERYMAX_%RANDOM%.TXT & ' +
148
            r'ECHO SELECT DISK 0 > %SCRIPT% & ' +
149
            'ECHO SELECT PARTITION %d >> %%SCRIPT%% & ' % self.last_part_num +
150
            r'ECHO SHRINK QUERYMAX >> %SCRIPT% & ' +
151
            r'ECHO EXIT >> %SCRIPT% & ' +
152
            r'DISKPART /S %SCRIPT% & ' +
153
            r'IF ERRORLEVEL 1 EXIT /B 1 & ' +
154
            r'DEL /Q %SCRIPT%"')
155

  
156
        stdout, stderr, rc = self._guest_exec(cmd)
157

  
158
        querymax = None
159
        for line in stdout.splitlines():
160
            # diskpart will return something like this:
161
            #
162
            #   The maximum number of reclaimable bytes is: xxxx MB
163
            #
164
            if line.find('reclaimable') >= 0:
165
                querymax = line.split(':')[1].split()[0].strip()
166
                assert querymax.isdigit(), \
167
                    "Number of reclaimable bytes not a number"
168

  
169
        if querymax is None:
170
            FatalError("Error in shrinking! "
171
                       "Couldn't find the max number of reclaimable bytes!")
172

  
173
        querymax = int(querymax)
174
        # From ntfsresize:
175
        # Practically the smallest shrunken size generally is at around
176
        # "used space" + (20-200 MB). Please also take into account that
177
        # Windows might need about 50-100 MB free space left to boot safely.
178
        # I'll give 100MB extra space just to be sure
179
        querymax -= 100
180

  
181
        if querymax < 0:
182
            self.out.warn("Not enought available space to shrink the image!")
183
            return
184

  
185
        cmd = (
186
            r'cmd /Q /C "SET SCRIPT=%TEMP%\QUERYMAX_%RANDOM%.TXT & ' +
187
            r'ECHO SELECT DISK 0 > %SCRIPT% & ' +
188
            'ECHO SELECT PARTITION %d >> %%SCRIPT%% & ' % self.last_part_num +
189
            'ECHO SHRINK DESIRED=%d >> %%SCRIPT%% & ' % querymax +
190
            r'ECHO EXIT >> %SCRIPT% & ' +
191
            r'DISKPART /S %SCRIPT% & ' +
192
            r'IF ERRORLEVEL 1 EXIT /B 1 & ' +
193
            r'DEL /Q %SCRIPT%"')
194

  
195
        stdout, stderr, rc = self._guest_exec(cmd)
196

  
197
        for line in stdout.splitlines():
198
            if line.find('shrunk') >= 0:
199
                self.out.output(line)
145 200

  
146 201
    def do_sysprep(self):
147 202
        """Prepare system for image creation."""

Also available in: Unified diff