summaryrefslogtreecommitdiff
path: root/open-vm-tools/toolbox/toolboxcmd-shrink.c
blob: d0b9cabb80ab897899c654e836327a1073f11398 (plain)
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
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
334
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
367
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/*********************************************************
 * Copyright (C) 2008 VMware, Inc. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation version 2.1 and no later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the Lesser GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
 *
 *********************************************************/

/*
 * toolboxcmd-shrink.c --
 *
 *     The shrink operations for toolbox-cmd
 */


#include <string.h>
#include <stdlib.h>

#ifndef _WIN32
#   include <signal.h>
#endif

#include "vm_assert.h"
#include "toolboxCmdInt.h"
#include "guestApp.h"
#include "wiper.h"
#include "vmware/guestrpc/tclodefs.h"
#include "vmware/tools/i18n.h"

#ifndef _WIN32
static void ShrinkWiperDestroy(int signal);
#endif

#define SHRINK_DISABLED_ERR                                       \
   "Shrink disk is disabled for this virtual machine.\n\n"        \
   "Shrinking is disabled for linked clones, parents of "         \
   "linked clones, \npre-allocated disks, snapshots, or due to "  \
   "other factors. \nSee the User's manual for more "             \
   "information.\n"

#define SHRINK_FEATURE_ERR                                                    \
   "The shrink feature is not available,\n\n"                                 \
   "either because you are running an old version of a VMware product, "      \
   "or because too many communication channels are open.\n\n"                 \
   "If you are running an old version of a VMware product, you should "       \
   "consider upgrading.\n\n"                                                  \
   "If too many communication channels are open, you should power off your "  \
   "virtual machine and then power it back on.\n"

#define SHRINK_CONFLICT_ERR                                 \
   "Error, The Toolbox believes disk shrinking is "         \
   "enabled while the host believes it is disabled.\n\n "   \
   "Please close and reopen the Toolbox to synchronize "    \
   "it with the host.\n"

static Wiper_State *wiper = NULL;

#define WIPER_STATE_CMD "disk.wiper.enable"

typedef enum {
   WIPER_UNAVAILABLE,
   WIPER_DISABLED,
   WIPER_ENABLED,
} WiperState;


/*
 *-----------------------------------------------------------------------------
 *
 * ShrinkGetWiperState  --
 *
 *      Gets the state of the shrink backend in the host.
 *
 * Results:
 *      The shrink backend state.
 *
 * Side effects:
 *      None
 *
 *-----------------------------------------------------------------------------
 */

static WiperState
ShrinkGetWiperState(void)
{
   char *result = NULL;
   size_t resultLen;
   WiperState state = WIPER_UNAVAILABLE;

   if (ToolsCmd_SendRPC(WIPER_STATE_CMD, sizeof WIPER_STATE_CMD - 1,
                        &result, &resultLen)) {
      if (resultLen == 1 && strcmp(result, "1") == 0) {
         state = WIPER_ENABLED;
      } else {
         state = WIPER_DISABLED;
      }
   }
   free(result);
   return state;
}


/*
 *-----------------------------------------------------------------------------
 *
 * ShrinkGetMountPoints  --
 *
 *      Gets a list of wiper partitions.
 *
 * Results:
 *      The WiperPartion_List.
 *
 * Side effects:
 *      Prints to stderr on errors.
 *
 *-----------------------------------------------------------------------------
 */

static Bool
ShrinkGetMountPoints(WiperPartition_List *pl) // OUT: Known mount points
{
   WiperState state = ShrinkGetWiperState();

   switch (state) {
   case WIPER_UNAVAILABLE:
      ToolsCmd_PrintErr("%s",
                        SU_(disk.shrink.unavailable, SHRINK_FEATURE_ERR));
      break;

   case WIPER_DISABLED:
      ToolsCmd_PrintErr("%s",
                        SU_(disk.shrink.disabled, SHRINK_DISABLED_ERR));
      break;

   case WIPER_ENABLED:
      if (WiperPartition_Open(pl)) {
         return TRUE;
      }

      ToolsCmd_PrintErr("%s",
                        SU_(disk.shrink.partition.error,
                           "Unable to collect partition data.\n"));
      break;

   default:
      NOT_REACHED();
   }

   return FALSE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * ShrinkList  --
 *
 *      Prints mount points to stdout.
 *
 * Results:
 *      EXIT_SUCCESS.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

static int
ShrinkList(void)
{
   WiperPartition_List plist;
   DblLnkLst_Links *curr;
   uint32 countShrink = 0;
   WiperState wstate = ShrinkGetWiperState();

   if (!ShrinkGetMountPoints(&plist)) {
      return EX_TEMPFAIL;
   }

   DblLnkLst_ForEach(curr, &plist.link) {
      WiperPartition *p = DblLnkLst_Container(curr, WiperPartition, link);
      if (p->type != PARTITION_UNSUPPORTED &&
          (wstate == WIPER_ENABLED || Wiper_IsWipeSupported(p))) {
         g_print("%s\n", p->mountPoint);
         countShrink++;
      }
   }

   WiperPartition_Close(&plist);

   /*
    * No shrinkable/wipable disks found.
    */
   if (countShrink == 0) {
      g_debug("No shrinkable disks found\n");
      ToolsCmd_PrintErr("%s",
                        SU_(disk.shrink.disabled, SHRINK_DISABLED_ERR));
      return EX_TEMPFAIL;
   }

   return EXIT_SUCCESS;
}


/*
 *-----------------------------------------------------------------------------
 *
 * ShrinkDiskSendRPC  --
 *
 *      Shrink all shrinkable disks/partitions, returning only when the shrink
 *      RPC operation is done or canceled.
 *
 * Results:
 *      EXIT_SUCCESS on success.
 *      EX_TEMPFAIL on failure.
 *
 * Side effects:
 *      Prints to stderr on errors.
 *
 *-----------------------------------------------------------------------------
 */

static int
ShrinkDiskSendRPC(void)
{
   char *result;
   size_t resultLen;

   ToolsCmd_PrintErr("\n");

   if (ToolsCmd_SendRPC(DISK_SHRINK_CMD, sizeof DISK_SHRINK_CMD - 1,
                        &result, &resultLen)) {
      ToolsCmd_Print("%s",
                     SU_(disk.shrink.complete, "Disk shrinking complete.\n"));
      return EXIT_SUCCESS;
   }

   ToolsCmd_PrintErr(SU_(disk.shrink.error, "Error while shrinking: %s\n"), result);
   return EX_TEMPFAIL;
}


/*
 *-----------------------------------------------------------------------------
 *
 * ShrinkDoAllDiskShrinkOnly  --
 *
 *      Shrink all shrinkable disks/partitions if it is enabled. Layered around
 *      ShrinkDoAllDiskShrinkCommon. This routine does not invoke the disk wipe
 *      operation step.
 *
 * Results:
 *      EXIT_SUCCESS on success.
 *      EX_TEMPFAIL on failure.
 *
 * Side effects:
 *      Prints to stderr on errors.
 *
 *-----------------------------------------------------------------------------
 */

static int
ShrinkDoAllDiskShrinkOnly(void)
{
   WiperPartition_List plist;
   DblLnkLst_Links *curr;
   Bool canShrink = FALSE;
   WiperState wstate = ShrinkGetWiperState();

#ifndef _WIN32
   signal(SIGINT, ShrinkWiperDestroy);
#endif

   if (!ShrinkGetMountPoints(&plist)) {
      return EX_TEMPFAIL;
   }

   DblLnkLst_ForEach(curr, &plist.link) {
      WiperPartition *p = DblLnkLst_Container(curr, WiperPartition, link);
      if (p->type != PARTITION_UNSUPPORTED &&
          (wstate == WIPER_ENABLED || Wiper_IsWipeSupported(p))) {
         canShrink = TRUE;
         break;
      }
   }

   WiperPartition_Close(&plist);

   /*
    * Verify that shrinking is permitted on at least 1 disk.
    */

   if (!canShrink) {
      g_debug("No shrinkable disks found\n");
      ToolsCmd_PrintErr("%s",
                        SU_(disk.shrink.disabled, SHRINK_DISABLED_ERR));
      return EX_TEMPFAIL;
   }

   return ShrinkDiskSendRPC();
}


/*
 *-----------------------------------------------------------------------------
 *
 * ShrinkDoWipeAndShrink  --
 *
 *      Wipe a single partition, returning only when the wiper
 *      operation is done or canceled.
 *      Caller can optionally indicate whether a disk shrink operation is required
 *      to be performed after the wipe operation or not.
 *
 * Results:
 *      EXIT_SUCCESS on success.
 *      EX_OSFILE if partition is not found.
 *      EX_TEMPFAIL on failure.
 *
 * Side effects:
 *      The wipe operation will fill the partition with dummy files.
 *      Prints to stderr on errors.
 *
 *-----------------------------------------------------------------------------
 */

static int
ShrinkDoWipeAndShrink(char *mountPoint,         // IN: mount point
                      gboolean quiet,           // IN: verbosity flag
                      gboolean performShrink)   // IN: perform a shrink operation
{
   int i;
   int progress = 0;
   unsigned char *err;
   WiperPartition *part = NULL;
   WiperPartition_List plist;
   int rc;

#if defined(_WIN32)
   DWORD currPriority = GetPriorityClass(GetCurrentProcess());
#else
   signal(SIGINT, ShrinkWiperDestroy);
#endif

   if (ShrinkGetMountPoints(&plist)) {
      DblLnkLst_Links *curr, *nextElem;
      DblLnkLst_ForEachSafe(curr, nextElem, &plist.link) {
         WiperPartition *p = DblLnkLst_Container(curr, WiperPartition, link);
         if (toolbox_strcmp(p->mountPoint, mountPoint) == 0) {
            WiperSinglePartition_Close(part);
            part = p;
            /*
             * Detach the element we are interested in so it is not
             * destroyed when we call WiperPartition_Close.
             */
            DblLnkLst_Unlink1(&part->link);
            if (part->type != PARTITION_UNSUPPORTED) {
               break;
            }
         }
      }
      WiperPartition_Close(&plist);
   }

   if (part == NULL) {
      ToolsCmd_PrintErr(SU_(disk.shrink.partition.notfound,
                            "Unable to find partition %s\n"),
                        mountPoint);
      return EX_OSFILE;
   }

   if (part->type == PARTITION_UNSUPPORTED) {
      ToolsCmd_PrintErr(SU_(disk.shrink.partition.unsupported,
                            "Partition %s is not shrinkable\n"),
                        part->mountPoint);
      rc = EX_UNAVAILABLE;
      goto out;
   }

   /*
    * Verify that wiping/shrinking are permitted before going through with the
    * wiping operation.
    */
   if (!ShrinkGetWiperState() == WIPER_ENABLED && !Wiper_IsWipeSupported(part)) {
      g_debug("%s cannot be wiped / shrunk\n", mountPoint);
      ToolsCmd_PrintErr("%s",
                        SU_(disk.shrink.disabled, SHRINK_DISABLED_ERR));
      rc = EX_TEMPFAIL;
      goto out;
   }

   /*
    * During the initial 'wipe' process, the Toolbox CLI first fills the
    * entire guest's disk space with files filled with zeroes. During this step,
    * user may notice few warning messages related to 'low disk space' in the
    * guest operating system. We need to print a warning message to disregard
    * such warnings in the guest operating system.
    */
   if (performShrink) {
      ToolsCmd_Print("%s", SU_(disk.shrink.ignoreFreeSpaceWarnings,
                               "Please disregard any warnings about disk space "
                               "for the duration of shrink process.\n"));
   } else {
      ToolsCmd_Print("%s", SU_(disk.wipe.ignoreFreeSpaceWarnings,
                               "Please disregard any warnings about disk space "
                               "for the duration of wipe process.\n"));
   }

   wiper = Wiper_Start(part, MAX_WIPER_FILE_SIZE);

#if defined(_WIN32)
   /*
    * On Win32, lower the process priority during wipe, so other applications
    * can still run (sort of) normally while we're filling the disk.
    */
   if (!SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS)) {
      g_debug("Unable to lower process priority: %u.", GetLastError());
   }
#endif

   while (progress < 100 && wiper != NULL) {
      err = Wiper_Next(&wiper, &progress);
      if (strlen(err) > 0) {
         if (strcmp(err, "error.create") == 0) {
            ToolsCmd_PrintErr("%s",
                              SU_(disk.wiper.file.error,
                                  "Error, Unable to create wiper file.\n"));
         } else {
            ToolsCmd_PrintErr(SU_(disk.wiper.error, "Error: %s"), err);
         }

         rc = EX_TEMPFAIL;
         break;
      }

      if (!quiet) {
         g_print(SU_(disk.wiper.progress, "\rProgress: %d"), progress);
         g_print(" [");
         for (i = 0; i <= progress / 10; i++) {
            putchar('=');
         }
         g_print(">%*c", 10 - i + 1, ']');
         fflush(stdout);
      }
   }

#if defined(_WIN32)
   /* Go back to our original priority. */
   if (!SetPriorityClass(GetCurrentProcess(), currPriority)) {
      g_debug("Unable to restore process priority: %u.", GetLastError());
   }
#endif

   rc = EXIT_SUCCESS;
   if (progress >= 100 && performShrink) {
      rc = ShrinkDiskSendRPC();
   } else if (progress < 100) {
      rc = EX_TEMPFAIL;
   } else {
      g_debug("Shrinking skipped.\n");
   }

   if (rc != EXIT_SUCCESS) {
      ToolsCmd_PrintErr("%s",
                        SU_(disk.shrink.incomplete, "Shrinking not completed.\n"));
   }

out:
   WiperSinglePartition_Close(part);
   free(wiper);
   wiper = NULL;
   return rc;
}


