浅聊ansible的幂等 file模块源码解析

描述#

  幂等性是在实际应用中经常需要考虑的概念,尤其是运维中。相较于将幂等性理解为各种异常情况的综合处理,将其理解为执行时需要考虑到在前次执行产生的影响的情况下能够正常执行则会更加容易接近业务需求。
  ansible包含众多的模块,大部分内置模块都能够保证操作的幂等性,即相关操作的多次执行能够达到相同结果这一特性,不会出现多次执行带来副作用的影响。但是也有不满足幂等原则的,比如shell模块、raw模块、command模块。

幂等操作和非幂等操作的对比

场景说明:
比如实现删除一个临时性的文件/root/testfile的操作,如果希望其在相同的条件下,多次执行能够保持相同的结果和不会带来其它副作用,至少需要保证此操作在/root/testfile文件存在和不存在的情况下都能正常动作。

# 当采用raw模块执行shell命令删除文件,第一次删除是成功,当执行第二次删除也是成功的,但是在生产环境这结果是不理想的,比如重启一个服务,你会随便重启服务吗?

[root@Server-1~]# touch /root/testfile
[root@Server-1~]# ansible localhost -m shell -a "rm -rf testfile"
localhost | CHANGED | rc=0 >>
[root@Server-1~]# ansible localhost -m shell -a "rm -rf testfile"
localhost | CHANGED | rc=0 >>

# 当采用file 模块执行删除文件,第一次执行删除文件成功changed: true,多次执行删除文件都是同一样的结果,不会带来副作用的影响changed: Fasle

[root@Server-1~]# touch /root/testfile
[root@Server-1~]# ansible localhost -m file -a "path=/root/testfile state=absent"
localhost | CHANGED => {"changed": true, "path": "/root/testfile", "state": "absent"
}
[root@Server-1~]# ansible localhost -m file -a "path=/root/testfile state=absent"
localhost | SUCCESS => {"changed": false, "path": "/root/testfile", "state": "absent"
}
那file模块是如何实现幂等的呢?如下是file模块执行absent文件时的代码(有中文注释)

vim /usr/lib/python2.7/site-packages/ansible/modules/files/file.py
.....
def get_state(path):''' Find out current state '''b_path = to_bytes(path, errors='surrogate_or_strict')try:if os.path.lexists(b_path): # 如果文件存在返回file,文件不存在返回absentif os.path.islink(b_path):return 'link'elif os.path.isdir(b_path):return 'directory'elif os.stat(b_path).st_nlink > 1:return 'hard'# could be many other things, but defaulting to filereturn 'file' return 'absent'except OSError as e:if e.errno == errno.ENOENT:  # It may already have been removedreturn 'absent'else:raisedef ensure_absent(path):b_path = to_bytes(path, errors='surrogate_or_strict')prev_state = get_state(b_path) # 获取文件的状态result = {}if prev_state != 'absent': # 当prev_state='directory' or 'file' 为真diff = initial_diff(path, 'absent', prev_state)if not module.check_mode:if prev_state == 'directory': # 如果prev_state='directory', 则删除目录try:shutil.rmtree(b_path, ignore_errors=False)except Exception as e:raise AnsibleModuleError(results={'msg': "rmtree failed: %s" % to_native(e)})else:try:os.unlink(b_path) # 如果prev_state='file', 则删除文件except OSError as e:if e.errno != errno.ENOENT:  # It may already have been removedraise AnsibleModuleError(results={'msg': "unlinking failed: %s " % to_native(e),'path': path})result.update({'path': path, 'changed': True, 'diff': diff, 'state': 'absent'}) # 删除文件成功,动作有改变,changed=Trueelse:result.update({'path': path, 'changed': False, 'state': 'absent'}) # 如果prev_state='absent', 动作没有改变,changed=False, 实现多次操作执行不会有任何改变。return resultdef main():global modulemodule = AnsibleModule(argument_spec=dict(state=dict(type='str', choices=['absent', 'directory', 'file', 'hard', 'link', 'touch']),path=dict(type='path', required=True, aliases=['dest', 'name']),_original_basename=dict(type='str'),  # Internal use only, for recursive opsrecurse=dict(type='bool', default=False),force=dict(type='bool', default=False),  # Note: Should not be in file_common_args in futurefollow=dict(type='bool', default=True),  # Note: Different default than file_common_args_diff_peek=dict(type='bool'),  # Internal use only, for internal checks in the action pluginssrc=dict(type='path'),  # Note: Should not be in file_common_args in futuremodification_time=dict(type='str'),modification_time_format=dict(type='str', default='%Y%m%d%H%M.%S'),access_time=dict(type='str'),access_time_format=dict(type='str', default='%Y%m%d%H%M.%S'),),add_file_common_args=True,supports_check_mode=True,)# When we rewrite basic.py, we will do something similar to this on instantiating an AnsibleModulesys.excepthook = _ansible_excepthookadditional_parameter_handling(module.params)params = module.paramsstate = params['state']recurse = params['recurse']force = params['force']follow = params['follow']path = params['path']src = params['src']timestamps = {}timestamps['modification_time'] = keep_backward_compatibility_on_timestamps(params['modification_time'], state)timestamps['modification_time_format'] = params['modification_time_format']timestamps['access_time'] = keep_backward_compatibility_on_timestamps(params['access_time'], state)timestamps['access_time_format'] = params['access_time_format']# short-circuit for diff_peekif params['_diff_peek'] is not None:appears_binary = execute_diff_peek(to_bytes(path, errors='surrogate_or_strict'))module.exit_json(path=path, changed=False, appears_binary=appears_binary)if state == 'file':result = ensure_file_attributes(path, follow, timestamps)elif state == 'directory':result = ensure_directory(path, follow, recurse, timestamps)elif state == 'link':result = ensure_symlink(path, src, follow, force, timestamps)elif state == 'hard':result = ensure_hardlink(path, src, follow, force, timestamps)elif state == 'touch':result = execute_touch(path, follow, timestamps)elif state == 'absent': result = ensure_absent(path) # 执行删除文件时,调用方法 def ensure_absentmodule.exit_json(**result)if __name__ == '__main__':main()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/650322.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

第3章:Python 的函数和模块(基于最新版 Python3.12 编写)

文章目录 3.1 函数:编写你的代码乐曲3.1.1 什么是函数?3.1.2 如何定义函数?3.1.3 如何调用函数?3.1.4 函数的返回值3.1.5 函数的文档字符串3.1.6 默认参数值3.1.7 可变数量的参数3.1.8 局部变量和全局变量3.1.9 递归函数 3.2 模块…

蓝桥杯备赛 week 4 —— DP 背包问题

目录 🌈前言🌈: 📁 01背包问题 分析: dp数组求解: 优化:滚动数组: 📁 完全背包问题 📁 总结 🌈前言🌈: 这篇文章主…

大数据就业方向-(工作)ETL开发

上一篇文章: 大数据 - 大数据入门第一篇 | 关于大数据你了解多少?-CSDN博客 目录 🐶1.ETL概念 🐶2. ETL的用处 🐶3.ETL实现方式 🐶4. ETL体系结构 🐶5. 什么是ETL技术? &…

每日OJ题_算法_二分查找⑧_力扣LCR 173. 点名

目录 力扣LCR 173. 点名 解析代码 力扣LCR 173. 点名 LCR 173. 点名 - 力扣(LeetCode) 难度 简单 某班级 n 位同学的学号为 0 ~ n-1。点名结果记录于升序数组 records。假定仅有一位同学缺席,请返回他的学号。 示例 1: 输入: records …

力扣0087——扰乱字符串

扰乱字符串 难度:困难 题目描述 使用下面描述的算法可以扰乱字符串 s 得到字符串 t : 如果字符串的长度为 1 ,算法停止如果字符串的长度 > 1 ,执行下述步骤: 在一个随机下标处将字符串分割成两个非空的子字符串…

c# cad PromptSelectionResult批量选择 PromptEntityOptions选择单个实体介绍

一、PromptSelectionResult : 是 AutoCAD .NET API 中的一个类,位于 Autodesk.AutoCAD.EditorInput 命名空间下。它代表了用户在 AutoCAD 编辑器中进行图形对象选择操作的结果。 当你通过 Editor 类的 GetSelection() 方法(或者其他类似的方…

MySQL JSON数据类型全解析(JSON datatype and functions)

JSON(JavaScript Object Notation)是一种常见的信息交换格式,其简单易读且非常适合程序处理。MySQL从5.7版本开始支持JSON数据类型,本文对MySQL中JSON数据类型的使用进行一个总结。 目录 一、MySQL中的JSON 1.1 JSON数据格式 1.2 …

11. 发送邮件

1. 简介 Spring Boot 收发邮件最简便方式是通过 spring-boot-starter-mail。 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId> </dependency>spring-boot-starter-mail 本质…

hive - explode 用法以及练习

hive explode 的用法以及练习 一行变多行 explode 例如&#xff1a; 临时表 temp_table &#xff0c;列名为1st 1st1,2,34,5,6 变为 1 2 3 4 5 6 方式一&#xff1a;直接使用 explode select explode(split(1st,,)) from temp_table;方式二&#xff1a;使用 lateral view…

spring-boot-starter-validation常用注解

文章目录 一、使用二、常用注解三、Valid or Validated &#xff1f;四、分组校验1. 分组校验的基本概念2. 定义验证组3. 应用分组到模型4. 在控制器中使用分组5. 总结 一、使用 要使用这些注解&#xff0c;首先确保在你的 Spring Boot 应用的 pom.xml 文件中添加了 spring-bo…

Java问题排查工具集

Java 问题排查工具箱 n 默认值相关问题 l -XX:PrintFlagsFinal || jinfo -flags n 类装载相关问题 l -XX:TraceClassLoading n 应用无响应相关问题 l sar 等系统指标 l jstack [-l] [-m] Java 问题排查工具箱 n 内存相关问题 l -XX:HeapDumpOnOutOfMemoryEr…

探秘Dmail:Web3世界的通讯引领者

摘要&#xff1a;在一个充满潜力并且对创新要求严格的领域中&#xff0c;Dmail作为一种开创性的Web3通讯协议应运而生。 1月24日&#xff0c;OKX Jumpstart宣布上线Dmail&#xff0c;在Web3领域引起了巨大反响&#xff0c;这是一个旨在重新定义数字通讯范式的富有远见的项目&a…

#资源#llm训练 获取数据集的网站

llm训练需要获取数据&#xff0c;互联网上会有一些别人开源的数据集&#xff0c;我们可以拿来即用 https://github.com/huggingface/datasets https://huggingface.co/datasets 支持使用python直接调取&#xff0c;譬如squad_dataset load_datasets(“squad”)。 https://dat…

【c++学习】数据结构中的栈

c栈 栈代码用线性表实现栈用链表实现栈 栈 栈&#xff1a;先进后出 只对栈顶元素进行操作&#xff0c;包括新元素入栈、栈顶元素出栈和查看栈顶元素&#xff08;只支持对栈顶的增、删、查&#xff09;。 代码 下述代码实现了栈及其接口 包括对栈顶的增、删、查以及查看栈的大…

[足式机器人]Part2 Dr. CAN学习笔记- 最优控制Optimal Control Ch07

本文仅供学习使用 本文参考&#xff1a; B站&#xff1a;DR_CAN Dr. CAN学习笔记 - 最优控制Optimal Control Ch07-1最优控制问题与性能指标 1. 最优控制问题与性能指标2. 动态规划 Dynamic Programming2.1 基本概念2.2 代码详解2.3 简单一维案例 3. 线性二次型调节器&#xff…

Linux date命令详解:如何设置、更改、格式化和显示日期时间(附实例与注意事项)

Linux date命令介绍 date命令在Linux中用来显示和设置系统日期和时间。这个命令允许用户以不同的格式打印时间&#xff0c;也可以计算未来和过去的日期。 Linux date命令适用的Linux版本 date命令在所有主流的Linux发行版中都可以使用&#xff0c;包括但不限于Debian、Ubunt…

GIt同时存在传入和传出更改修改,无法合并

前言 Git是常用的版本管理工具&#xff0c;之前面试被问到过一次——Git有无遇到过使用错误情况&#xff1f;当时卡壳了没答上来&#xff0c;所以这次遇到&#xff0c;特此记录学习。 问题概述 前一天提交了代码&#xff0c;mt进行了修改。但我忘记拉取最新&#xff0c;就进…

bxCAN 标识符筛选

标识符筛选 在 CAN 协议中&#xff0c;消息的标识符与节点地址无关&#xff0c;但与消息内容有关。因此&#xff0c;发送器将消息广播给所有接收器。在接收到消息时&#xff0c;接收器节点会根据标识符的值来确定软件是否需要该消息。如果需要&#xff0c;该消息将复制到 SRAM…

每日一题 力扣2865 美丽塔Ⅰ

2865. 美丽塔 I 题目描述&#xff1a; 给你一个长度为 n 下标从 0 开始的整数数组 maxHeights 。 你的任务是在坐标轴上建 n 座塔。第 i 座塔的下标为 i &#xff0c;高度为 heights[i] 。 如果以下条件满足&#xff0c;我们称这些塔是 美丽 的&#xff1a; 1 < height…

QT笔记 - QToolButton triggered(QAction *)不触发问题

QToolButton 有两个功能&#xff0c;一个是基本按钮功能&#xff0c;同QPushButton一样&#xff0c;发出clicked()信号。 另一个功能是QAction功能&#xff0c;发出触发triggered(QAction *)信号&#xff0c;但它自己不包含QAction&#xff0c;需要同其它比如QMenu或QToolBar上…