Skip to content

Commit

Permalink
fix ansible exec fail
Browse files Browse the repository at this point in the history
  • Loading branch information
hgz6536 committed Jul 26, 2017
1 parent 8e25afd commit ea573af
Show file tree
Hide file tree
Showing 11 changed files with 161 additions and 97 deletions.
67 changes: 67 additions & 0 deletions devop/data/DsMySQL.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#!/usr/bin/env python
# _#_ coding:utf-8 _*_
from opman.models import (Log_Ansible_Model, Ansible_CallBack_Model_Result,
Global_Config, Ansible_CallBack_PlayBook_Result,
Log_Ansible_Playbook)


class AnsibleSaveResult(object):
class Model(object):
@staticmethod
def insert(logId, content):
try:
config = Global_Config.objects.get(id=1)
if config.ansible_model == 1:
return Ansible_CallBack_Model_Result.objects.create(
logId=logId,
content=content
)
except Exception as e:
return False

class PlayBook(object):
@staticmethod
def insert(logId, content):
try:
config = Global_Config.objects.get(id=1)
if config.ansible_playbook == 1:
return Ansible_CallBack_PlayBook_Result.objects.create(
logId=logId,
content=content
)
except Exception as e:
return False


class AnsibleRecord(object):
class Model(object):
@staticmethod
def insert(user, ans_model, ans_server, ans_args=None):
try:
config = Global_Config.objects.get(id=1)
if config.ansible_model == 1:
return Log_Ansible_Model.objects.create(
ans_user=user,
ans_server=ans_server,
ans_args=ans_args,
ans_model=ans_model,
)
except Exception as e:
return False

class PlayBook(object):
@staticmethod
def insert(user, ans_id, ans_name, ans_content, ans_server=None):
try:
config = Global_Config.objects.get(id=1)
if config.ansible_playbook == 1:
return Log_Ansible_Playbook.objects.create(
ans_user=user,
ans_server=ans_server,
ans_name=ans_name,
ans_id=ans_id,
ans_content=ans_content,
)
except Exception as e:
print(e)
return False
3 changes: 2 additions & 1 deletion devop/data/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ def getRedisConnection(db):
settings.REDSI_LPUSH_POOL = redis.ConnectionPool(host=args.get('host'), port=args.get('port'),db=args.get('db'))
pools = settings.REDSI_LPUSH_POOL
connection = redis.Redis(connection_pool=pools)
return connection
return connection

2 changes: 2 additions & 0 deletions devop/restapis/assets_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,7 @@ def asset_server_list(request, format=None):
data = request.data.get('data')
else:
data = request.data
print(data)
serializer = ServerSerializer(data = data)
if serializer.is_valid():
serializer.save()
Expand Down Expand Up @@ -446,6 +447,7 @@ def asset_server_detail(request, id, format=None):
assets.save()
recordAssets.delay(user=str(request.user), content="修改服务器资产:{ip}".format(ip=snippet.ip), type="server",
id=id)
print(data)
serializer = ServerSerializer(snippet,data=data)
if serializer.is_valid():
serializer.save()
Expand Down
3 changes: 2 additions & 1 deletion devop/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from django.views.generic.base import RedirectView
from devop.views.index import index, login, logout, noperm, config
from devop.views.user import user_center, user_manage, user, register, group, permission
from devop.views.app import apps_list, apps_model, apps_add, ansible_log
from devop.views.app import apps_list, apps_model, apps_add, ansible_log,ansible_run
from devop.views.depoy import deploy_add, deploy_list, deploy_ask, deploy_init,deploy_order,deploy_log
from devop.views.cron import cron_log, cron_add, cron_list, cron_config
from devop.views.assets import assets_config,assets_add,assets_list,assets_log,assets_modf,assets_view
Expand Down Expand Up @@ -51,6 +51,7 @@
url(r'^apps/model/$', apps_model),
url(r'^apps/playbook/add/$', apps_add),
url(r'^apps/log/$', ansible_log),
url(r'^apps/run/$',ansible_run),

url(r'^deploy_order/$', deploy_order),
url(r'^deploy_add', deploy_add),
Expand Down
6 changes: 3 additions & 3 deletions devop/utils/ansibleApi.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def add_dynamic_group(self, hosts, groupname, groupvars=None):
my_host.set_variable('ansible_ssh_private_key_file', ssh_key)

# set other variables
for key, value in host.iteritems():
for key, value in host.items():
if key not in ["hostname", "port", "username", "password"]:
my_host.set_variable(key, value)
# add to group
Expand Down Expand Up @@ -118,7 +118,7 @@ def v2_runner_on_ok(self, result, *args, **kwargs):
for remove_key in ('changed', 'invocation'):
if remove_key in result._result:
del result._result[remove_key]
if result._result.has_key('rc') and result._result.has_key('stdout'):
if 'rc' in result._result and 'stdout' in result._result:
data = "{host} | SUCCESS | rc={rc} >> \n{stdout}".format(host=result._host.get_name(),
rc=result._result.get('rc'),
stdout=result._result.get('stdout'))
Expand All @@ -131,7 +131,7 @@ def v2_runner_on_failed(self, result, *args, **kwargs):
for remove_key in ('changed', 'invocation'):
if remove_key in result._result:
del result._result[remove_key]
if result._result.has_key('rc') and result._result.has_key('stdout'):
if 'rc' in result._result and 'stdout' in result._result:
data = "{host} | FAILED | rc={rc} >> \n{stdout}".format(host=result._host.get_name(),
rc=result._result.get('rc'),
stdout=result._result.get('stdout'))
Expand Down
2 changes: 1 addition & 1 deletion devop/utils/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def chown(user, path):

