40EnforcePersonality 1.72 KB
Newer Older
1
#!/usr/bin/env python
2
3
4
5
6
7
8
9

### BEGIN TASK INFO
# Provides:		EnforcePersonality
# RunBefore:		UmountImage
# RunAfter:		MountImage
# Short-Description:	Inject files to the instance
### END TASK INFO

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
"""Personalize an Image by injecting files

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

"""

import sys
import os
import json
import datetime
import base64


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


def main():
32
33
34
35
36
37
38
39
40
    if not os.environ.has_key('SNF_IMAGE_TARGET'):
        sys.stderr.write('Error: SNF_IMAGE_TARGET variable is missing\n')
        return 1

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

41
    if os.environ.has_key('SNF_IMAGE_PERSONALITY'):
42
43
44
        osp_img_personality = os.environ['SNF_IMAGE_PERSONALITY']
        files = json.loads(osp_img_personality)
        for f in files:
45
46
47
48
            real_path = target + '/' + f['path']
            if os.path.lexists(real_path):
                backup_file = real_path + '.bak.' + timestamp()
                os.rename(real_path, backup_file)
49
50
51
            newfile = open(real_path, 'w')
            newfile.write(base64.b64decode(f['contents']))
            newfile.close()
52
53
            os.chmod(real_path, 0440)
        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
57
58
59
60
61
62
    return 0


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

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