#ifndef _WIN32
/*
 *-----------------------------------------------------------------------------
 *
 * ShrinkWiperDestroy  --
 *
 *      Catch SIGINT and cancel wiper operation.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The wipe operation will be canceled, and "zero" files removed.
 *      We will also exit the vmware-toolbox-cmd program.
 *
 *-----------------------------------------------------------------------------
 */

void
ShrinkWiperDestroy(int signal)	// IN: Signal caught
{
   if (wiper != NULL) {
      Wiper_Cancel(&wiper);
      wiper = NULL;
   }
   ToolsCmd_Print("%s", SU_(disk.shrink.canceled, "Disk shrink canceled.\n"));
   exit(EXIT_SUCCESS);
}
#endif


/*
 *-----------------------------------------------------------------------------
 *
 * Disk_Command --
 *
 *      Handle and parse disk commands.
 *
 * Results:
 *      Returns EXIT_SUCCESS on success.
 *      Returns the appropriate exit code on errors.
 *
 * Side effects:
 *      Might shrink disk
 *
 *-----------------------------------------------------------------------------
 */

int
Disk_Command(char **argv,      // IN: command line arguments
             int argc,         // IN: The length of the command line arguments
             gboolean quiet)   // IN
{
   if (toolbox_strcmp(argv[optind], "list") == 0) {
      return ShrinkList();
   } else if (toolbox_strcmp(argv[optind], "shrink") == 0) {
      if (++optind >= argc) {
         ToolsCmd_MissingEntityError(argv[0], SU_(arg.mountpoint, "mount point"));
      } else {
         return ShrinkDoWipeAndShrink(argv[optind], quiet,
                                      TRUE /* perform shrink */);
      }
   } else if (toolbox_strcmp(argv[optind], "wipe") == 0) {
      if (++optind >= argc) {
         ToolsCmd_MissingEntityError(argv[0], SU_(arg.mountpoint, "mount point"));
      } else {
         return ShrinkDoWipeAndShrink(argv[optind], quiet,
                                      FALSE /* do not perform shrink */);
      }
   } else if (toolbox_strcmp(argv[optind], "shrinkonly") == 0) {
      return ShrinkDoAllDiskShrinkOnly();
   } else {
      ToolsCmd_UnknownEntityError(argv[0],
                                  SU_(arg.subcommand, "subcommand"),
                                  argv[optind]);
   }
   return EX_USAGE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * Disk_Help --
 *
 *      Prints the help for the disk command.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *-----------------------------------------------------------------------------
 */

void
Disk_Help(const char *progName, // IN: The name of the program obtained from argv[0]
          const char *cmd)      // IN
{
   g_print(SU_(help.disk, "%s: perform disk shrink operations\n"
                          "Usage: %s %s <subcommand> [args]\n\n"
                          "Subcommands:\n"
                          "   list: list available locations\n"
                          "   shrink <location>: wipes and shrinks a file system at the given location\n"
                          "   shrinkonly: shrinks all disks\n"
                          "   wipe <location>: wipes a file system at the given location\n"),
           cmd, progName, cmd);
}