def makeToken(strs):
m = hashlib.md5()
m.update(strs)
m.update(strs.encode("utf8"))
return m.hexdigest()


Expand Down
54 changes: 19 additions & 35 deletions devop/views/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,59 +14,43 @@
from opman.models import (Ansible_Playbook, Ansible_Playbook_Number,
Log_Ansible_Model, Log_Ansible_Playbook)
from devop.tasks import recordAnsibleModel, recordAnsiblePlaybook

from devop.data.DsMySQL import AnsibleRecord

@login_required()
def apps_model(request):
if request.method == "GET":
serverList = Server_Assets.objects.all()
return render(request, 'apps/apps_model.html', {"user": request.user, "serverList": serverList})
elif request.method == "POST" and request.user.has_perm('OpsManage.can_change_ansible_playbook'):
return render(request,'apps/apps_model.html',{"user":request.user,"ans_uuid":uuid.uuid4(),"serverList":serverList})
elif request.method == "POST" and request.user.has_perm('OpsManage.can_change_ansible_playbook'):
resource = []
sList = []
serverList = request.POST.getlist('ansible_server')
for server in serverList:
server_assets = Server_Assets.objects.get(id=server)
sList.append(server_assets.ip)
if server_assets.keyfile == 1:
resource.append({"hostname": server_assets.ip, "port": int(server_assets.port)})
else:
resource.append(
{"hostname": server_assets.ip, "port": int(server_assets.port), "username": server_assets.username,
"password": server_assets.passwd})
if len(request.POST.get('custom_model')) > 0:
model_name = request.POST.get('custom_model')
else:
model_name = request.POST.get('ansible_model', None)
redisKey = base.makeToken(strs=str(request.user) + "ansible_model")
if server_assets.keyfile == 1:resource.append({"hostname": server_assets.ip, "port": int(server_assets.port)})
else:resource.append({"hostname": server_assets.ip, "port": int(server_assets.port),"username": server_assets.username,"password": server_assets.passwd})
if len(request.POST.get('custom_model')) > 0:model_name = request.POST.get('custom_model')
else:model_name = request.POST.get('ansible_model',None)
redisKey = request.POST.get('ans_uuid')
#操作日志异步记录
# redisKey = base.makeToken(strs=str(request.user)+"ansible_model")
logId = AnsibleRecord.Model.insert(user=str(request.user),ans_model=model_name,ans_server=','.join(sList),ans_args=request.POST.get('ansible_agrs',None))
DsRedis.OpsAnsibleModel.delete(redisKey)
DsRedis.OpsAnsibleModel.lpush(redisKey, "[Start] Ansible Model: {model} ARGS:{args}".format(model=model_name,
args=request.POST.get(
'ansible_agrs',
"None")))
ANS = ANSRunner(resource, redisKey)
ANS.run_model(host_list=sList, module_name=model_name, module_args=request.POST.get('ansible_agrs', ""))
DsRedis.OpsAnsibleModel.lpush(redisKey, "[Start] Ansible Model: {model} ARGS:{args}".format(model=model_name,args=request.POST.get('ansible_agrs',"None")))
ANS = ANSRunner(resource,redisKey,logId)
ANS.run_model(host_list=sList,module_name=model_name,module_args=request.POST.get('ansible_agrs',""))
DsRedis.OpsAnsibleModel.lpush(redisKey, "[Done] Ansible Done.")
# 操作日志异步记录
recordAnsibleModel.delay(user=str(request.user), ans_model=model_name, ans_server=','.join(sList),
ans_args=request.POST.get('ansible_agrs', None))
return JsonResponse({'msg': "操作成功", "code": 200, 'data': []})
return JsonResponse({'msg':"操作成功","code":200,'data':[]})


@login_required()
def ansible_run(request):
if request.method == "POST":
if request.POST.get('model') == 'model':
strs = str(request.user) + "ansible_model"
redisKey = base.makeToken(strs)
msg = DsRedis.OpsAnsibleModel.rpop(redisKey)
elif request.POST.get('model') == 'playbook':
redisKey = request.POST.get('playbook_uuid')
msg = DsRedis.OpsAnsiblePlayBook.rpop(redisKey)
if msg:
return JsonResponse({'msg': msg, "code": 200, 'data': []})
else:
return JsonResponse({'msg': None, "code": 200, 'data': []})
redisKey = request.POST.get('ans_uuid')
msg = DsRedis.OpsAnsibleModel.rpop(redisKey)
if msg:return JsonResponse({'msg':str(msg),"code":200,'data':[]})
else:return JsonResponse({'msg':None,"code":200,'data':[]})


@login_required()
Expand Down
7 changes: 7 additions & 0 deletions opman/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -503,4 +503,11 @@ class Log_Cron_Config(models.Model):
create_time = models.DateTimeField(auto_now_add=True, blank=True, null=True, verbose_name='执行时间')


class Ansible_CallBack_Model_Result(models.Model):
logId = models.ForeignKey('Log_Ansible_Model')
content = models.TextField(verbose_name='输出内容', blank=True, null=True)


class Ansible_CallBack_PlayBook_Result(models.Model):
logId = models.ForeignKey('Log_Ansible_Playbook')
content = models.TextField(verbose_name='输出内容', blank=True, null=True)
Loading

0 comments on commit ea573af

Please sign in to comment.