Statistics
| Branch: | Tag: | Revision:

root / snf-image-helper / tasks / 40EnforcePersonality.py @ f93f9fae

History | View | Annotate | Download (1.6 kB)

1
#!/usr/bin/env python
2
#
3
# Copyright (c) 2011 Greek Research and Technology Network
4
#
5
"""Personalize an Image by injecting files
6

7
This hook injects files into the filesystem of an Image.
8
The files are passed to the hook through the Ganeti
9
OS interface and found in the variable OSP_IMG_PERSONALITY.
10

11
"""
12

    
13
import sys
14
import os
15
import json
16
import datetime
17
import base64
18

    
19

    
20
def timestamp():
21
    now = datetime.datetime.now()
22
    current_time = now.strftime("%Y%m%d.%H%M%S")
23
    return current_time
24

    
25

    
26
def main():
27
    if not os.environ.has_key('SNF_IMAGE_TARGET'):
28
        sys.stderr.write('Error: SNF_IMAGE_TARGET variable is missing\n')
29
        return 1
30

    
31
    target = os.environ['SNF_IMAGE_TARGET']
32
    if not os.path.isdir(target):
33
        sys.stderr.write('Error: Target: `'+target+'\' is not a directory.\n')
34
        return 2
35

    
36
    if os.environ.has_key('SNF_IMAGE_PERSONALITY'):
37
        osp_img_personality = os.environ['SNF_IMAGE_PERSONALITY']
38
        files = json.loads(osp_img_personality)
39
        for f in files:
40
            real_path = target + '/' + f['path']
41
            if os.path.lexists(real_path):
42
                backup_file = real_path + '.bak.' + timestamp()
43
                os.rename(real_path, backup_file)
44
            file = file(real_path, 'w')
45
            file.write(base64.b64decode(f['contents']))
46
            file.close()
47
            os.chmod(real_path, 0440)
48
        sys.stderr.write('Successful personalization of Image\n')
49
    else:
50
        sys.stderr.write('This Image has no personality (0 files to inject)\n')
51
    return 0
52

    
53

    
54
if __name__ == "__main__":
55
    sys.exit(main())
56

    
57
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :