Add diskdump support in the helper (part 1)
[snf-image] / snf-image-helper / tasks / 40EnforcePersonality
1 #!/usr/bin/env python
2
3 ### BEGIN TASK INFO
4 # Provides:             EnforcePersonality
5 # RunBefore:            UmountImage
6 # RunAfter:             MountImage
7 # Short-Description:    Inject files to the instance
8 ### END TASK INFO
9
10 """Personalize an Image by injecting files
11
12 This hook injects files into the filesystem of an Image.
13 The files are passed to the hook through the Ganeti
14 OS interface and found in the variable OSP_IMG_PERSONALITY.
15
16 """
17
18 import sys
19 import os
20 import json
21 import datetime
22 import base64
23
24
25 def timestamp():
26     now = datetime.datetime.now()
27     current_time = now.strftime("%Y%m%d.%H%M%S")
28     return current_time
29
30
31 def main():
32     if not os.environ.has_key('SNF_IMAGE_TARGET'):
33         sys.stderr.write('Error: SNF_IMAGE_TARGET variable is missing\n')
34         return 1
35
36     target = os.environ['SNF_IMAGE_TARGET']
37     if not os.path.isdir(target):
38         sys.stderr.write('Error: Target: `'+target+'\' is not a directory.\n')
39         return 2
40
41     if os.environ.has_key('SNF_IMAGE_PERSONALITY'):
42         osp_img_personality = os.environ['SNF_IMAGE_PERSONALITY']
43         files = json.loads(osp_img_personality)
44         for f in files:
45             real_path = target + '/' + f['path']
46             if os.path.lexists(real_path):
47                 backup_file = real_path + '.bak.' + timestamp()
48                 os.rename(real_path, backup_file)
49             newfile = open(real_path, 'w')
50             newfile.write(base64.b64decode(f['contents']))
51             newfile.close()
52             os.chmod(real_path, 0440)
53         sys.stderr.write('Successful personalization of Image\n')
54     else:
55         sys.stderr.write('This Image has no personality (0 files to inject)\n')
56     return 0
57
58
59 if __name__ == "__main__":
60     sys.exit(main())
61
62 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :