一、总目录

二、具体代码

salt

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:luoahong import os,sys if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Stark.settings")
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#print(BASE_DIR)
sys.path.append(BASE_DIR)
from Arya.action_list import actions
from Arya.backends.utils import ArgvManagement
obj = ArgvManagement(sys.argv)

models

from django.db import models
# Create your models here.
class Host(models.Model):
hostname = models.CharField(max_length=128,unique=True)
key = models.TextField()
status_choices = ((0,'Waiting Approval'),
(1,'Accepted'),
(2,'Rejected')) os_type_choices =(
('redhat','Redhat\CentOS'),
('ubuntu','Ubuntu'),
('suse','Suse'),
('windows','Windows'),
) os_type = models.CharField(choices=os_type_choices,max_length=64,default='redhat')
status = models.SmallIntegerField(choices=status_choices,default=0) def __str__(self):
return self.hostname
class HostGroup(models.Model):
name = models.CharField(max_length=64,unique=True)
hosts = models.ManyToManyField(Host,blank=True) def __str__(self):
return self.name

admin

from django.contrib import admin

# Register your models here.
from Arya import models
admin.site.register(models.Host)
admin.site.register(models.HostGroup)

base_module

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:luoahong class BaseSaltModule(object):
def __init__(self,sys_argvs,db_models,settings):
self.db_models = db_models
self.settings = settings
self.sys_argvs = sys_argvs def get_selected_os_types(self):
data = {}
for host in self.host_list:
data[host.os_type] = []
print('--->data',data)
return data
def process(self):
self.fetch_hosts()
self.config_data_dic = self.get_selected_os_types()
def require(self,*args,**kwargs):
pass
def fetch_hosts(self):
print('--fetching hosts---') if '-h' in self.sys_argvs or '-g' in self.sys_argvs:
host_list = []
if '-h' in self.sys_argvs:
host_str_index = self.sys_argvs.index('-h') +1
if len(self.sys_argvs) <= host_str_index:
exit("host argument must be provided after -h")
else: #get the host str
host_str = self.sys_argvs[host_str_index]
host_str_list = host_str.split(',')
host_list += self.db_models.Host.objects.filter(hostname__in=host_str_list)
if '-g' in self.sys_argvs:
group_str_index = self.sys_argvs.index('-g') +1
if len(self.sys_argvs) <= group_str_index:
exit("group argument must be provided after -g")
else: #get the group str
group_str = self.sys_argvs[group_str_index]
group_str_list = group_str.split(',')
group_list = self.db_models.HostGroup.objects.filter(name__in=group_str_list)
for group in group_list:
host_list += group.hosts.select_related()
self.host_list = set(host_list)
return True
print('----host list:', host_list)
else:
exit("host [-h] or group[-g] argument must be provided") def syntax_parser(self,section_name,mod_name,mod_data):
print("-going to parser state data:",section_name,mod_name)
for state_item in mod_data:
print("\t",state_item)
for key,val in state_item.items():
if hasattr(self,key):
state_func = getattr(self,key)
state_func(val)
else:
exit("Error:module [%s] has no argument [%s]" %( mod_name,key ))

utils

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Alex Li
import sys from Arya import action_list
import django
django.setup() from Stark import settings
from Arya import models
class ArgvManagement(object):
'''
接收用户指令并分配到相应模块
'''
def __init__(self,argvs):
self.argvs = argvs
self.argv_parse() def help_msg(self):
print("Available modules:")
for registered_module in action_list.actions:
print(" %s" % registered_module)
exit()
def argv_parse(self):
#print(self.argvs)
if len(self.argvs) <2:
self.help_msg()
module_name = self.argvs[1]
if '.' in module_name:
mod_name,mod_method = module_name.split('.')
module_instance = action_list.actions.get(mod_name)
if module_instance:#matched
module_obj = module_instance(self.argvs,models,settings)
module_obj.process() #提取 主机
if hasattr(module_obj,mod_method):
module_method_obj = getattr(module_obj,mod_method)#解析任务,发送到队列,取任务结果
module_method_obj() #调用指定的指令
else:
exit("module [%s] doesn't have [%s] method" % (mod_name,mod_method))
else:
exit("invalid module name argument")

cmd

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:luoahong from Arya.backends.base_module import BaseSaltModule
class CMD(BaseSaltModule):
print('in cmd module ')

file

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:luoahong
from Arya.backends.base_module import BaseSaltModule
class File(BaseSaltModule):
pass

group

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:luoahong
from Arya.backends.base_module import BaseSaltModule
class Group(BaseSaltModule): def gid(self,*args,**kwargs):
pass

pkg

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:luoahong
from Arya.backends.base_module import BaseSaltModule
class Pkg(BaseSaltModule): pass

service

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:luoahong
from Arya.backends.base_module import BaseSaltModule
class Service(BaseSaltModule):
pass

state

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:luoahong
from Arya.backends.base_module import BaseSaltModule
import os class State(BaseSaltModule): def load_state_files(self,state_filename):
from yaml import load, dump
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
state_file_path = "%s/%s" %(self.settings.SALT_CONFIG_FILES_DIR,state_filename)
if os.path.isfile(state_file_path):
with open(state_file_path) as f:
data = load(f.read(), Loader=Loader)
return data
else:
exit("%s is not a valid yaml config file" % state_filename) def apply(self):
'''
1. load the configurations file
2. parse it
3. create a task and sent it to the MQ
4. collect the result with task-callback id
:return:
''' if '-f' in self.sys_argvs:
yaml_file_index = self.sys_argvs.index('-f') + 1
try:
yaml_filename = self.sys_argvs[yaml_file_index]
state_data = self.load_state_files(yaml_filename)
#print('state data:',state_data) for os_type,os_type_data in self.config_data_dic.items(): #按照不同的操作系统单独生成一份配置文件
for section_name,section_data in state_data.items():
print('Section:',section_name) for mod_name,mod_data in section_data.items():
base_mod_name = mod_name.split(".")[0]
plugin_file_path = "%s/%s.py" % (self.settings.SALT_PLUGINS_DIR,base_mod_name)
if os.path.isfile(plugin_file_path):
#导入 模块 module_plugin = __import__('plugins.%s' %base_mod_name)
special_os_module_name = "%s%s" %(os_type.capitalize(),base_mod_name.capitalize())
#print('dir module plugin:',module_plugin,base_mod_name)
#getattr(module_plugin,base_mod_name)
module_file= getattr(module_plugin, base_mod_name) # 这里才是真正导入模块
if hasattr(module_file, special_os_module_name): #判断有没有根据操作系统的类型进行特殊解析 的类,在这个文件里
module_instance = getattr(module_file, special_os_module_name)
else:
module_instance = getattr(module_file, base_mod_name.capitalize()) #开始调用 此module 进行配置解析
module_obj = module_instance(self.sys_argvs,self.db_models,self.settings)
module_obj.syntax_parser(section_name,mod_name,mod_data )
else:
exit("module [%s] is not exist" % base_mod_name)
#print(" ",mod_name)
#for state_item in mod_data:
# print("\t",state_item) except IndexError as e:
exit("state file must be provided after -f") else:
exit("statefile must be specified.")

user

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:luoahong
from Arya.backends.base_module import BaseSaltModule class User(BaseSaltModule):
def uid(self,*args,**kwargs):
pass
def gid(self,*args,**kwargs):
pass
def shell(self,*args,**kwargs):
pass
def home(self,*args,**kwargs):
pass class UbuntuUser(User):
def home(self,*args,**kwargs):
print('in ubnutn home ')

三、调用逻辑图

四、流程解析

1、salt开始
2、utils命令分发器

把不同的命令分发到不同的模块
怎么样才能把不同的命令分发给不同的模块
通过actions_list对应着不同的模块

3、actions
4、 'state':state.State对应着 state模块

1、加载load_state_files
2、解析
3、创建一个任务扔到MO

    1. 根据字符串把plugins里面的组件一个个的加载出来
    2. 不同的操作系统的语法是不一样
    3. 如果没有进行特殊处理,就调通用模块
    4. 如果有特殊处理,就用相同的模块处理
    5. 通用类的好处

saltstack主机管理项目:今日总结(六)的更多相关文章

  1. saltstack主机管理项目:主机管理项目架构设计(二)

    1.salt架构图 https://docs.saltstack.com/en/getstarted/system/plugins.html plug-ins(左边):场景可插拔 subsystem- ...

  2. saltstack主机管理项目【day23】:主机管理项目需求分析-设计

    本节内容 一. 主机管理项目需求分析 二 .主机管理项目架构设计 三.主机管理项目初始构建 四. 主机管理项目编主机分发器 一. 主机管理项目需求分析 场景:我现在又一台裸机要实现一下人物 配置管理: ...

  3. saltstack主机管理项目【day39】:主机管理项目开发

    项目目标 salt state.apply -h "ubuntu,centos" -g "ubuntu,centos" -f "ubuntu,cent ...

  4. saltstack主机管理项目:主机管理项目需求分析(一)

    1.场景: 我现在又一台裸机要实现一下任务 2.配置管理: 1.装上nginx,mysql 2.nginx用我指定的配置文件 3.mysql用户 4.设置一个默认的数据库访问权限 5.启动mysql ...

  5. saltstack主机管理项目:编写插件基类-获取主机列表-提取yaml配置文件(四)

    一.编写插件基类 1.目录结构 1.我是如何获知我有多少种系统? 当客户端第一连接过来的时候,我就已经把这些文件存下来了 ,存在到哪里了?存到数据库了 每次对主机发送命令的动作时,我从库里把数据取出来 ...

  6. saltstack主机管理项目:计主机管理项目命令分发器(三)

    一.开发目标命令格式如下: 二.目录结构 三.代码注解 01.salt.py 只是一个入口,没干什么事情 #!/usr/bin/env python # -*- coding:utf-8 -*- # ...

  7. saltstack主机管理项目:动态调用插件解析-模块解析(五)

    一.动态调用插件解析 1.目录结构 1.base_module代码解析: def syntax_parser(self,section_name,mod_name,mod_data): print(& ...

  8. 【主机管理项目】-(models.py(一对多、多对多数据库创建代码))

    # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class U ...

  9. 构建微服务开发环境7————使用Github管理项目代码的版本

    [内容指引] 1.注册GitHub帐号: 2.下载Github Desktop客户端: 3.macOS安装Github Desktop客户端: 4.windows安装Github Desktop客户端 ...

随机推荐

  1. Cherrypy文件上传非ASCII文件名乱码问题解决

    Cherrypy 版本: 18.0.1 由于某些特殊原因(可能是与标准兼容的问题),Cherrypy对上传文件的原文件名使用 ISO-8859-1 编码方式解码,导致非 ASCII 的文件名显示为乱码 ...

  2. SQLServer之创建索引视图

    索引视图创建注意事项 对视图创建的第一个索引必须是唯一聚集索引. 创建唯一聚集索引后,可以创建更多非聚集索引. 为视图创建唯一聚集索引可以提高查询性能,因为视图在数据库中的存储方式与具有聚集索引的表的 ...

  3. the security settings could not be applied to the database(mysql安装error)【简记】

    在安装mysql时,出现“The security settings could not be applied to the database because the connection has f ...

  4. Windows Server 2012 R2 配置FTP服务器

    Windows Server 2012 R2 安装IIS参考上一篇配置IIS 8.0:https://www.cnblogs.com/aq-ry/p/9329310.html 搭建完IIS 后,最近又 ...

  5. virtualenvwrapper 虚拟环境的使用 和 python 安装源的更改

    virtualenvwrapper 虚拟环境的使用 鉴于virtualenv不便于对虚拟环境集中管理,所以推荐直接使用virtualenvwrapper. virtualenvwrapper提供了一系 ...

  6. DeveloperGuide Hive UDF

    Creating Custom UDFs First, you need to create a new class that extends UDF, with one or more method ...

  7. Linux安装python2.7

    一.Python安装 以Python-2.7.7为例,安装包:Python-2.7.7.tgz如无特殊说明,以下安装步骤都采用root用户执行 1. 解压Python-2.7.7.tgz tar -x ...

  8. 学号 20175329 2018-2019-3《Java程序设计》第六周学习总结

    学号 20175329 2018-2019-3<Java程序设计>第六周学习总结 教材学习内容 第七章 内部类与异常类 内部类与外嵌类之间的重要关系如下: 内部类的外嵌类的成员变量在内部类 ...

  9. android9.0系统适配遇到的问题

    一.apk在9.0以下的系统上安装运行,没有问题.但是在9.0系统上运行会弹出一个框 解决办法: private void closeAndroidPDialog() { try { Class aC ...

  10. 8个Python高效数据分析的技巧

    一行代码定义List 下面是使用For循环创建列表和用一行代码创建列表的对比. x = [1,2,3,4] out = [] for item in x: out.append(item**2) pr ...