Skip to content

Commit cbf2b03

Browse files
committed
refactore cloud related tools
1 parent fd24a1e commit cbf2b03

13 files changed

Lines changed: 1539 additions & 401 deletions

agent/bindir/cloud-setup-agent.in

Lines changed: 97 additions & 138 deletions
Original file line numberDiff line numberDiff line change
@@ -1,148 +1,107 @@
1-
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
1+
#!/usr/bin/python
2+
import os
3+
import logging
4+
import sys
5+
import socket
6+
from cloud.cloudException import CloudRuntimeException, CloudInternalException
7+
from cloud.utilities import initLoging
8+
from cloud.configFileOps import configFileOps
9+
from cloud.globalEnv import globalEnv
10+
from cloud.networkConfig import networkConfig
11+
from cloud.syscfg import sysConfigFactory
312

4-
import sys, os, subprocess, errno, re, traceback, getopt
13+
from optparse import OptionParser
14+
15+
def getUserInputs():
16+
print "Welcome to myCloud Setup:"
517

6-
# ---- This snippet of code adds the sources path and the waf configured PYTHONDIR to the Python path ----
7-
# ---- We do this so cloud_utils can be looked up in the following order:
8-
# ---- 1) Sources directory
9-
# ---- 2) waf configured PYTHONDIR
10-
# ---- 3) System Python path
11-
for pythonpath in (
12-
"@PYTHONDIR@",
13-
os.path.join(os.path.dirname(__file__),os.path.pardir,os.path.pardir,"python","lib"),
14-
):
15-
if os.path.isdir(pythonpath): sys.path.insert(0,pythonpath)
16-
# ---- End snippet of code ----
17-
import cloud_utils
18-
from cloud_utils import stderr,CheckFailed,TaskFailed,backup_etc,restore_etc
19-
from cloud_utils import setup_agent_config,stop_service,enable_service
20-
from cloud_utils import exit as bail
21-
from cloud_utils import all, any
18+
cfo = configFileOps("/etc/cloud/agent/agent.properties")
19+
oldMgt = cfo.getEntry("host")
2220

21+
mgtSvr = raw_input("Please input the Management Server Name/IP:[%s]"%oldMgt)
22+
if mgtSvr == "":
23+
mgtSvr = oldMgt
24+
try:
25+
socket.getaddrinfo(mgtSvr, 443)
26+
except:
27+
print "Failed to resolve %s. Please input correct server name or IP."%mgtSvr
28+
exit(1)
2329

24-
#--------------- procedure starts here ------------
30+
oldToken = cfo.getEntry("zone")
31+
zoneToken = raw_input("Please input the Zone Token:[%s]"%oldToken)
32+
33+
if zoneToken == "":
34+
zoneToken = oldToken
2535

26-
# FÏXME for backup and restore: collect service state for all services so we can restore the system's runtime state back to what it was before
27-
# possible exit states:
28-
# a. system configuration needs administrator attention
29-
# b. automatic reconfiguration failed
30-
# c. process interrupted
31-
# d. everything was configured properly (exit status 0)
36+
try:
37+
defaultNic = networkConfig.getDefaultNetwork()
38+
except:
39+
print "Failed to get default route. Please configure your network to have a default route"
40+
exit(1)
41+
42+
defNic = defaultNic.name
43+
network = raw_input("Please choose which network used to create VM:[%s]"%defNic)
44+
if network == "":
45+
if defNic == "":
46+
print "You need to specifiy one of Nic or bridge on your system"
47+
exit(1)
48+
elif network == "":
49+
network = defNic
3250

33-
brname = "@PACKAGE@br0"
34-
servicename = "@PACKAGE@-agent"
35-
configfile = "@AGENTSYSCONFDIR@/agent.properties"
36-
backupdir = "@SHAREDSTATEDIR@/@AGENTPATH@/etcbackup"
51+
return [mgtSvr, zoneToken, network]
3752

38-
#=================== the magic happens here ====================
53+
if __name__ == '__main__':
54+
initLoging("/var/log/cloud/setupAgent.log")
55+
glbEnv = globalEnv()
3956

57+
glbEnv.mode = "Agent"
58+
glbEnv.agentMode = "Agent"
59+
parser = OptionParser()
60+
parser.add_option("-a", action="store_true", dest="auto", help="auto mode")
61+
parser.add_option("-m", "--host", dest="mgt", help="management server name or IP")
62+
parser.add_option("-z", "--zone", dest="zone", help="zone id")
63+
parser.add_option("-p", "--pod", dest="pod", help="pod id")
64+
parser.add_option("-c", "--cluster", dest="cluster", help="cluster id")
65+
parser.add_option("-g", "--guid", dest="guid", help="guid")
66+
parser.add_option("--pubNic", dest="pubNic", help="public nic")
67+
parser.add_option("--prvNic", dest="prvNic", help="private nic")
68+
parser.add_option("--guestNic", dest="guestNic", help="guest nic")
4069

41-
try:
42-
# parse cmd line
43-
opts, args = getopt.getopt(sys.argv[1:], "a", ["host=", "zone=", "pod=", "cluster=", "no-kvm", "guid=", "pubNic=", "prvNic="])
44-
host=None
45-
zone=None
46-
pod=None
47-
cluster=None
48-
guid=None
49-
pubNic=None
50-
prvNic=None
51-
autoMode=False
52-
do_check_kvm = True
53-
for opt, arg in opts:
54-
if opt == "--host":
55-
if arg != "":
56-
host = arg
57-
elif opt == "--zone":
58-
if arg != "":
59-
zone = arg
60-
elif opt == "--pod":
61-
if arg != "":
62-
pod = arg
63-
elif opt == "--cluster":
64-
if arg != "":
65-
cluster = arg
66-
elif opt == "--guid":
67-
if arg != "":
68-
guid = arg
69-
elif opt == "--pubNic":
70-
pubNic = arg
71-
elif opt == "--prvNic":
72-
prvNic = arg
73-
elif opt == "--no-kvm":
74-
do_check_kvm = False
75-
elif opt == "-a":
76-
autoMode=True
77-
78-
if autoMode:
79-
cloud_utils.setLogFile("/var/log/cloud/setupAgent.log")
80-
81-
stderr("Welcome to the Cloud Agent setup")
82-
stderr("")
83-
# pre-flight checks for things that the administrator must fix
84-
try:
85-
for f,n in cloud_utils.preflight_checks(
86-
do_check_kvm=do_check_kvm
87-
):
88-
stderr(n)
89-
f()
90-
except CheckFailed,e:
91-
stderr(str(e))
92-
bail(cloud_utils.E_NEEDSMANUALINTERVENTION,
93-
"Cloud Agent setup cannot continue until these issues have been addressed")
94-
95-
# system configuration tasks that our Cloud Agent setup performs
96-
97-
try:
98-
tasks = cloud_utils.config_tasks(brname, pubNic, prvNic)
99-
for t in tasks:
100-
t.setAutoMode(autoMode)
101-
if all( [ t.done() for t in tasks ] ):
102-
103-
stderr("All configuration tasks have been performed already")
104-
105-
else:
106-
107-
backup_etc(backupdir)
108-
try:
109-
# run all tasks that have not been done
110-
for t in [ n for n in tasks if not n.done() ]:
111-
t.run()
112-
except:
113-
# oops, something wrong, restore system to earlier state and re-raise
114-
stderr("A fatal issue has been detected -- restoring system configuration.\nPlease be patient; *do not* interrupt this process.")
115-
restore_etc(backupdir)
116-
for t in [ n for n in tasks if hasattr(n,"restore_state") ]:
117-
t.restore_state()
118-
raise
119-
120-
except (TaskFailed,CheckFailed),e:
121-
# some configuration task or post-flight check failed, we exit right away
122-
stderr(str(e))
123-
bail(cloud_utils.E_SETUPFAILED,"Cloud Agent setup failed")
124-
125-
setup_agent_config(configfile, host, zone, pod, cluster, guid, pubNic, prvNic)
126-
stderr("Enabling and starting the Cloud Agent")
127-
stop_service(servicename)
128-
enable_service(servicename)
129-
stderr("Cloud Agent restarted")
130-
131-
except KeyboardInterrupt,e:
132-
# user interrupted, we exit right away
133-
bail(cloud_utils.E_INTERRUPTED,"Cloud Agent setup interrupted")
134-
except SystemExit,e:
135-
# process above handled a failure then called bail(), which raises a SystemExit on CentOS
136-
sys.exit(e.code)
137-
except Exception,e:
138-
# at ths point, any exception has been dealt with cleanly by restoring system config from a backup
139-
# we just inform the user that there was a problem
140-
# and bail prematurely
141-
stderr("Cloud Agent setup has experienced an unrecoverable error. Please report the following technical details to Cloud.com.")
142-
traceback.print_exc()
143-
bail(cloud_utils.E_UNHANDLEDEXCEPTION,"Cloud Agent setup ended prematurely")
70+
(options, args) = parser.parse_args()
71+
if options.auto is None:
72+
userInputs = getUserInputs()
73+
glbEnv.mgtSvr = userInputs[0]
74+
glbEnv.zone = userInputs[1]
75+
glbEnv.defaultNic = userInputs[2]
76+
#generate UUID
77+
glbEnv.uuid = configFileOps("/etc/cloud/agent/agent.properties").getEntry("guid")
78+
if glbEnv.uuid == "":
79+
glbEnv.uuid = bash("uuidgen").getStdout()
80+
else:
81+
for para, value in options.__dict__.items():
82+
if value is None:
83+
print "Missing operand:%s"%para
84+
print "Try %s --help for more information"%sys.argv[0]
85+
sys.exit(1)
14486

145-
stderr("")
146-
stderr("Cloud Agent setup completed successfully")
147-
148-
# ========================= end program ========================
87+
glbEnv.uuid = options.guid
88+
glbEnv.mgtSvr = options.mgt
89+
glbEnv.zone = options.zone
90+
glbEnv.pod = options.pod
91+
glbEnv.cluster = options.cluster
92+
glbEnv.nics.append(options.prvNic)
93+
glbEnv.nics.append(options.pubNic)
94+
glbEnv.nics.append(options.guestNic)
95+
96+
print "Starting to configure your system:"
97+
syscfg = sysConfigFactory.getSysConfigFactory(glbEnv)
98+
try:
99+
syscfg.config()
100+
print "Cloud Agent setup is Done!"
101+
except (CloudRuntimeException,CloudInternalException), e:
102+
print e
103+
print "Try to restore your system:"
104+
try:
105+
syscfg.restore()
106+
except:
107+
pass

0 commit comments

Comments
 (0)